repo
stringlengths 2
99
| file
stringlengths 14
239
| code
stringlengths 20
3.99M
| file_length
int64 20
3.99M
| avg_line_length
float64 9.73
128
| max_line_length
int64 11
86.4k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
cowrie | cowrie-master/src/cowrie/output/malshare.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
"""
Send files to https://malshare.com/
More info https://malshare.com/doc.php
"""
from __future__ import annotations
import os
from urllib.parse import urlparse
import requests
from twisted.python import log
import cowrie.core.output
from cowrie.core.config import CowrieConfig
class Output(cowrie.core.output.Output):
"""
malshare output
TODO: use `treq`
"""
apiKey: str
def start(self):
"""
Start output plugin
"""
self.apiKey = CowrieConfig.get("output_malshare", "api_key")
def stop(self):
"""
Stop output plugin
"""
pass
def write(self, entry):
if entry["eventid"] == "cowrie.session.file_download":
p = urlparse(entry["url"]).path
if p == "":
fileName = entry["shasum"]
else:
b = os.path.basename(p)
if b == "":
fileName = entry["shasum"]
else:
fileName = b
self.postfile(entry["outfile"], fileName)
elif entry["eventid"] == "cowrie.session.file_upload":
self.postfile(entry["outfile"], entry["filename"])
def postfile(self, artifact, fileName):
"""
Send a file to MalShare
"""
try:
res = requests.post(
"https://malshare.com/api.php?api_key="
+ self.apiKey
+ "&action=upload",
files={"upload": open(artifact, "rb")},
)
if res and res.ok:
log.msg("Submitted to MalShare")
else:
log.msg(f"MalShare Request failed: {res.status_code}")
except Exception as e:
log.msg(f"MalShare Request failed: {e}")
| 3,275 | 31.117647 | 75 | py |
cowrie | cowrie-master/src/cowrie/output/s3.py | """
Send downloaded/uplaoded files to S3 (or compatible)
"""
from __future__ import annotations
from typing import Any
from configparser import NoOptionError
from botocore.exceptions import ClientError
from botocore.session import get_session
from twisted.internet import defer, threads
from twisted.python import log
import cowrie.core.output
from cowrie.core.config import CowrieConfig
class Output(cowrie.core.output.Output):
"""
s3 output
"""
def start(self) -> None:
self.bucket = CowrieConfig.get("output_s3", "bucket")
self.seen: set[str] = set()
self.session = get_session()
try:
if CowrieConfig.get("output_s3", "access_key_id") and CowrieConfig.get(
"output_s3", "secret_access_key"
):
self.session.set_credentials(
CowrieConfig.get("output_s3", "access_key_id"),
CowrieConfig.get("output_s3", "secret_access_key"),
)
except NoOptionError:
log.msg(
"No AWS credentials found in config - using botocore global settings."
)
self.client = self.session.create_client(
"s3",
region_name=CowrieConfig.get("output_s3", "region"),
endpoint_url=CowrieConfig.get("output_s3", "endpoint", fallback=None),
verify=CowrieConfig.getboolean("output_s3", "verify", fallback=True),
)
def stop(self) -> None:
pass
def write(self, entry: dict[str, Any]) -> None:
if entry["eventid"] == "cowrie.session.file_download":
self.upload(entry["shasum"], entry["outfile"])
elif entry["eventid"] == "cowrie.session.file_upload":
self.upload(entry["shasum"], entry["outfile"])
@defer.inlineCallbacks
def _object_exists_remote(self, shasum):
try:
yield threads.deferToThread(
self.client.head_object,
Bucket=self.bucket,
Key=shasum,
)
except ClientError as e:
if e.response["Error"]["Code"] == "404":
defer.returnValue(False)
raise
defer.returnValue(True)
@defer.inlineCallbacks
def upload(self, shasum, filename):
if shasum in self.seen:
log.msg(f"Already uploaded file with sha {shasum} to S3")
return
exists = yield self._object_exists_remote(shasum)
if exists:
log.msg(f"Somebody else already uploaded file with sha {shasum} to S3")
self.seen.add(shasum)
return
log.msg(f"Uploading file with sha {shasum} ({filename}) to S3")
with open(filename, "rb") as fp:
yield threads.deferToThread(
self.client.put_object,
Bucket=self.bucket,
Key=shasum,
Body=fp.read(),
ContentType="application/octet-stream",
)
self.seen.add(shasum)
| 3,019 | 29.505051 | 86 | py |
cowrie | cowrie-master/src/cowrie/output/socketlog.py | from __future__ import annotations
import json
import socket
import cowrie.core.output
from cowrie.core.config import CowrieConfig
class Output(cowrie.core.output.Output):
"""
socketlog output
"""
def start(self):
self.timeout = CowrieConfig.getint("output_socketlog", "timeout")
addr = CowrieConfig.get("output_socketlog", "address")
self.host = addr.split(":")[0]
self.port = int(addr.split(":")[1])
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(self.timeout)
self.sock.connect((self.host, self.port))
def stop(self):
self.sock.close()
def write(self, logentry):
for i in list(logentry.keys()):
# Remove twisted 15 legacy keys
if i.startswith("log_"):
del logentry[i]
message = json.dumps(logentry) + "\n"
try:
self.sock.sendall(message.encode())
except OSError as ex:
if ex.errno == 32: # Broken pipe
self.start()
self.sock.sendall(message.encode())
else:
raise
| 1,156 | 25.906977 | 73 | py |
cowrie | cowrie-master/src/cowrie/output/greynoise.py | """
Send attackers IP to GreyNoise
"""
from __future__ import annotations
import treq
from twisted.internet import defer, error
from twisted.python import log
import cowrie.core.output
from cowrie.core.config import CowrieConfig
COWRIE_USER_AGENT = "Cowrie Honeypot"
GNAPI_URL = "https://api.greynoise.io/v3/community/"
class Output(cowrie.core.output.Output):
"""
greynoise output
"""
def start(self):
"""
Start output plugin
"""
self.apiKey = CowrieConfig.get("output_greynoise", "api_key", fallback=None)
self.debug = CowrieConfig.getboolean(
"output_greynoise", "debug", fallback=False
)
def stop(self):
"""
Stop output plugin
"""
pass
def write(self, entry):
if entry["eventid"] == "cowrie.session.connect":
self.scanip(entry)
@defer.inlineCallbacks
def scanip(self, entry):
"""
Scan IP against GreyNoise API
"""
def message(query):
if query["noise"]:
log.msg(
eventid="cowrie.greynoise.result",
session=entry["session"],
format=f"GreyNoise: {query['ip']} has been observed scanning the Internet. GreyNoise "
f"classification is {query['classification']} and the believed owner is {query['name']}",
)
if query["riot"]:
log.msg(
eventid="cowrie.greynoise.result",
session=entry["session"],
format=f"GreyNoise: {query['ip']} belongs to a benign service or provider. "
f"The owner is {query['name']}.",
)
gn_url = f"{GNAPI_URL}{entry['src_ip']}".encode()
headers = {"User-Agent": [COWRIE_USER_AGENT], "key": self.apiKey}
try:
response = yield treq.get(url=gn_url, headers=headers, timeout=10)
except (
defer.CancelledError,
error.ConnectingCancelledError,
error.DNSLookupError,
):
log.msg("GreyNoise requests timeout")
return
if response.code == 404:
rsp = yield response.json()
log.err(f"GreyNoise: {rsp['ip']} - {rsp['message']}")
return
if response.code != 200:
rsp = yield response.text()
log.err(f"GreyNoise: got error {rsp}")
return
j = yield response.json()
if self.debug:
log.msg("GreyNoise: debug: " + repr(j))
if j["message"] == "Success":
message(j)
else:
log.msg("GreyNoise: no results for for IP {}".format(entry["src_ip"]))
| 2,749 | 27.947368 | 109 | py |
cowrie | cowrie-master/src/cowrie/core/checkers.py |
"""
This module contains ...
"""
from __future__ import annotations
from sys import modules
from zope.interface import implementer
from twisted.conch import error
from twisted.conch.ssh import keys
from twisted.cred.checkers import ICredentialsChecker
from twisted.cred.credentials import ISSHPrivateKey
from twisted.cred.error import UnauthorizedLogin, UnhandledCredentials
from twisted.internet import defer
from twisted.python import failure, log
from cowrie.core import auth
from cowrie.core import credentials as conchcredentials
from cowrie.core.config import CowrieConfig
@implementer(ICredentialsChecker)
class HoneypotPublicKeyChecker:
"""
Checker that accepts, logs and denies public key authentication attempts
"""
credentialInterfaces = (ISSHPrivateKey,)
def requestAvatarId(self, credentials):
_pubKey = keys.Key.fromString(credentials.blob)
log.msg(
eventid="cowrie.client.fingerprint",
format="public key attempt for user %(username)s of type %(type)s with fingerprint %(fingerprint)s",
username=credentials.username,
fingerprint=_pubKey.fingerprint(),
key=_pubKey.toString("OPENSSH"),
type=_pubKey.sshType(),
)
return failure.Failure(error.ConchError("Incorrect signature"))
@implementer(ICredentialsChecker)
class HoneypotNoneChecker:
"""
Checker that does no authentication check
"""
credentialInterfaces = (conchcredentials.IUsername,)
def requestAvatarId(self, credentials):
return defer.succeed(credentials.username)
@implementer(ICredentialsChecker)
class HoneypotPasswordChecker:
"""
Checker that accepts "keyboard-interactive" and "password"
"""
credentialInterfaces = (
conchcredentials.IUsernamePasswordIP,
conchcredentials.IPluggableAuthenticationModulesIP,
)
def requestAvatarId(self, credentials):
if hasattr(credentials, "password"):
if self.checkUserPass(
credentials.username, credentials.password, credentials.ip
):
return defer.succeed(credentials.username)
return defer.fail(UnauthorizedLogin())
if hasattr(credentials, "pamConversion"):
return self.checkPamUser(
credentials.username, credentials.pamConversion, credentials.ip
)
return defer.fail(UnhandledCredentials())
def checkPamUser(self, username, pamConversion, ip):
r = pamConversion((("Password:", 1),))
return r.addCallback(self.cbCheckPamUser, username, ip)
def cbCheckPamUser(self, responses, username, ip):
for (response, _) in responses:
if self.checkUserPass(username, response, ip):
return defer.succeed(username)
return defer.fail(UnauthorizedLogin())
def checkUserPass(self, theusername: bytes, thepassword: bytes, ip: str) -> bool:
# UserDB is the default auth_class
authname = auth.UserDB
# Is the auth_class defined in the config file?
if CowrieConfig.has_option("honeypot", "auth_class"):
authclass = CowrieConfig.get("honeypot", "auth_class")
authmodule = "cowrie.core.auth"
# Check if authclass exists in this module
if hasattr(modules[authmodule], authclass):
authname = getattr(modules[authmodule], authclass)
else:
log.msg(f"auth_class: {authclass} not found in {authmodule}")
theauth = authname()
if theauth.checklogin(theusername, thepassword, ip):
log.msg(
eventid="cowrie.login.success",
format="login attempt [%(username)s/%(password)s] succeeded",
username=theusername,
password=thepassword,
)
return True
log.msg(
eventid="cowrie.login.failed",
format="login attempt [%(username)s/%(password)s] failed",
username=theusername,
password=thepassword,
)
return False
| 4,224 | 32.007813 | 112 | py |
cowrie | cowrie-master/src/cowrie/core/auth.py |
"""
This module contains authentication code
"""
from __future__ import annotations
import json
import re
from collections import OrderedDict
from os import path
from random import randint
from typing import Any, Union
from re import Pattern
from twisted.python import log
from cowrie.core.config import CowrieConfig
_USERDB_DEFAULTS: list[str] = [
"root:x:!root",
"root:x:!123456",
"root:x:!/honeypot/i",
"root:x:*",
"phil:x:*",
"phil:x:fout",
]
class UserDB:
"""
By Walter de Jong <walter@sara.nl>
"""
def __init__(self) -> None:
self.userdb: dict[
tuple[Union[Pattern[bytes], bytes], Union[Pattern[bytes], bytes]], bool
] = OrderedDict()
self.load()
def load(self) -> None:
"""
load the user db
"""
dblines: list[str]
try:
with open(
"{}/userdb.txt".format(CowrieConfig.get("honeypot", "etc_path")),
encoding="ascii",
) as db:
dblines = db.readlines()
except OSError:
log.msg("Could not read etc/userdb.txt, default database activated")
dblines = _USERDB_DEFAULTS
for user in dblines:
if not user.startswith("#"):
try:
login = user.split(":")[0].encode("utf8")
password = user.split(":")[2].strip().encode("utf8")
except IndexError:
continue
else:
self.adduser(login, password)
def checklogin(
self, thelogin: bytes, thepasswd: bytes, src_ip: str = "0.0.0.0"
) -> bool:
for credentials, policy in self.userdb.items():
login: Union[bytes, Pattern[bytes]]
passwd: Union[bytes, Pattern[bytes]]
login, passwd = credentials
if self.match_rule(login, thelogin):
if self.match_rule(passwd, thepasswd):
return policy
return False
def match_rule(
self, rule: Union[bytes, Pattern[bytes]], data: bytes
) -> Union[bool, bytes]:
if isinstance(rule, bytes):
return rule in [b"*", data]
return bool(rule.search(data))
def re_or_bytes(self, rule: bytes) -> Union[Pattern[bytes], bytes]:
"""
Convert a /.../ type rule to a regex, otherwise return the string as-is
@param login: rule
@type login: bytes
"""
res = re.match(rb"/(.+)/(i)?$", rule)
if res:
return re.compile(res.group(1), re.IGNORECASE if res.group(2) else 0)
return rule
def adduser(self, login: bytes, passwd: bytes) -> None:
"""
All arguments are bytes
@param login: user id
@type login: bytes
@param passwd: password
@type passwd: bytes
"""
user = self.re_or_bytes(login)
if passwd[0] == ord("!"):
policy = False
passwd = passwd[1:]
else:
policy = True
p = self.re_or_bytes(passwd)
self.userdb[(user, p)] = policy
class AuthRandom:
"""
Alternative class that defines the checklogin() method.
Users will be authenticated after a random number of attempts.
"""
def __init__(self) -> None:
# Default values
self.mintry: int = 2
self.maxtry: int = 5
self.maxcache: int = 10
# Are there auth_class parameters?
if CowrieConfig.has_option("honeypot", "auth_class_parameters"):
parameters: str = CowrieConfig.get("honeypot", "auth_class_parameters")
parlist: list[str] = parameters.split(",")
if len(parlist) == 3:
self.mintry = int(parlist[0])
self.maxtry = int(parlist[1])
self.maxcache = int(parlist[2])
if self.maxtry < self.mintry:
self.maxtry = self.mintry + 1
log.msg(f"maxtry < mintry, adjusting maxtry to: {self.maxtry}")
self.uservar: dict[Any, Any] = {}
self.uservar_file: str = "{}/auth_random.json".format(
CowrieConfig.get("honeypot", "state_path")
)
self.loadvars()
def loadvars(self) -> None:
"""
Load user vars from json file
"""
if path.isfile(self.uservar_file):
with open(self.uservar_file, encoding="utf-8") as fp:
try:
self.uservar = json.load(fp)
except Exception:
self.uservar = {}
def savevars(self) -> None:
"""
Save the user vars to json file
"""
data = self.uservar
# Note: this is subject to races between cowrie logins
with open(self.uservar_file, "w", encoding="utf-8") as fp:
json.dump(data, fp)
def checklogin(self, thelogin: bytes, thepasswd: bytes, src_ip: str) -> bool:
"""
Every new source IP will have to try a random number of times between
'mintry' and 'maxtry' before succeeding to login.
All username/password combinations must be different.
The successful login combination is stored with the IP address.
Successful username/passwords pairs are also cached for 'maxcache' times.
This is to allow access for returns from different IP addresses.
Variables are saved in 'uservar.json' in the data directory.
"""
auth: bool = False
userpass: str = str(thelogin) + ":" + str(thepasswd)
if "cache" not in self.uservar:
self.uservar["cache"] = []
cache = self.uservar["cache"]
# Check if it is the first visit from src_ip
if src_ip not in self.uservar:
self.uservar[src_ip] = {}
ipinfo = self.uservar[src_ip]
ipinfo["try"] = 0
if userpass in cache:
log.msg(f"first time for {src_ip}, found cached: {userpass}")
ipinfo["max"] = 1
ipinfo["user"] = str(thelogin)
ipinfo["pw"] = str(thepasswd)
auth = True
self.savevars()
return auth
ipinfo["max"] = randint(self.mintry, self.maxtry)
log.msg("first time for {}, need: {}".format(src_ip, ipinfo["max"]))
else:
if userpass in cache:
ipinfo = self.uservar[src_ip]
log.msg(f"Found cached: {userpass}")
ipinfo["max"] = 1
ipinfo["user"] = str(thelogin)
ipinfo["pw"] = str(thepasswd)
auth = True
self.savevars()
return auth
ipinfo = self.uservar[src_ip]
# Fill in missing variables
if "max" not in ipinfo:
ipinfo["max"] = randint(self.mintry, self.maxtry)
if "try" not in ipinfo:
ipinfo["try"] = 0
if "tried" not in ipinfo:
ipinfo["tried"] = []
# Don't count repeated username/password combinations
if userpass in ipinfo["tried"]:
log.msg("already tried this combination")
self.savevars()
return auth
ipinfo["try"] += 1
attempts: int = ipinfo["try"]
need: int = ipinfo["max"]
log.msg(f"login attempt: {attempts}")
# Check if enough login attempts are tried
if attempts < need:
self.uservar[src_ip]["tried"].append(userpass)
elif attempts == need:
ipinfo["user"] = str(thelogin)
ipinfo["pw"] = str(thepasswd)
cache.append(userpass)
if len(cache) > self.maxcache:
cache.pop(0)
auth = True
# Returning after successful login
elif attempts > need:
if "user" not in ipinfo or "pw" not in ipinfo:
log.msg("return, but username or password not set!!!")
ipinfo["tried"].append(userpass)
ipinfo["try"] = 1
else:
log.msg(
"login return, expect: [{}/{}]".format(ipinfo["user"], ipinfo["pw"])
)
if thelogin == ipinfo["user"] and str(thepasswd) == ipinfo["pw"]:
auth = True
self.savevars()
return auth
| 8,448 | 31.003788 | 88 | py |
cowrie | cowrie-master/src/cowrie/core/credentials.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
from collections.abc import Callable
from zope.interface import implementer
from twisted.cred.credentials import ICredentials, IUsernamePassword
class IUsername(ICredentials):
"""
Encapsulate username only
@type username: C{str}
@ivar username: The username associated with these credentials.
"""
class IUsernamePasswordIP(IUsernamePassword):
"""
I encapsulate a username, a plaintext password and a source IP
@type username: C{str}
@ivar username: The username associated with these credentials.
@type password: C{str}
@ivar password: The password associated with these credentials.
@type ip: C{str}
@ivar ip: The source ip address associated with these credentials.
"""
class IPluggableAuthenticationModulesIP(ICredentials):
"""
Twisted removed IPAM in 15, adding in Cowrie now
"""
@implementer(IPluggableAuthenticationModulesIP)
class PluggableAuthenticationModulesIP:
"""
Twisted removed IPAM in 15, adding in Cowrie now
"""
def __init__(self, username: str, pamConversion: Callable, ip: str) -> None:
self.username: str = username
self.pamConversion: Callable = pamConversion
self.ip: str = ip
@implementer(IUsername)
class Username:
def __init__(self, username: str):
self.username: str = username
@implementer(IUsernamePasswordIP)
class UsernamePasswordIP:
"""
This credential interface also provides an IP address
"""
def __init__(self, username: str, password: str, ip: str) -> None:
self.username: str = username
self.password: str = password
self.ip: str = ip
def checkPassword(self, password: str) -> bool:
return self.password == password
| 3,261 | 31.949495 | 80 | py |
cowrie | cowrie-master/src/cowrie/core/utils.py | # -*- test-case-name: cowrie.test.utils -*-
from __future__ import annotations
import configparser
from typing import BinaryIO
from twisted.application import internet
from twisted.internet import endpoints
def durationHuman(duration: float) -> str:
"""
Turn number of seconds into human readable string
"""
seconds: int = int(round(duration))
minutes: int
minutes, seconds = divmod(seconds, 60)
hours: int
hours, minutes = divmod(minutes, 60)
days: float
days, hours = divmod(hours, 24)
years: float
years, days = divmod(days, 365.242199)
syears: str = str(years)
sseconds: str = str(seconds).rjust(2, "0")
sminutes: str = str(minutes).rjust(2, "0")
shours: str = str(hours).rjust(2, "0")
sduration: list[str] = []
if years > 0:
sduration.append("{} year{} ".format(syears, "s" * (years != 1)))
else:
if days > 0:
sduration.append("{} day{} ".format(days, "s" * (days != 1)))
if hours > 0:
sduration.append(f"{shours}:")
if minutes >= 0:
sduration.append(f"{sminutes}:")
if seconds >= 0:
sduration.append(f"{sseconds}")
return "".join(sduration)
def tail(the_file: BinaryIO, lines_2find: int = 20) -> list[bytes]:
"""
From http://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail
"""
lines_found: int = 0
total_bytes_scanned: int = 0
the_file.seek(0, 2)
bytes_in_file: int = the_file.tell()
while lines_2find + 1 > lines_found and bytes_in_file > total_bytes_scanned:
byte_block: int = min(1024, bytes_in_file - total_bytes_scanned)
the_file.seek(-(byte_block + total_bytes_scanned), 2)
total_bytes_scanned += byte_block
lines_found += the_file.read(1024).count(b"\n")
the_file.seek(-total_bytes_scanned, 2)
line_list: list[bytes] = list(the_file.readlines())
return line_list[-lines_2find:]
# We read at least 21 line breaks from the bottom, block by block for speed
# 21 to ensure we don't get a half line
def uptime(total_seconds: float) -> str:
"""
Gives a human-readable uptime string
Thanks to http://thesmithfam.org/blog/2005/11/19/python-uptime-script/
(modified to look like the real uptime command)
"""
total_seconds = float(total_seconds)
# Helper vars:
MINUTE: int = 60
HOUR: int = MINUTE * 60
DAY: int = HOUR * 24
# Get the days, hours, etc:
days: int = int(total_seconds / DAY)
hours: int = int((total_seconds % DAY) / HOUR)
minutes: int = int((total_seconds % HOUR) / MINUTE)
# 14 days, 3:53
# 11 min
s: str = ""
if days > 0:
s += str(days) + " " + (days == 1 and "day" or "days") + ", "
if len(s) > 0 or hours > 0:
s += "{}:{}".format(str(hours).rjust(2), str(minutes).rjust(2, "0"))
else:
s += f"{minutes!s} min"
return s
def get_endpoints_from_section(
cfg: configparser.ConfigParser, section: str, default_port: int
) -> list[str]:
listen_addr: str
listen_port: int
listen_endpoints: list[str] = []
if cfg.has_option(section, "listen_endpoints"):
return cfg.get(section, "listen_endpoints").split()
if cfg.has_option(section, "listen_addr"):
listen_addr = cfg.get(section, "listen_addr")
else:
listen_addr = "0.0.0.0"
if cfg.has_option(section, "listen_port"):
listen_port = cfg.getint(section, "listen_port")
else:
listen_port = default_port
for i in listen_addr.split():
listen_endpoints.append(f"tcp:{listen_port}:interface={i}")
return listen_endpoints
def create_endpoint_services(reactor, parent, listen_endpoints, factory):
for listen_endpoint in listen_endpoints:
endpoint = endpoints.serverFromString(reactor, listen_endpoint)
service = internet.StreamServerEndpointService(endpoint, factory)
# FIXME: Use addService on parent ?
service.setServiceParent(parent)
| 4,153 | 30 | 105 | py |
cowrie | cowrie-master/src/cowrie/core/realm.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
from zope.interface import implementer
from twisted.conch.interfaces import IConchUser
from twisted.conch.telnet import ITelnetProtocol
from twisted.cred.portal import IRealm
from cowrie.shell import avatar as shellavatar
from cowrie.shell import server as shellserver
from cowrie.telnet import session
@implementer(IRealm)
class HoneyPotRealm:
def __init__(self) -> None:
pass
def requestAvatar(self, avatarId, _mind, *interfaces):
user: IConchUser
if IConchUser in interfaces:
serv = shellserver.CowrieServer(self)
user = shellavatar.CowrieUser(avatarId, serv)
return interfaces[0], user, user.logout
if ITelnetProtocol in interfaces:
serv = shellserver.CowrieServer(self)
user = session.HoneyPotTelnetSession(avatarId, serv)
return interfaces[0], user, user.logout
raise NotImplementedError
| 2,435 | 41 | 75 | py |
cowrie | cowrie-master/src/cowrie/core/artifact.py |
"""
This module contains code to handling saving of honeypot artifacts
These will typically be files uploaded to the honeypot and files
downloaded inside the honeypot, or input being piped in.
Code behaves like a normal Python file handle.
Example:
with Artifact(name) as f:
f.write("abc")
or:
g = Artifact("testme2")
g.write("def")
g.close()
"""
from __future__ import annotations
import hashlib
import os
import tempfile
from types import TracebackType
from typing import Any, Optional
from twisted.python import log
from cowrie.core.config import CowrieConfig
class Artifact:
artifactDir: str = CowrieConfig.get("honeypot", "download_path")
def __init__(self, label: str) -> None:
self.label: str = label
self.fp = tempfile.NamedTemporaryFile(dir=self.artifactDir, delete=False) # pylint: disable=R1732
self.tempFilename = self.fp.name
self.closed: bool = False
self.shasum: str = ""
self.shasumFilename: str = ""
def __enter__(self) -> Any:
return self.fp
def __exit__(
self,
etype: Optional[type[BaseException]],
einst: Optional[BaseException],
etrace: Optional[TracebackType],
) -> bool:
self.close()
return True
def write(self, data: bytes) -> None:
self.fp.write(data)
def fileno(self) -> Any:
return self.fp.fileno()
def close(self, keepEmpty: bool = False) -> Optional[tuple[str, str]]:
size: int = self.fp.tell()
if size == 0 and not keepEmpty:
os.remove(self.fp.name)
return None
self.fp.seek(0)
data = self.fp.read()
self.fp.close()
self.closed = True
self.shasum = hashlib.sha256(data).hexdigest()
self.shasumFilename = os.path.join(self.artifactDir, self.shasum)
if os.path.exists(self.shasumFilename):
log.msg("Not storing duplicate content " + self.shasum)
os.remove(self.fp.name)
else:
os.rename(self.fp.name, self.shasumFilename)
umask = os.umask(0)
os.umask(umask)
os.chmod(self.shasumFilename, 0o666 & ~umask)
return self.shasum, self.shasumFilename
| 2,319 | 24.217391 | 106 | py |
cowrie | cowrie-master/src/cowrie/core/cef.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# cowrie.client.fingerprint
# cowrie.client.size
# cowrie.client.var
# cowrie.client.version
# cowrie.direct-tcpip.data
# cowrie.direct-tcpip.request
# cowrie.log.closed
# cowrie.login.failed
# cowrie.login.success
# cowrie.session.closed
# cowrie.session.connect
# cowrie.session.file_download
# cowrie.session.file_upload
from __future__ import annotations
def formatCef(logentry: dict[str, str]) -> str:
"""
Take logentry and turn into CEF string
"""
# Jan 18 11:07:53 host CEF:Version|Device Vendor|Device Product|
# Device Version|Signature ID|Name|Severity|[Extension]
cefVendor = "Cowrie"
cefProduct = "Cowrie"
cefVersion = "1.0"
cefSignature = logentry["eventid"]
cefName = logentry["eventid"]
cefSeverity = "5"
cefExtensions = {
"app": "SSHv2",
"destinationServicename": "sshd",
"deviceExternalId": logentry["sensor"],
"msg": logentry["message"],
"src": logentry["src_ip"],
"proto": "tcp",
}
if logentry["eventid"] == "cowrie.session.connect":
cefExtensions["spt"] = logentry["src_port"]
cefExtensions["dpt"] = logentry["dst_port"]
cefExtensions["src"] = logentry["src_ip"]
cefExtensions["dst"] = logentry["dst_ip"]
elif logentry["eventid"] == "cowrie.login.success":
cefExtensions["duser"] = logentry["username"]
cefExtensions["outcome"] = "success"
elif logentry["eventid"] == "cowrie.login.failed":
cefExtensions["duser"] = logentry["username"]
cefExtensions["outcome"] = "failed"
elif logentry["eventid"] == "cowrie.file.file_download":
cefExtensions["filehash"] = logentry["filehash"]
cefExtensions["filePath"] = logentry["filename"]
cefExtensions["fsize"] = logentry["size"]
elif logentry["eventid"] == "cowrie.file.file_upload":
cefExtensions["filehash"] = logentry["filehash"]
cefExtensions["filePath"] = logentry["filename"]
cefExtensions["fsize"] = logentry["size"]
# 'out' 'outcome' request, rt
cefList = []
for key in list(cefExtensions.keys()):
value = str(cefExtensions[key])
cefList.append(f"{key}={value}")
cefExtension = " ".join(cefList)
cefString = (
"CEF:0|"
+ cefVendor
+ "|"
+ cefProduct
+ "|"
+ cefVersion
+ "|"
+ cefSignature
+ "|"
+ cefName
+ "|"
+ cefSeverity
+ "|"
+ cefExtension
)
return cefString
| 4,079 | 33.576271 | 75 | py |
cowrie | cowrie-master/src/cowrie/core/output.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
import abc
import re
import socket
import time
from os import environ
from typing import Any
from re import Pattern
from twisted.internet import reactor
from twisted.logger import formatTime
from cowrie.core.config import CowrieConfig
# Events:
# cowrie.client.fingerprint
# cowrie.client.size
# cowrie.client.var
# cowrie.client.version
# cowrie.direct-tcpip.data
# cowrie.direct-tcpip.request
# cowrie.log.closed
# cowrie.login.failed
# cowrie.login.success
# cowrie.session.closed
# cowrie.session.connect
# cowrie.session.file_download
# cowrie.session.file_upload
# The time is available in two formats in each event, as key 'time'
# in epoch format and in key 'timestamp' as a ISO compliant string
# in UTC.
def convert(data):
"""
This converts a nested dictionary with bytes in it to string
"""
if isinstance(data, str):
return data
if isinstance(data, dict):
return {convert(key): convert(value) for key, value in list(data.items())}
if isinstance(data, dict):
return {convert(key): convert(value) for key, value in list(data.items())}
if isinstance(data, list):
return [convert(element) for element in data]
if isinstance(data, bytes):
try:
string = data.decode("utf-8")
except UnicodeDecodeError:
string = repr(data)
return string
return data
class Output(metaclass=abc.ABCMeta):
"""
This is the abstract base class intended to be inherited by
cowrie output plugins. Plugins require the mandatory
methods: stop, start and write
"""
def __init__(self) -> None:
self.sessions: dict[str, str] = {}
self.ips: dict[str, str] = {}
# Need these for each individual transport, or else the session numbers overlap
self.sshRegex: Pattern[str] = re.compile(".*SSHTransport,([0-9]+),[0-9a-f:.]+$")
self.telnetRegex: Pattern[str] = re.compile(
".*TelnetTransport,([0-9]+),[0-9a-f:.]+$"
)
self.sensor: str = CowrieConfig.get(
"honeypot", "sensor_name", fallback=socket.gethostname()
)
self.timeFormat: str
# use Z for UTC (Zulu) time, it's shorter.
if "TZ" in environ and environ["TZ"] == "UTC":
self.timeFormat = "%Y-%m-%dT%H:%M:%S.%fZ"
else:
self.timeFormat = "%Y-%m-%dT%H:%M:%S.%f%z"
# Event trigger so that stop() is called by the reactor when stopping
reactor.addSystemEventTrigger("before", "shutdown", self.stop) # type: ignore
self.start()
def logDispatch(self, **kw: str) -> None:
"""
Use logDispatch when the HoneypotTransport prefix is not available.
Here you can explicitly set the sessionIds to tie the sessions together
"""
ev = kw
# ev["message"] = msg
self.emit(ev)
@abc.abstractmethod
def start(self) -> None:
"""
Abstract method to initialize output plugin
"""
pass
@abc.abstractmethod
def stop(self) -> None:
"""
Abstract method to shut down output plugin
"""
pass
@abc.abstractmethod
def write(self, event: dict[str, Any]) -> None:
"""
Handle a general event within the output plugin
"""
pass
def emit(self, event: dict) -> None:
"""
This is the main emit() hook that gets called by the the Twisted logging
To make this work with Cowrie, the event dictionary needs the following keys:
- 'eventid'
- 'sessionno' or 'session'
- 'message' or 'format'
"""
sessionno: str
ev: dict
# Ignore stdout and stderr in output plugins
if "printed" in event:
return
# Ignore anything without eventid
if "eventid" not in event:
return
# Ignore anything without session information
if (
"sessionno" not in event
and "session" not in event
and "system" not in event
):
return
# Ignore anything without message
if "message" not in event and "format" not in event:
return
ev: dict[str, any] = convert(event) # type: ignore
ev["sensor"] = self.sensor
if "isError" in ev:
del ev["isError"]
# Add ISO timestamp and sensor data
if "time" not in ev:
ev["time"] = time.time()
ev["timestamp"] = formatTime(ev["time"], timeFormat=self.timeFormat)
if "format" in ev and ("message" not in ev or ev["message"] == ()):
try:
ev["message"] = ev["format"] % ev
del ev["format"]
except Exception:
pass
# Explicit sessionno (from logDispatch) overrides from 'system'
if "sessionno" in ev:
sessionno = ev["sessionno"]
del ev["sessionno"]
# Maybe it's passed explicitly
elif "session" in ev:
# reverse engineer sessionno
try:
sessionno = next(
key
for key, value in self.sessions.items()
if value == ev["session"]
)
except StopIteration:
return
# Extract session id from the twisted log prefix
elif "system" in ev:
sessionno = "0"
telnetmatch = self.telnetRegex.match(ev["system"])
if telnetmatch:
sessionno = f"T{telnetmatch.groups()[0]}"
else:
sshmatch = self.sshRegex.match(ev["system"])
if sshmatch:
sessionno = f"S{sshmatch.groups()[0]}"
if sessionno == "0":
return
if sessionno in self.ips:
ev["src_ip"] = self.ips[sessionno]
# Connection event is special. adds to session list
if ev["eventid"] == "cowrie.session.connect":
self.sessions[sessionno] = ev["session"]
self.ips[sessionno] = ev["src_ip"]
else:
ev["session"] = self.sessions[sessionno]
self.write(ev)
# Disconnect is special, remove cached data
if ev["eventid"] == "cowrie.session.closed":
del self.sessions[sessionno]
del self.ips[sessionno]
| 7,999 | 31.653061 | 88 | py |
cowrie | cowrie-master/src/cowrie/core/ttylog.py | # -*- test-case-name: cowrie.test.utils -*-
"""
Should be compatible with user mode linux
"""
from __future__ import annotations
import hashlib
import struct
OP_OPEN, OP_CLOSE, OP_WRITE, OP_EXEC = 1, 2, 3, 4
TYPE_INPUT, TYPE_OUTPUT, TYPE_INTERACT = 1, 2, 3
TTYSTRUCT = "<iLiiLL"
def ttylog_open(logfile: str, stamp: float) -> None:
"""
Initialize new tty log
@param logfile: logfile name
@param stamp: timestamp
"""
with open(logfile, "ab") as f:
sec, usec = int(stamp), int(1000000 * (stamp - int(stamp)))
f.write(struct.pack(TTYSTRUCT, OP_OPEN, 0, 0, 0, sec, usec))
def ttylog_write(
logfile: str, length: int, direction: int, stamp: float, data: bytes
) -> None:
"""
Write to tty log
@param logfile: timestamp
@param length: length
@param direction: 0 or 1
@param stamp: timestamp
@param data: data
"""
with open(logfile, "ab") as f:
sec, usec = int(stamp), int(1000000 * (stamp - int(stamp)))
f.write(struct.pack(TTYSTRUCT, OP_WRITE, 0, length, direction, sec, usec))
f.write(data)
def ttylog_close(logfile: str, stamp: float) -> None:
"""
Close tty log
@param logfile: logfile name
@param stamp: timestamp
"""
with open(logfile, "ab") as f:
sec, usec = int(stamp), int(1000000 * (stamp - int(stamp)))
f.write(struct.pack(TTYSTRUCT, OP_CLOSE, 0, 0, 0, sec, usec))
def ttylog_inputhash(logfile: str) -> str:
"""
Create unique hash of the input parts of tty log
@param logfile: logfile name
"""
ssize: int = struct.calcsize(TTYSTRUCT)
inputbytes: bytes = b""
with open(logfile, "rb") as fd:
while 1:
try:
op: int
_tty: int
length: int
direction: int
_sec: int
_usec: int
op, _tty, length, direction, _sec, _usec = struct.unpack(
TTYSTRUCT, fd.read(ssize)
)
data: bytes = fd.read(length)
except struct.error:
break
if op is OP_WRITE and direction is TYPE_OUTPUT:
continue
inputbytes = inputbytes + data
shasum: str = hashlib.sha256(inputbytes).hexdigest()
return shasum
| 2,437 | 25.215054 | 82 | py |
cowrie | cowrie-master/src/cowrie/telnet_proxy/server_transport.py | """
Telnet Transport and Authentication for the Honeypot
@author: Olivier Bilodeau <obilodeau@gosecure.ca>
"""
from __future__ import annotations
import time
import uuid
from twisted.conch.telnet import TelnetTransport
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.protocols.policies import TimeoutMixin
from twisted.python import log
from cowrie.core.config import CowrieConfig
from cowrie.telnet_proxy import client_transport
from cowrie.telnet_proxy.handler import TelnetHandler
# object is added for Python 2.7 compatibility (#1198) - as is super with args
class FrontendTelnetTransport(TimeoutMixin, TelnetTransport):
def __init__(self):
super().__init__()
self.peer_ip = None
self.peer_port = 0
self.local_ip = None
self.local_port = 0
self.startTime = None
self.pool_interface = None
self.client = None
self.frontendAuthenticated = False
self.delayedPacketsToBackend = []
# this indicates whether the client effectively connected to the backend
# if they did we recycle the VM, else the VM can be considered "clean"
self.client_used_backend = False
# only used when simple proxy (no pool) set
self.backend_ip = None
self.backend_port = None
self.telnetHandler = TelnetHandler(self)
def connectionMade(self):
self.transportId = uuid.uuid4().hex[:12]
sessionno = self.transport.sessionno
self.peer_ip = self.transport.getPeer().host
self.peer_port = self.transport.getPeer().port + 1
self.local_ip = self.transport.getHost().host
self.local_port = self.transport.getHost().port
log.msg(
eventid="cowrie.session.connect",
format="New connection: %(src_ip)s:%(src_port)s (%(dst_ip)s:%(dst_port)s) [session: %(session)s]",
src_ip=self.transport.getPeer().host,
src_port=self.transport.getPeer().port,
dst_ip=self.transport.getHost().host,
dst_port=self.transport.getHost().port,
session=self.transportId,
sessionno=f"T{sessionno!s}",
protocol="telnet",
)
TelnetTransport.connectionMade(self)
# if we have a pool connect to it and later request a backend, else just connect to a simple backend
# when pool is set we can just test self.pool_interface to the same effect of getting the config
proxy_backend = CowrieConfig.get("proxy", "backend", fallback="simple")
if proxy_backend == "pool":
# request a backend
d = self.factory.pool_handler.request_interface()
d.addCallback(self.pool_connection_success)
d.addErrback(self.pool_connection_error)
else:
# simply a proxy, no pool
backend_ip = CowrieConfig.get("proxy", "backend_telnet_host")
backend_port = CowrieConfig.getint("proxy", "backend_telnet_port")
self.connect_to_backend(backend_ip, backend_port)
def pool_connection_error(self, reason):
log.msg(
f"Connection to backend pool refused: {reason.value}. Disconnecting frontend..."
)
self.transport.loseConnection()
def pool_connection_success(self, pool_interface):
log.msg("Connected to backend pool")
self.pool_interface = pool_interface
self.pool_interface.set_parent(self)
# now request a backend
self.pool_interface.send_vm_request(self.peer_ip)
def received_pool_data(self, operation, status, *data):
if operation == b"r":
honey_ip = data[0]
snapshot = data[1]
telnet_port = data[3]
log.msg(f"Got backend data from pool: {honey_ip.decode()}:{telnet_port}")
log.msg(f"Snapshot file: {snapshot.decode()}")
self.connect_to_backend(honey_ip, telnet_port)
def backend_connection_error(self, reason):
log.msg(
f"Connection to honeypot backend refused: {reason.value}. Disconnecting frontend..."
)
self.transport.loseConnection()
def backend_connection_success(self, backendTransport):
log.msg("Connected to honeypot backend")
self.startTime = time.time()
self.setTimeout(
CowrieConfig.getint("honeypot", "authentication_timeout", fallback=120)
)
def connect_to_backend(self, ip, port):
# connection to the backend starts here
client_factory = client_transport.BackendTelnetFactory()
client_factory.server = self
point = TCP4ClientEndpoint(reactor, ip, port, timeout=20)
d = point.connect(client_factory)
d.addCallback(self.backend_connection_success)
d.addErrback(self.backend_connection_error)
def dataReceived(self, data: bytes) -> None:
self.telnetHandler.addPacket("frontend", data)
def write(self, data):
self.transport.write(data)
def timeoutConnection(self):
"""
Make sure all sessions time out eventually.
Timeout is reset when authentication succeeds.
"""
log.msg("Timeout reached in FrontendTelnetTransport")
# close transports on both sides
if self.transport:
self.transport.loseConnection()
if self.client and self.client.transport:
self.client.transport.loseConnection()
# signal that we're closing to the handler
self.telnetHandler.close()
def connectionLost(self, reason):
"""
Fires on pre-authentication disconnects
"""
self.setTimeout(None)
TelnetTransport.connectionLost(self, reason)
# close transport on backend
if self.client and self.client.transport:
self.client.transport.loseConnection()
# signal that we're closing to the handler
self.telnetHandler.close()
if self.pool_interface:
# free VM from pool (VM was used if auth was performed successfully)
self.pool_interface.send_vm_free(self.telnetHandler.authDone)
# close transport connection to pool
self.pool_interface.transport.loseConnection()
if self.startTime is not None: # startTime is not set when auth fails
duration = time.time() - self.startTime
log.msg(
eventid="cowrie.session.closed",
format="Connection lost after %(duration)d seconds",
duration=duration,
)
def packet_buffer(self, payload):
"""
We have to wait until we have a connection to the backend ready. Meanwhile, we hold packets from client
to server in here.
"""
if not self.client.backendConnected:
# wait till backend connects to send packets to them
log.msg("Connection to backend not ready, buffering packet from frontend")
self.delayedPacketsToBackend.append(payload)
else:
if len(self.delayedPacketsToBackend) > 0:
self.delayedPacketsToBackend.append(payload)
else:
self.client.transport.write(payload)
| 7,303 | 34.629268 | 111 | py |
cowrie | cowrie-master/src/cowrie/telnet_proxy/client_transport.py | # All rights reserved.
from __future__ import annotations
from twisted.conch.telnet import TelnetTransport
from twisted.internet import protocol
from twisted.protocols.policies import TimeoutMixin
from twisted.python import log
class BackendTelnetTransport(TelnetTransport, TimeoutMixin):
def __init__(self):
# self.delayedPacketsToFrontend = []
self.backendConnected = False
self.telnetHandler = None
super().__init__()
def connectionMade(self):
log.msg(f"Connected to Telnet backend at {self.transport.getPeer().host}")
self.telnetHandler = self.factory.server.telnetHandler
self.telnetHandler.setClient(self)
self.backendConnected = True
self.factory.server.client = self
for packet in self.factory.server.delayedPacketsToBackend:
self.transport.write(packet)
self.factory.server.delayedPacketsToBackend = []
super(TelnetTransport, self).connectionMade()
# TODO timeout if no backend available
def connectionLost(self, reason):
# close transport on frontend
self.factory.server.loseConnection()
# signal that we're closing to the handler
self.telnetHandler.close()
def timeoutConnection(self):
"""
Make sure all sessions time out eventually.
Timeout is reset when authentication succeeds.
"""
log.msg("Timeout reached in BackendTelnetTransport")
# close transports on both sides
self.transport.loseConnection()
self.factory.server.transport.loseConnection()
# signal that we're closing to the handler
self.telnetHandler.close()
def dataReceived(self, data):
self.telnetHandler.addPacket("backend", data)
def write(self, data):
self.transport.write(data)
def packet_buffer(self, payload):
"""
We can only proceed if authentication has been performed between client and proxy.
Meanwhile we hold packets in here.
"""
self.factory.server.transport.write(payload)
class BackendTelnetFactory(protocol.ClientFactory):
protocol = BackendTelnetTransport
| 2,253 | 30.746479 | 90 | py |
cowrie | cowrie-master/src/cowrie/telnet_proxy/handler.py | from __future__ import annotations
import os
import re
import time
from twisted.python import log
from cowrie.core import ttylog
from cowrie.core.checkers import HoneypotPasswordChecker
from cowrie.core.config import CowrieConfig
def process_backspaces(s: bytes) -> bytes:
"""
Takes a user-input string that might have backspaces in it (represented as 0x7F),
and actually performs the 'backspace operation' to return a clean string.
"""
n = b""
for i in range(len(s)):
char = chr(s[i]).encode()
if char == b"\x7f":
n = n[:-1]
else:
n += char
return n
def remove_all(original_string: bytes, remove_list: list[bytes]) -> bytes:
"""
Removes all substrings in the list remove_list from string original_string.
"""
n = original_string
for substring in remove_list:
n = n.replace(substring, b"")
return n
class TelnetHandler:
def __init__(self, server):
# holds packet data; useful to manipulate it across functions as needed
self.currentData: bytes = b""
self.sendData = True
# front and backend references
self.server = server
self.client = None
# definitions from config
self.spoofAuthenticationData = CowrieConfig.getboolean(
"proxy", "telnet_spoof_authentication"
)
self.backendLogin = CowrieConfig.get("proxy", "backend_user").encode()
self.backendPassword = CowrieConfig.get("proxy", "backend_pass").encode()
self.usernameInNegotiationRegex = CowrieConfig.get(
"proxy", "telnet_username_in_negotiation_regex", raw=True
).encode()
self.usernamePromptRegex = CowrieConfig.get(
"proxy", "telnet_username_prompt_regex", raw=True
).encode()
self.passwordPromptRegex = CowrieConfig.get(
"proxy", "telnet_password_prompt_regex", raw=True
).encode()
# telnet state
self.currentCommand = b""
# auth state
self.authStarted = False
self.authDone = False
self.usernameState = b"" # TODO clear on end
self.inputingLogin = False
self.passwordState = b"" # TODO clear on end
self.inputingPassword = False
self.waitingLoginEcho = False
# some data is sent by the backend right before the password prompt, we want to capture that
# and the respective frontend response and send it before starting to intercept auth data
self.prePasswordData = False
# buffer
self.backend_buffer = []
# tty logging
self.startTime = time.time()
self.ttylogPath = CowrieConfig.get("honeypot", "ttylog_path")
self.ttylogEnabled = CowrieConfig.getboolean(
"honeypot", "ttylog", fallback=True
)
self.ttylogSize = 0
if self.ttylogEnabled:
self.ttylogFile = "{}/telnet-{}.log".format(
self.ttylogPath, time.strftime("%Y%m%d-%H%M%S")
)
ttylog.ttylog_open(self.ttylogFile, self.startTime)
def setClient(self, client):
self.client = client
def close(self):
if self.ttylogEnabled:
ttylog.ttylog_close(self.ttylogFile, time.time())
shasum = ttylog.ttylog_inputhash(self.ttylogFile)
shasumfile = os.path.join(self.ttylogPath, shasum)
if os.path.exists(shasumfile):
duplicate = True
os.remove(self.ttylogFile)
else:
duplicate = False
os.rename(self.ttylogFile, shasumfile)
umask = os.umask(0)
os.umask(umask)
os.chmod(shasumfile, 0o666 & ~umask)
self.ttylogEnabled = (
False # do not close again if function called after closing
)
log.msg(
eventid="cowrie.log.closed",
format="Closing TTY Log: %(ttylog)s after %(duration)d seconds",
ttylog=shasumfile,
size=self.ttylogSize,
shasum=shasum,
duplicate=duplicate,
duration=time.time() - self.startTime,
)
def sendBackend(self, data: bytes) -> None:
self.backend_buffer.append(data)
if not self.client:
return
for packet in self.backend_buffer:
self.client.transport.write(packet)
# log raw packets if user sets so
if CowrieConfig.getboolean("proxy", "log_raw", fallback=False):
log.msg("to_backend - " + data.decode("unicode-escape"))
if self.ttylogEnabled and self.authStarted:
cleanData = data.replace(
b"\x00", b"\n"
) # some frontends send 0xFF instead of newline
ttylog.ttylog_write(
self.ttylogFile,
len(cleanData),
ttylog.TYPE_INPUT,
time.time(),
cleanData,
)
self.ttylogSize += len(cleanData)
self.backend_buffer = self.backend_buffer[1:]
def sendFrontend(self, data: bytes) -> None:
self.server.transport.write(data)
# log raw packets if user sets so
if CowrieConfig.getboolean("proxy", "log_raw", fallback=False):
log.msg("to_frontend - " + data.decode("unicode-escape"))
if self.ttylogEnabled and self.authStarted:
ttylog.ttylog_write(
self.ttylogFile, len(data), ttylog.TYPE_OUTPUT, time.time(), data
)
# self.ttylogSize += len(data)
def addPacket(self, parent: str, data: bytes) -> None:
self.currentData = data
self.sendData = True
if self.spoofAuthenticationData and not self.authDone:
# detect prompts from backend
if parent == "backend":
self.setProcessingStateBackend()
# detect patterns from frontend
if parent == "frontend":
self.setProcessingStateFrontend()
# save user inputs from frontend
if parent == "frontend":
if self.inputingPassword:
self.processPasswordInput()
if self.inputingLogin:
self.processUsernameInput()
# capture username echo from backend
if self.waitingLoginEcho and parent == "backend":
self.currentData = self.currentData.replace(
self.backendLogin + b"\r\n", b""
)
self.waitingLoginEcho = False
# log user commands
if parent == "frontend" and self.authDone:
self.currentCommand += data.replace(b"\r\x00", b"").replace(b"\r\n", b"")
# check if a command has terminated
if b"\r" in data:
if len(self.currentCommand) > 0:
log.msg(
eventid="cowrie.command.input",
input=self.currentCommand,
format="CMD: %(input)s",
)
self.currentCommand = b""
# send data after processing (also check if processing did not reduce it to an empty string)
if self.sendData and len(self.currentData):
if parent == "frontend":
self.sendBackend(self.currentData)
else:
self.sendFrontend(self.currentData)
def processUsernameInput(self) -> None:
self.sendData = False # withold data until input is complete
# remove control characters
control_chars = [b"\r", b"\x00", b"\n"]
self.usernameState += remove_all(self.currentData, control_chars)
# backend echoes data back to user to show on terminal prompt
# - NULL char is replaced by NEWLINE by backend
# - 0x7F (backspace) is replaced by two 0x08 separated by a blankspace
self.sendFrontend(
self.currentData.replace(b"\x7f", b"\x08 \x08").replace(b"\x00", b"\n")
)
# check if done inputing
if b"\r" in self.currentData:
terminatingChar = chr(
self.currentData[self.currentData.index(b"\r") + 1]
).encode() # usually \n or \x00
# cleanup
self.usernameState = process_backspaces(self.usernameState)
log.msg(f"User input login: {self.usernameState.decode('unicode-escape')}")
self.inputingLogin = False
# actually send to backend
self.currentData = self.backendLogin + b"\r" + terminatingChar
self.sendData = True
# we now have to ignore the username echo from the backend in the next packet
self.waitingLoginEcho = True
def processPasswordInput(self) -> None:
self.sendData = False # withold data until input is complete
if self.prePasswordData:
self.sendBackend(self.currentData[:3])
self.prePasswordData = False
# remove control characters
control_chars = [b"\xff", b"\xfd", b"\x01", b"\r", b"\x00", b"\n"]
self.passwordState += remove_all(self.currentData, control_chars)
# check if done inputing
if b"\r" in self.currentData:
terminatingChar = chr(
self.currentData[self.currentData.index(b"\r") + 1]
).encode() # usually \n or \x00
# cleanup
self.passwordState = process_backspaces(self.passwordState)
log.msg(
f"User input password: {self.passwordState.decode('unicode-escape')}"
)
self.inputingPassword = False
# having the password (and the username, either empy or set before), we can check the login
# on the database, and if valid authenticate or else, if invalid send a fake password to get
# the login failed prompt
src_ip = self.server.transport.getPeer().host
if HoneypotPasswordChecker().checkUserPass(
self.usernameState, self.passwordState, src_ip
):
passwordToSend = self.backendPassword
self.authDone = True
self.server.setTimeout(
CowrieConfig.getint("honeypot", "interactive_timeout", fallback=300)
)
else:
log.msg("Sending invalid auth to backend")
passwordToSend = self.backendPassword + b"fake"
# actually send to backend
self.currentData = passwordToSend + b"\r" + terminatingChar
self.sendData = True
def setProcessingStateBackend(self) -> None:
"""
This function analyses a data packet and sets the processing state of the handler accordingly.
It looks for authentication phases (password input and username input), as well as data that
may need to be processed specially.
"""
hasPassword = re.search(self.passwordPromptRegex, self.currentData)
if hasPassword:
log.msg("Password prompt from backend")
self.authStarted = True
self.inputingPassword = True
self.passwordState = b""
hasLogin = re.search(self.usernamePromptRegex, self.currentData)
if hasLogin:
log.msg("Login prompt from backend")
self.authStarted = True
self.inputingLogin = True
self.usernameState = b""
self.prePasswordData = b"\xff\xfb\x01" in self.currentData
def setProcessingStateFrontend(self) -> None:
"""
Same for the frontend.
"""
# login username is sent in channel negotiation to match the client's username
negotiationLoginPattern = re.compile(self.usernameInNegotiationRegex)
hasNegotiationLogin = negotiationLoginPattern.search(self.currentData)
if hasNegotiationLogin:
self.usernameState = hasNegotiationLogin.group(2)
log.msg(
f"Detected username {self.usernameState.decode('unicode-escape')} in negotiation, spoofing for backend..."
)
# spoof username in data sent
# username is always sent correct, password is the one sent wrong if we don't want to authenticate
self.currentData = negotiationLoginPattern.sub(
rb"\1" + self.backendLogin + rb"\3", self.currentData
)
| 12,570 | 35.75731 | 122 | py |
cowrie | cowrie-master/src/cowrie/python/logfile.py | # -*- test-case-name: cowrie.test.utils -*-
from __future__ import annotations
from os import environ
from twisted.logger import textFileLogObserver
from twisted.python import logfile
from cowrie.core.config import CowrieConfig
class CowrieDailyLogFile(logfile.DailyLogFile):
"""
Overload original Twisted with improved date formatting
"""
def suffix(self, tupledate):
"""
Return the suffix given a (year, month, day) tuple or unixtime
"""
try:
return "{:02d}-{:02d}-{:02d}".format(
tupledate[0], tupledate[1], tupledate[2]
)
except Exception:
# try taking a float unixtime
return "_".join(map(str, self.toDate(tupledate)))
def logger():
directory = CowrieConfig.get("honeypot", "log_path", fallback="var/log/cowrie")
logfile = CowrieDailyLogFile("cowrie.log", directory)
# use Z for UTC (Zulu) time, it's shorter.
if "TZ" in environ and environ["TZ"] == "UTC":
timeFormat = "%Y-%m-%dT%H:%M:%S.%fZ"
else:
timeFormat = "%Y-%m-%dT%H:%M:%S.%f%z"
return textFileLogObserver(logfile, timeFormat=timeFormat)
| 1,281 | 27.488889 | 83 | py |
cowrie | cowrie-master/src/cowrie/telnet/userauth.py | """
Telnet Transport and Authentication for the Honeypot
@author: Olivier Bilodeau <obilodeau@gosecure.ca>
"""
from __future__ import annotations
import struct
from twisted.conch.telnet import (
ECHO,
LINEMODE,
NAWS,
SGA,
AuthenticatingTelnetProtocol,
ITelnetProtocol,
)
from twisted.python import log
from cowrie.core.config import CowrieConfig
from cowrie.core.credentials import UsernamePasswordIP
class HoneyPotTelnetAuthProtocol(AuthenticatingTelnetProtocol):
"""
TelnetAuthProtocol that takes care of Authentication. Once authenticated this
protocol is replaced with HoneyPotTelnetSession.
"""
loginPrompt = b"login: "
passwordPrompt = b"Password: "
windowSize = [40, 80]
def connectionMade(self):
# self.transport.negotiationMap[NAWS] = self.telnet_NAWS
# Initial option negotation. Want something at least for Mirai
# for opt in (NAWS,):
# self.transport.doChain(opt).addErrback(log.err)
# I need to doubly escape here since my underlying
# CowrieTelnetTransport hack would remove it and leave just \n
self.transport.write(self.factory.banner.replace(b"\n", b"\r\r\n"))
self.transport.write(self.loginPrompt)
def connectionLost(self, reason):
"""
Fires on pre-authentication disconnects
"""
AuthenticatingTelnetProtocol.connectionLost(self, reason)
def telnet_User(self, line):
"""
Overridden to conditionally kill 'WILL ECHO' which confuses clients
that don't implement a proper Telnet protocol (most malware)
"""
self.username = line # .decode()
# only send ECHO option if we are chatting with a real Telnet client
self.transport.willChain(ECHO)
# FIXME: this should be configurable or provided via filesystem
self.transport.write(self.passwordPrompt)
return "Password"
def telnet_Password(self, line):
username, password = self.username, line # .decode()
del self.username
def login(ignored):
self.src_ip = self.transport.getPeer().host
creds = UsernamePasswordIP(username, password, self.src_ip)
d = self.portal.login(creds, self.src_ip, ITelnetProtocol)
d.addCallback(self._cbLogin)
d.addErrback(self._ebLogin)
# are we dealing with a real Telnet client?
if self.transport.options:
# stop ECHO
# even if ECHO negotiation fails we still want to attempt a login
# this allows us to support dumb clients which is common in malware
# thus the addBoth: on success and on exception (AlreadyNegotiating)
self.transport.wontChain(ECHO).addBoth(login)
else:
# process login
login("")
return "Discard"
def telnet_Command(self, command):
self.transport.protocol.dataReceived(command + b"\r")
return "Command"
def _cbLogin(self, ial):
"""
Fired on a successful login
"""
interface, protocol, logout = ial
protocol.windowSize = self.windowSize
self.protocol = protocol
self.logout = logout
self.state = "Command"
self.transport.write(b"\n")
# Remove the short timeout of the login prompt.
self.transport.setTimeout(
CowrieConfig.getint("honeypot", "interactive_timeout", fallback=300)
)
# replace myself with avatar protocol
protocol.makeConnection(self.transport)
self.transport.protocol = protocol
def _ebLogin(self, failure):
# TODO: provide a way to have user configurable strings for wrong password
self.transport.wontChain(ECHO)
self.transport.write(b"\nLogin incorrect\n")
self.transport.write(self.loginPrompt)
self.state = "User"
def telnet_NAWS(self, data):
"""
From TelnetBootstrapProtocol in twisted/conch/telnet.py
"""
if len(data) == 4:
width, height = struct.unpack("!HH", b"".join(data))
self.windowSize = [height, width]
else:
log.msg("Wrong number of NAWS bytes")
def enableLocal(self, opt):
if opt == ECHO:
return True
# TODO: check if twisted now supports SGA (see git commit c58056b0)
elif opt == SGA:
return False
else:
return False
def enableRemote(self, opt):
# TODO: check if twisted now supports LINEMODE (see git commit c58056b0)
if opt == LINEMODE:
return False
elif opt == NAWS:
return True
elif opt == SGA:
return True
else:
return False
| 4,827 | 31.186667 | 82 | py |
cowrie | cowrie-master/src/cowrie/telnet/factory.py | """
Telnet Transport and Authentication for the Honeypot
@author: Olivier Bilodeau <obilodeau@gosecure.ca>
"""
from __future__ import annotations
import time
from twisted.cred import portal as tp
from twisted.internet import protocol
from twisted.plugin import IPlugin
from twisted.python import log
from cowrie.core.config import CowrieConfig
from cowrie.telnet.transport import CowrieTelnetTransport
from cowrie.telnet.userauth import HoneyPotTelnetAuthProtocol
from cowrie.telnet_proxy.server_transport import FrontendTelnetTransport
class HoneyPotTelnetFactory(protocol.ServerFactory):
"""
This factory creates HoneyPotTelnetAuthProtocol instances
They listen directly to the TCP port
"""
tac: IPlugin
portal: tp.Portal | None = None # gets set by Twisted plugin
banner: bytes
starttime: float
def __init__(self, backend, pool_handler):
self.backend: str = backend
self.pool_handler = pool_handler
super().__init__()
# TODO logging clarity can be improved: see what SSH does
def logDispatch(self, **args):
"""
Special delivery to the loggers to avoid scope problems
"""
args["sessionno"] = "T{}".format(str(args["sessionno"]))
for output in self.tac.output_plugins:
output.logDispatch(**args)
def startFactory(self):
try:
honeyfs = CowrieConfig.get("honeypot", "contents_path")
issuefile = honeyfs + "/etc/issue.net"
with open(issuefile, "rb") as banner:
self.banner = banner.read()
except OSError:
self.banner = b""
# For use by the uptime command
self.starttime = time.time()
# hook protocol
if self.backend == "proxy":
self.protocol = lambda: FrontendTelnetTransport()
else:
self.protocol = lambda: CowrieTelnetTransport(
HoneyPotTelnetAuthProtocol, self.portal
)
protocol.ServerFactory.startFactory(self)
log.msg("Ready to accept Telnet connections")
def stopFactory(self) -> None:
"""
Stop output plugins
"""
protocol.ServerFactory.stopFactory(self)
def buildProtocol(self, addr):
"""
Overidden so we can keep a reference to running protocols (which is used for testing)
"""
p = self.protocol()
p.factory = self
return p
| 2,489 | 28.294118 | 93 | py |
cowrie | cowrie-master/src/cowrie/telnet/session.py | """
Telnet User Session management for the Honeypot
@author: Olivier Bilodeau <obilodeau@gosecure.ca>
"""
from __future__ import annotations
import traceback
from zope.interface import implementer
from twisted.conch.ssh import session
from twisted.conch.telnet import ECHO, SGA, TelnetBootstrapProtocol
from twisted.internet import interfaces, protocol
from twisted.python import log
from cowrie.insults import insults
from cowrie.shell import protocol as cproto
from cowrie.shell import pwd
class HoneyPotTelnetSession(TelnetBootstrapProtocol):
id = 0 # telnet can only have 1 simultaneous session, unlike SSH
windowSize = [40, 80]
# to be populated by HoneyPotTelnetAuthProtocol after auth
transportId = None
def __init__(self, username, server):
self.username = username.decode()
self.server = server
try:
pwentry = pwd.Passwd().getpwnam(self.username)
self.uid = pwentry["pw_uid"]
self.gid = pwentry["pw_gid"]
self.home = pwentry["pw_dir"]
except KeyError:
self.uid = 1001
self.gid = 1001
self.home = "/home"
self.environ = {
"LOGNAME": self.username,
"USER": self.username,
"SHELL": "/bin/bash",
"HOME": self.home,
"TMOUT": "1800",
}
if self.uid == 0:
self.environ[
"PATH"
] = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else:
self.environ[
"PATH"
] = "/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
# required because HoneyPotBaseProtocol relies on avatar.avatar.home
self.avatar = self
# Do the delayed file system initialization
self.server.initFileSystem(self.home)
def connectionMade(self):
processprotocol = TelnetSessionProcessProtocol(self)
# If we are dealing with a proper Telnet client: enable server echo
if self.transport.options:
self.transport.willChain(SGA)
self.transport.willChain(ECHO)
self.protocol = insults.LoggingTelnetServerProtocol(
cproto.HoneyPotInteractiveTelnetProtocol, self
)
# somewhere in Twisted this exception gets lost. Log explicitly here
try:
self.protocol.makeConnection(processprotocol)
processprotocol.makeConnection(session.wrapProtocol(self.protocol))
except Exception:
log.msg(traceback.format_exc())
def connectionLost(self, reason):
TelnetBootstrapProtocol.connectionLost(self, reason)
self.server = None
self.avatar = None
self.protocol = None
def logout(self):
log.msg(f"avatar {self.username} logging out")
# Taken and adapted from
@implementer(interfaces.ITransport)
class TelnetSessionProcessProtocol(protocol.ProcessProtocol):
"""
I am both an L{IProcessProtocol} and an L{ITransport}.
I am a transport to the remote endpoint and a process protocol to the
local subsystem.
"""
def __init__(self, sess):
self.session = sess
self.lostOutOrErrFlag = False
def outReceived(self, data: bytes) -> None:
self.session.write(data)
def errReceived(self, data: bytes) -> None:
log.msg(f"Error received: {data.decode()}")
# EXTENDED_DATA_STDERR is from ssh, no equivalent in telnet?
# self.session.writeExtended(connection.EXTENDED_DATA_STDERR, err)
def outConnectionLost(self) -> None:
"""
EOF should only be sent when both STDOUT and STDERR have been closed.
"""
if self.lostOutOrErrFlag:
self.session.conn.sendEOF(self.session)
else:
self.lostOutOrErrFlag = True
def errConnectionLost(self) -> None:
"""
See outConnectionLost().
"""
self.outConnectionLost()
def connectionLost(self, reason=None):
self.session.loseConnection()
self.session = None
def processEnded(self, reason=None):
"""
here SSH is doing signal handling, I don't think telnet supports that so
I'm simply going to bail out
"""
log.msg(f"Process ended. Telnet Session disconnected: {reason}")
self.session.loseConnection()
def getHost(self):
"""
Return the host from my session's transport.
"""
return self.session.transport.getHost()
def getPeer(self):
"""
Return the peer from my session's transport.
"""
return self.session.transport.getPeer()
def write(self, data):
self.session.write(data)
def writeSequence(self, seq):
self.session.write(b"".join(seq))
def loseConnection(self):
self.session.loseConnection()
| 5,044 | 29.575758 | 116 | py |
cowrie | cowrie-master/src/cowrie/telnet/transport.py | """
Telnet Transport and Authentication for the Honeypot
@author: Olivier Bilodeau <obilodeau@gosecure.ca>
"""
from __future__ import annotations
import time
import uuid
from twisted.conch.telnet import AlreadyNegotiating, TelnetTransport
from twisted.protocols.policies import TimeoutMixin
from twisted.python import log
from cowrie.core.config import CowrieConfig
class CowrieTelnetTransport(TelnetTransport, TimeoutMixin):
"""
CowrieTelnetTransport
"""
def connectionMade(self):
self.transportId: str = uuid.uuid4().hex[:12]
sessionno = self.transport.sessionno
self.startTime = time.time()
self.setTimeout(
CowrieConfig.getint("honeypot", "authentication_timeout", fallback=120)
)
log.msg(
eventid="cowrie.session.connect",
format="New connection: %(src_ip)s:%(src_port)s (%(dst_ip)s:%(dst_port)s) [session: %(session)s]",
src_ip=self.transport.getPeer().host,
src_port=self.transport.getPeer().port,
dst_ip=self.transport.getHost().host,
dst_port=self.transport.getHost().port,
session=self.transportId,
sessionno=f"T{sessionno!s}",
protocol="telnet",
)
TelnetTransport.connectionMade(self)
def write(self, data):
"""
Because of the presence of two ProtocolTransportMixin in the protocol
stack once authenticated, I need to override write() and remove a \r
otherwise we end up with \r\r\n on the wire.
It is kind of a hack. I asked for a better solution here:
http://stackoverflow.com/questions/35087250/twisted-telnet-server-how-to-avoid-nested-crlf
"""
self.transport.write(data.replace(b"\r\n", b"\n"))
def timeoutConnection(self):
"""
Make sure all sessions time out eventually.
Timeout is reset when authentication succeeds.
"""
log.msg("Timeout reached in CowrieTelnetTransport")
self.transport.loseConnection()
def connectionLost(self, reason):
"""
Fires on pre-authentication disconnects
"""
self.setTimeout(None)
TelnetTransport.connectionLost(self, reason)
duration = time.time() - self.startTime
log.msg(
eventid="cowrie.session.closed",
format="Connection lost after %(duration)d seconds",
duration=duration,
)
def willChain(self, option):
return self._chainNegotiation(None, self.will, option)
def wontChain(self, option):
return self._chainNegotiation(None, self.wont, option)
def doChain(self, option):
return self._chainNegotiation(None, self.do, option)
def dontChain(self, option):
return self._chainNegotiation(None, self.dont, option)
def _handleNegotiationError(self, f, func, option):
if f.type is AlreadyNegotiating:
s = self.getOptionState(option)
if func in (self.do, self.dont):
s.him.onResult.addCallback(self._chainNegotiation, func, option)
s.him.onResult.addErrback(self._handleNegotiationError, func, option)
if func in (self.will, self.wont):
s.us.onResult.addCallback(self._chainNegotiation, func, option)
s.us.onResult.addErrback(self._handleNegotiationError, func, option)
# We only care about AlreadyNegotiating, everything else can be ignored
# Possible other types include OptionRefused, AlreadyDisabled, AlreadyEnabled, ConnectionDone, ConnectionLost
elif f.type is AssertionError:
log.msg(
"Client tried to illegally refuse to disable an option; ignoring, but undefined behavior may result"
)
# TODO: Is ignoring this violation of the protocol the proper behavior?
# Should the connection be terminated instead?
# The telnetd package on Ubuntu (netkit-telnet) does all negotiation before sending the login prompt,
# but does handle client-initiated negotiation at any time.
def _chainNegotiation(self, res, func, option):
return func(option).addErrback(self._handleNegotiationError, func, option)
| 4,310 | 37.491071 | 117 | py |
cowrie | cowrie-master/src/cowrie/pool_interface/client.py |
from __future__ import annotations
import struct
from twisted.internet.protocol import ClientFactory, Protocol
from twisted.python import log
from cowrie.core.config import CowrieConfig
class PoolClient(Protocol):
"""
Represents the connection between a protocol instance (SSH or Telnet) and a QEMU pool
"""
def __init__(self, factory):
self.factory = factory
self.parent = None
self.vm_id = None # used when disconnecting
def connectionMade(self):
pass
def set_parent(self, parent):
self.parent = parent
def send_initialisation(self):
"""
Used only by the PoolHandler on the first connection, to set the pool up.
"""
max_vms = CowrieConfig.getint("proxy", "pool_max_vms", fallback=2)
vm_unused_timeout = CowrieConfig.getint(
"proxy", "pool_vm_unused_timeout", fallback=600
)
share_guests = CowrieConfig.getboolean(
"proxy", "pool_share_guests", fallback=True
)
buf = struct.pack("!cII?", b"i", max_vms, vm_unused_timeout, share_guests)
self.transport.write(buf)
def send_vm_request(self, src_ip):
fmt = f"!cH{len(src_ip)}s"
buf = struct.pack(fmt, b"r", len(src_ip), src_ip.encode())
self.transport.write(buf)
def send_vm_free(self, backend_dirty):
# free the guest, if we had any guest in this connection to begin with
if self.vm_id is not None:
op_code = b"f" if backend_dirty else b"u"
buf = struct.pack("!cI", op_code, self.vm_id)
self.transport.write(buf)
def dataReceived(self, data):
# only makes sense to process data if we have a parent to send it to
if not self.parent:
log.err("Parent not set, discarding data from pool")
return
response = struct.unpack("!cI", data[0:5])
res_op = response[0]
res_code = response[1]
# shift data forward
data = data[5:]
if res_op == b"i":
# callback to the handler to signal that pool was initialised successfully,
# so that SSH and Telnet setup can proceed
self.parent.initialisation_response(res_code)
elif res_op == b"r":
if res_code != 0:
log.msg(
eventid="cowrie.pool_client",
format="Error in pool while requesting guest. Losing connection...",
)
self.parent.loseConnection()
return
# extract VM id
recv = struct.unpack("!I", data[:4])
self.vm_id = recv[0]
data = data[4:]
# extract IP
recv = struct.unpack("!H", data[:2])
ip_len = recv[0]
data = data[2:]
recv = struct.unpack(f"!{ip_len}s", data[:ip_len])
honey_ip = recv[0]
data = data[ip_len:]
# extract ports for SSH and Telnet
recv = struct.unpack("!HH", data[:4])
ssh_port = recv[0]
telnet_port = recv[1]
data = data[4:]
# extract snapshot path
recv = struct.unpack("!H", data[:2])
snaphsot_len = recv[0]
data = data[2:]
recv = struct.unpack(f"!{snaphsot_len}s", data[:snaphsot_len])
snapshot = recv[0]
data = data[snaphsot_len:]
self.parent.received_pool_data(
res_op, res_code, honey_ip, snapshot, ssh_port, telnet_port
)
class PoolClientFactory(ClientFactory):
def __init__(self, handler):
pass
# self.handler = handler
def buildProtocol(self, addr):
return PoolClient(self)
| 3,888 | 29.622047 | 89 | py |
cowrie | cowrie-master/src/cowrie/pool_interface/handler.py |
from __future__ import annotations
import os
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.python import log
from cowrie.pool_interface.client import PoolClientFactory
class PoolNotReadyError(Exception):
pass
class PoolHandler:
"""
When the PoolHandler is started, it establishes a "master" connection to the pool server. After that connection is
successful (initial_pool_connection_success), it issues an initialisation command to the server. Only after this
command returns (initialisation_response) connections can use the pool.
"""
def __init__(self, pool_host, pool_port, cowrie_plugin):
# used for initialisation only
self.cowrie_plugin = cowrie_plugin
# connection details
self.pool_ip: str = pool_host
self.pool_port: int = pool_port
self.pool_ready: bool = False
self.client_factory = PoolClientFactory(self)
# create a main connection to set params
d = self.request_interface(initial_setup=True)
d.addCallback(self.initial_pool_connection_success) # TODO error when timeout?
d.addErrback(self.initial_pool_connection_error)
def initial_pool_connection_success(self, client):
log.msg("Initialising pool with Cowrie settings...")
# TODO get settings from config and send
client.set_parent(self)
client.send_initialisation()
def initial_pool_connection_error(self, reason):
log.err(f"Could not connect to VM pool: {reason.value}")
os._exit(1)
def initialisation_response(self, res_code):
"""
When the pool's initialisation is successful, signal to the plugin that SSH and Telnet can be started.
"""
if res_code == 0:
log.msg("VM pool fully initialised")
self.pool_ready = True
self.cowrie_plugin.pool_ready()
else:
log.err("VM pool could not initialise correctly!")
os._exit(1)
def request_interface(self, initial_setup=False):
if not initial_setup and not self.pool_ready:
raise PoolNotReadyError()
# d.addCallback(self.connectToPoolSuccess)
# d.addErrback(self.connectToPoolError)
endpoint = TCP4ClientEndpoint(reactor, self.pool_ip, self.pool_port, timeout=10)
return endpoint.connect(self.client_factory)
| 2,547 | 33.432432 | 118 | py |
cowrie | cowrie-master/src/cowrie/ssh_proxy/userauth.py |
from __future__ import annotations
from twisted.conch.ssh.common import getNS
from cowrie.ssh import userauth
# object is added for Python 2.7 compatibility (#1198) - as is super with args
class ProxySSHAuthServer(userauth.HoneyPotSSHUserAuthServer):
def __init__(self):
super().__init__()
self.triedPassword = None
def auth_password(self, packet):
"""
Overridden to get password
"""
self.triedPassword = getNS(packet[1:])[0]
return super().auth_password(packet)
def _cbFinishedAuth(self, result):
"""
We only want to return a success to the user, no service needs to be set.
Those will be proxied back to the backend.
"""
self.transport.sendPacket(52, b"")
self.transport.frontendAuthenticated = True
# TODO store this somewhere else, and do not call from here
if self.transport.sshParse.client:
self.transport.sshParse.client.authenticateBackend(
self.user, self.triedPassword
)
| 1,168 | 29.763158 | 81 | py |
cowrie | cowrie-master/src/cowrie/ssh_proxy/server_transport.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
import re
import struct
import time
import uuid
import zlib
from hashlib import md5
from twisted.conch.ssh import transport
from twisted.conch.ssh.common import getNS
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.protocols.policies import TimeoutMixin
from twisted.python import log, randbytes
from cowrie.core.config import CowrieConfig
from cowrie.ssh_proxy import client_transport
from cowrie.ssh_proxy.protocols import ssh
class FrontendSSHTransport(transport.SSHServerTransport, TimeoutMixin):
"""
Represents a connection from the frontend (a client or attacker).
When such connection is received, start the connection to the backend (the VM that will provide the session);
at the same time, perform the userauth service via ProxySSHAuthServer (built-in Cowrie's mechanism).
After both sides are authenticated, forward all things from one side to another.
"""
buf: bytes
ourVersionString: bytes
gotVersion: bool
# TODO merge this with HoneyPotSSHTransport(transport.SSHServerTransport, TimeoutMixin)
# maybe create a parent class with common methods for the two
def __init__(self):
self.timeoutCount = 0
self.sshParse = None
self.disconnected = False # what was this used for
self.peer_ip = None
self.peer_port: int = 0
self.local_ip = None
self.local_port: int = 0
self.startTime = None
self.transportId = None
self.pool_interface = None
self.backendConnected = False
self.frontendAuthenticated = False
self.delayedPackets = []
# only used when simple proxy (no pool) set
self.backend_ip = None
self.backend_port = None
def connectionMade(self):
"""
Called when the connection is made to the other side. We sent our
version and the MSG_KEXINIT packet.
"""
self.sshParse = ssh.SSH(self)
self.transportId = uuid.uuid4().hex[:12]
self.peer_ip = self.transport.getPeer().host
self.peer_port = self.transport.getPeer().port + 1
self.local_ip = self.transport.getHost().host
self.local_port = self.transport.getHost().port
self.transport.write(self.ourVersionString + b"\r\n")
self.currentEncryptions = transport.SSHCiphers(
b"none", b"none", b"none", b"none"
)
self.currentEncryptions.setKeys(b"", b"", b"", b"", b"", b"")
log.msg(
eventid="cowrie.session.connect",
format="New connection: %(src_ip)s:%(src_port)s (%(dst_ip)s:%(dst_port)s) [session: %(session)s]",
src_ip=self.peer_ip,
src_port=self.transport.getPeer().port,
dst_ip=self.local_ip,
dst_port=self.transport.getHost().port,
session=self.transportId,
sessionno=f"S{self.transport.sessionno}",
protocol="ssh",
)
# if we have a pool connect to it and later request a backend, else just connect to a simple backend
# when pool is set we can just test self.pool_interface to the same effect of getting the CowrieConfig
proxy_backend = CowrieConfig.get("proxy", "backend", fallback="simple")
if proxy_backend == "pool":
# request a backend
d = self.factory.pool_handler.request_interface()
d.addCallback(self.pool_connection_success)
d.addErrback(self.pool_connection_error)
else:
# simply a proxy, no pool
backend_ip = CowrieConfig.get("proxy", "backend_ssh_host")
backend_port = CowrieConfig.getint("proxy", "backend_ssh_port")
self.connect_to_backend(backend_ip, backend_port)
def pool_connection_error(self, reason):
log.msg(
f"Connection to backend pool refused: {reason.value}. Disconnecting frontend..."
)
self.transport.loseConnection()
def pool_connection_success(self, pool_interface):
log.msg("Connected to backend pool")
self.pool_interface = pool_interface
self.pool_interface.set_parent(self)
# now request a backend
self.pool_interface.send_vm_request(self.peer_ip)
def received_pool_data(self, operation, status, *data):
if operation == b"r":
honey_ip = data[0]
snapshot = data[1]
ssh_port = data[2]
log.msg(f"Got backend data from pool: {honey_ip.decode()}:{ssh_port}")
log.msg(f"Snapshot file: {snapshot.decode()}")
self.connect_to_backend(honey_ip, ssh_port)
def backend_connection_error(self, reason):
log.msg(
f"Connection to honeypot backend refused: {reason.value}. Disconnecting frontend..."
)
self.transport.loseConnection()
def backend_connection_success(self, backendTransport):
log.msg("Connected to honeypot backend")
self.startTime = time.time()
# this timeout is replaced with `interactive_timeout` in ssh.py
self.setTimeout(
CowrieConfig.getint("honeypot", "authentication_timeout", fallback=120)
)
def connect_to_backend(self, ip, port):
# connection to the backend starts here
client_factory = client_transport.BackendSSHFactory()
client_factory.server = self
point = TCP4ClientEndpoint(reactor, ip, port, timeout=10)
d = point.connect(client_factory)
d.addCallback(self.backend_connection_success)
d.addErrback(self.backend_connection_error)
def sendKexInit(self):
"""
Don't send key exchange prematurely
"""
if not self.gotVersion:
return
transport.SSHServerTransport.sendKexInit(self)
def _unsupportedVersionReceived(self, remoteVersion):
"""
Change message to be like OpenSSH
"""
self.transport.write(b"Protocol major versions differ.\n")
self.transport.loseConnection()
def dataReceived(self, data: bytes) -> None:
"""
First, check for the version string (SSH-2.0-*). After that has been
received, this method adds data to the buffer, and pulls out any
packets.
@type data: C{str}
"""
self.buf += data
# get version from start of communication; check if valid and supported by Twisted
if not self.gotVersion:
if b"\n" not in self.buf:
return
self.otherVersionString = self.buf.split(b"\n")[0].strip()
log.msg(
eventid="cowrie.client.version",
version=self.otherVersionString.decode(
"utf-8", errors="backslashreplace"
),
format="Remote SSH version: %(version)s",
)
m = re.match(rb"SSH-(\d+.\d+)-(.*)", self.otherVersionString)
if m is None:
log.msg(
f"Bad protocol version identification: {self.otherVersionString!r}"
)
if self.transport:
self.transport.write(b"Protocol mismatch.\n")
self.transport.loseConnection()
return
else:
self.gotVersion = True
remote_version = m.group(1)
if remote_version not in self.supportedVersions:
self._unsupportedVersionReceived(None)
return
i = self.buf.index(b"\n")
self.buf = self.buf[i + 1 :]
self.sendKexInit()
packet = self.getPacket()
while packet:
message_num = ord(packet[0:1])
self.dispatchMessage(message_num, packet[1:])
packet = self.getPacket()
def dispatchMessage(self, message_num, payload):
# overriden dispatchMessage sets services, we do that here too then
# we're particularly interested in userauth, since Twisted does most of that for us
if message_num == 5:
self.ssh_SERVICE_REQUEST(payload)
elif 50 <= message_num <= 79: # userauth numbers
self.frontendAuthenticated = False
transport.SSHServerTransport.dispatchMessage(
self, message_num, payload
) # let userauth deal with it
# TODO delay userauth until backend is connected?
elif transport.SSHServerTransport.isEncrypted(self, "both"):
self.packet_buffer(message_num, payload)
else:
transport.SSHServerTransport.dispatchMessage(self, message_num, payload)
def sendPacket(self, messageType, payload):
"""
Override because OpenSSH pads with 0 on KEXINIT
"""
if self._keyExchangeState != self._KEY_EXCHANGE_NONE:
if not self._allowedKeyExchangeMessageType(messageType):
self._blockedByKeyExchange.append((messageType, payload))
return
payload = chr(messageType).encode() + payload
if self.outgoingCompression:
payload = self.outgoingCompression.compress(
payload
) + self.outgoingCompression.flush(2)
bs = self.currentEncryptions.encBlockSize
# 4 for the packet length and 1 for the padding length
totalSize = 5 + len(payload)
lenPad = bs - (totalSize % bs)
if lenPad < 4:
lenPad = lenPad + bs
if messageType == transport.MSG_KEXINIT:
padding = b"\0" * lenPad
else:
padding = randbytes.secureRandom(lenPad)
packet = struct.pack(b"!LB", totalSize + lenPad - 4, lenPad) + payload + padding
encPacket = self.currentEncryptions.encrypt(
packet
) + self.currentEncryptions.makeMAC(self.outgoingPacketSequence, packet)
self.transport.write(encPacket)
self.outgoingPacketSequence += 1
def ssh_KEXINIT(self, packet):
k = getNS(packet[16:], 10)
strings, _ = k[:-1], k[-1]
(kexAlgs, keyAlgs, encCS, _, macCS, _, compCS, _, langCS, _) = (
s.split(b",") for s in strings
)
# hassh SSH client fingerprint
ckexAlgs = ",".join([alg.decode("utf-8") for alg in kexAlgs])
cencCS = ",".join([alg.decode("utf-8") for alg in encCS])
cmacCS = ",".join([alg.decode("utf-8") for alg in macCS])
ccompCS = ",".join([alg.decode("utf-8") for alg in compCS])
hasshAlgorithms = "{kex};{enc};{mac};{cmp}".format(
kex=ckexAlgs, enc=cencCS, mac=cmacCS, cmp=ccompCS
)
hassh = md5(hasshAlgorithms.encode("utf-8")).hexdigest()
log.msg(
eventid="cowrie.client.kex",
format="SSH client hassh fingerprint: %(hassh)s",
hassh=hassh,
hasshAlgorithms=hasshAlgorithms,
kexAlgs=kexAlgs,
keyAlgs=keyAlgs,
encCS=encCS,
macCS=macCS,
compCS=compCS,
langCS=langCS,
)
return transport.SSHServerTransport.ssh_KEXINIT(self, packet)
def timeoutConnection(self):
"""
Make sure all sessions time out eventually.
Timeout is reset when authentication succeeds.
"""
log.msg("Timeout reached in FrontendSSHTransport")
if self.transport:
self.transport.loseConnection()
if self.sshParse.client and self.sshParse.client.transport:
self.sshParse.client.transport.loseConnection()
def setService(self, service):
"""
Remove login grace timeout, set zlib compression after auth
"""
# when auth is successful we enable compression
# this is called right after MSG_USERAUTH_SUCCESS
if service.name == "ssh-connection":
if self.outgoingCompressionType == "zlib@openssh.com":
self.outgoingCompression = zlib.compressobj(6)
if self.incomingCompressionType == "zlib@openssh.com":
self.incomingCompression = zlib.decompressobj()
transport.SSHServerTransport.setService(self, service)
def connectionLost(self, reason):
"""
This seems to be the only reliable place of catching lost connection
"""
self.setTimeout(None)
transport.SSHServerTransport.connectionLost(self, reason)
self.transport.connectionLost(reason)
self.transport = None
# if connection from backend is not closed, do it here
if self.sshParse.client and self.sshParse.client.transport:
self.sshParse.client.transport.loseConnection()
if self.pool_interface:
# free VM from pool (VM was used if we performed SSH authentication to the backend)
vm_dirty = self.sshParse.client.authDone if self.sshParse.client else False
self.pool_interface.send_vm_free(vm_dirty)
# close transport connection to pool
self.pool_interface.transport.loseConnection()
if self.startTime is not None: # startTime is not set when auth fails
duration = time.time() - self.startTime
log.msg(
eventid="cowrie.session.closed",
format="Connection lost after %(duration)d seconds",
duration=duration,
)
def sendDisconnect(self, reason, desc):
"""
http://kbyte.snowpenguin.org/portal/2013/04/30/kippo-protocol-mismatch-workaround/
Workaround for the "bad packet length" error message.
@param reason: the reason for the disconnect. Should be one of the
DISCONNECT_* values.
@type reason: C{int}
@param desc: a description of the reason for the disconnection.
@type desc: C{str}
"""
if b"bad packet length" not in desc:
# With python >= 3 we can use super?
transport.SSHServerTransport.sendDisconnect(self, reason, desc)
else:
self.transport.write(b"Packet corrupt\n")
log.msg(f"Disconnecting with error, code {reason}\nreason: {desc}")
self.transport.loseConnection()
def receiveError(self, reasonCode: str, description: str) -> None:
"""
Called when we receive a disconnect error message from the other
side.
@param reasonCode: the reason for the disconnect, one of the
DISCONNECT_ values.
@type reasonCode: L{int}
@param description: a human-readable description of the
disconnection.
@type description: L{str}
"""
log.msg(f"Got remote error, code {reasonCode} reason: {description}")
def packet_buffer(self, message_num: int, payload: bytes) -> None:
"""
We have to wait until we have a connection to the backend is ready. Meanwhile, we hold packets from client
to server in here.
"""
if not self.backendConnected:
# wait till backend connects to send packets to them
log.msg("Connection to backend not ready, buffering packet from frontend")
self.delayedPackets.append([message_num, payload])
else:
if len(self.delayedPackets) > 0:
self.delayedPackets.append([message_num, payload])
else:
self.sshParse.parse_num_packet("[SERVER]", message_num, payload)
| 17,117 | 38.442396 | 117 | py |
cowrie | cowrie-master/src/cowrie/ssh_proxy/client_transport.py | # All rights reserved.
from __future__ import annotations
from typing import Any
from twisted.conch.ssh import transport
from twisted.internet import defer, protocol
from twisted.protocols.policies import TimeoutMixin
from twisted.python import log
from cowrie.core.config import CowrieConfig
from cowrie.ssh_proxy.util import bin_string_to_hex, string_to_hex
def get_int(data: bytes, length: int = 4) -> int:
return int.from_bytes(data[:length], byteorder="big")
def get_bool(data: bytes) -> bool:
return bool(get_int(data, length=1))
def get_string(data: bytes) -> tuple[int, bytes]:
length = get_int(data, 4)
value = data[4 : length + 4]
return length + 4, value
class BackendSSHFactory(protocol.ClientFactory):
server: Any
def buildProtocol(self, addr):
return BackendSSHTransport(self)
class BackendSSHTransport(transport.SSHClientTransport, TimeoutMixin):
"""
This class represents the transport layer from Cowrie's proxy to the backend SSH server. It is responsible for
authentication to that server, and sending messages it gets to the handler.
"""
def __init__(self, factory: BackendSSHFactory):
self.delayedPackets: list[tuple[int, bytes]] = []
self.factory: BackendSSHFactory = factory
self.canAuth: bool = False
self.authDone: bool = False
# keep these from when frontend authenticates
self.frontendTriedUsername = None
self.frontendTriedPassword = None
def connectionMade(self):
log.msg(f"Connected to SSH backend at {self.transport.getPeer().host}")
self.factory.server.client = self
self.factory.server.sshParse.set_client(self)
transport.SSHClientTransport.connectionMade(self)
def verifyHostKey(self, pub_key, fingerprint):
return defer.succeed(True)
def connectionSecure(self):
log.msg("Backend Connection Secured")
self.canAuth = True
self.authenticateBackend()
def authenticateBackend(self, tried_username=None, tried_password=None):
"""
This is called when the frontend is authenticated, so as to give us the option to authenticate with the
username and password given by the attacker.
"""
# we keep these here in case frontend has authenticated and backend hasn't established the secure channel yet;
# in that case, tried credentials are stored to be used whenever usearauth with backend can be performed
if tried_username and tried_password:
self.frontendTriedUsername = tried_username
self.frontendTriedPassword = tried_password
# do nothing if frontend is not authenticated, or backend has not established a secure channel
if not self.factory.server.frontendAuthenticated or not self.canAuth:
return
# we authenticate with the backend using the credentials provided
# TODO create the account in the backend before (contact the pool of VMs for example)
# so these credentials from the config may not be needed after all
username = CowrieConfig.get("proxy", "backend_user")
password = CowrieConfig.get("proxy", "backend_pass")
log.msg(f"Will auth with backend: {username}/{password}")
self.sendPacket(5, bin_string_to_hex(b"ssh-userauth"))
payload = (
bin_string_to_hex(username.encode())
+ string_to_hex("ssh-connection")
+ string_to_hex("password")
+ b"\x00"
+ bin_string_to_hex(password.encode())
)
self.sendPacket(50, payload)
self.factory.server.backendConnected = True
# send packets from the frontend that were waiting to go to the backend
for packet in self.factory.server.delayedPackets:
self.factory.server.sshParse.parse_num_packet(
"[SERVER]", packet[0], packet[1]
)
self.factory.server.delayedPackets = []
# backend auth is done, attackers will now be connected to the backend
self.authDone = True
def connectionLost(self, reason):
if self.factory.server.pool_interface:
log.msg(
eventid="cowrie.proxy.client_disconnect",
format="Lost connection with the pool backend: id %(vm_id)s",
vm_id=self.factory.server.pool_interface.vm_id,
protocol="ssh",
)
else:
log.msg(
eventid="cowrie.proxy.client_disconnect",
format="Lost connection with the proxy's backend: %(honey_ip)s:%(honey_port)s",
honey_ip=self.factory.server.backend_ip,
honey_port=self.factory.server.backend_port,
protocol="ssh",
)
self.transport.connectionLost(reason)
self.transport = None
# if connection from frontend is not closed, do it here
if self.factory.server.transport:
self.factory.server.transport.loseConnection()
def timeoutConnection(self):
"""
Make sure all sessions time out eventually.
Timeout is reset when authentication succeeds.
"""
log.msg("Timeout reached in BackendSSHTransport")
self.transport.loseConnection()
self.factory.server.transport.loseConnection()
def dispatchMessage(self, message_num, payload):
if message_num in [6, 52]:
return # TODO consume these in authenticateBackend
if message_num == 98:
# looking for RFC 4254 - 6.10. Returning Exit Status
pointer = 4 # ignore recipient_channel
leng, message = get_string(payload[pointer:])
if message == b"exit-status":
pointer += leng + 1 # also boolean ignored
exit_status = get_int(payload[pointer:])
log.msg(f"exitCode: {exit_status}")
if transport.SSHClientTransport.isEncrypted(self, "both"):
self.packet_buffer(message_num, payload)
else:
transport.SSHClientTransport.dispatchMessage(self, message_num, payload)
def packet_buffer(self, message_num: int, payload: bytes) -> None:
"""
We can only proceed if authentication has been performed between client and proxy. Meanwhile we hold packets
from the backend to the frontend in here.
"""
if not self.factory.server.frontendAuthenticated:
# wait till frontend connects and authenticates to send packets to them
log.msg("Connection to client not ready, buffering packet from backend")
self.delayedPackets.append((message_num, payload))
else:
if len(self.delayedPackets) > 0:
self.delayedPackets.append((message_num, payload))
for packet in self.delayedPackets:
self.factory.server.sshParse.parse_num_packet(
"[CLIENT]", packet[0], packet[1]
)
self.delayedPackets = []
else:
self.factory.server.sshParse.parse_num_packet(
"[CLIENT]", message_num, payload
)
| 7,288 | 38.188172 | 118 | py |
cowrie | cowrie-master/src/cowrie/ssh_proxy/util.py | from __future__ import annotations
import struct
def string_to_hex(message: str) -> bytes:
b = message.encode("utf-8")
size = struct.pack(">L", len(b))
return size + b
def bin_string_to_hex(message: bytes) -> bytes:
size = struct.pack(">L", len(message))
return size + message
def int_to_hex(value: int) -> bytes:
return struct.pack(">L", value)
| 376 | 19.944444 | 47 | py |
cowrie | cowrie-master/src/cowrie/ssh_proxy/protocols/sftp.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
from twisted.python import log
from cowrie.ssh_proxy.protocols import base_protocol
class SFTP(base_protocol.BaseProtocol):
prevID: int = 0
ID: int = 0
handle: bytes = b""
path: bytes = b""
command: bytes = b""
payloadSize: int = 0
payloadOffset: int = 0
theFile: bytes = b""
packetLayout = {
1: "SSH_FXP_INIT",
# ['uint32', 'version'], [['string', 'extension_name'], ['string', 'extension_data']]]
2: "SSH_FXP_VERSION",
# [['uint32', 'version'], [['string', 'extension_name'], ['string', 'extension_data']]]
3: "SSH_FXP_OPEN",
# [['uint32', 'id'], ['string', 'filename'], ['uint32', 'pflags'], ['ATTRS', 'attrs']]
4: "SSH_FXP_CLOSE", # [['uint32', 'id'], ['string', 'handle']]
5: "SSH_FXP_READ", # [['uint32', 'id'], ['string', 'handle'], ['uint64', 'offset'], ['uint32', 'len']]
6: "SSH_FXP_WRITE",
# [['uint32', 'id'], ['string', 'handle'], ['uint64', 'offset'], ['string', 'data']]
7: "SSH_FXP_LSTAT", # [['uint32', 'id'], ['string', 'path']]
8: "SSH_FXP_FSTAT", # [['uint32', 'id'], ['string', 'handle']]
9: "SSH_FXP_SETSTAT", # [['uint32', 'id'], ['string', 'path'], ['ATTRS', 'attrs']]
10: "SSH_FXP_FSETSTAT", # [['uint32', 'id'], ['string', 'handle'], ['ATTRS', 'attrs']]
11: "SSH_FXP_OPENDIR", # [['uint32', 'id'], ['string', 'path']]
12: "SSH_FXP_READDIR", # [['uint32', 'id'], ['string', 'handle']]
13: "SSH_FXP_REMOVE", # [['uint32', 'id'], ['string', 'filename']]
14: "SSH_FXP_MKDIR", # [['uint32', 'id'], ['string', 'path'], ['ATTRS', 'attrs']]
15: "SSH_FXP_RMDIR", # [['uint32', 'id'], ['string', 'path']]
16: "SSH_FXP_REALPATH", # [['uint32', 'id'], ['string', 'path']]
17: "SSH_FXP_STAT", # [['uint32', 'id'], ['string', 'path']]
18: "SSH_FXP_RENAME", # [['uint32', 'id'], ['string', 'oldpath'], ['string', 'newpath']]
19: "SSH_FXP_READLINK", # [['uint32', 'id'], ['string', 'path']]
20: "SSH_FXP_SYMLINK", # [['uint32', 'id'], ['string', 'linkpath'], ['string', 'targetpath']]
101: "SSH_FXP_STATUS",
# [['uint32', 'id'], ['uint32', 'error_code'], ['string', 'error_message'], ['string', 'language']]
102: "SSH_FXP_HANDLE", # [['uint32', 'id'], ['string', 'handle']]
103: "SSH_FXP_DATA", # [['uint32', 'id'], ['string', 'data']]
104: "SSH_FXP_NAME",
# [['uint32', 'id'], ['uint32', 'count'], [['string', 'filename'], ['string', 'longname'], ['ATTRS', 'attrs']]]
105: "SSH_FXP_ATTRS", # [['uint32', 'id'], ['ATTRS', 'attrs']]
200: "SSH_FXP_EXTENDED", # []
201: "SSH_FXP_EXTENDED_REPLY", # []
}
def __init__(self, uuid, chan_name, ssh):
super().__init__(uuid, chan_name, ssh)
self.clientPacket = base_protocol.BaseProtocol()
self.serverPacket = base_protocol.BaseProtocol()
self.parent: str
self.offset: int = 0
def parse_packet(self, parent: str, payload: bytes) -> None:
self.parent = parent
if parent == "[SERVER]":
self.parentPacket = self.serverPacket
elif parent == "[CLIENT]":
self.parentPacket = self.clientPacket
else:
raise Exception
if self.parentPacket.packetSize == 0:
self.parentPacket.packetSize = int(payload[:4].hex(), 16) - len(payload[4:])
payload = payload[4:]
self.parentPacket.data = payload
payload = b""
else:
if len(payload) > self.parentPacket.packetSize:
self.parentPacket.data = (
self.parentPacket.data + payload[: self.parentPacket.packetSize]
)
payload = payload[self.parentPacket.packetSize :]
self.parentPacket.packetSize = 0
else:
self.parentPacket.packetSize -= len(payload)
self.parentPacket.data = self.parentPacket.data + payload
payload = b""
if self.parentPacket.packetSize == 0:
self.handle_packet(parent)
if len(payload) != 0:
self.parse_packet(parent, payload)
def handle_packet(self, parent: str) -> None:
self.packetSize: int = self.parentPacket.packetSize
self.data: bytes = self.parentPacket.data
self.command: bytes
sftp_num: int = self.extract_int(1)
packet: str = self.packetLayout[sftp_num]
self.prevID: int = self.ID
self.ID: int = self.extract_int(4)
self.path: bytes = b""
if packet == "SSH_FXP_OPENDIR":
self.path = self.extract_string()
elif packet == "SSH_FXP_REALPATH":
self.path = self.extract_string()
self.command = b"cd " + self.path
log.msg(parent + "[SFTP] Entered Command: " + self.command.decode())
elif packet == "SSH_FXP_OPEN":
self.path = self.extract_string()
pflags = f"{self.extract_int(4):08b}"
if pflags[6] == "1":
self.command = b"put " + self.path
self.theFile = b""
# self.out.download_started(self.uuid, self.path)
elif pflags[7] == "1":
self.command = b"get " + self.path
else:
# Unknown PFlag
log.msg(
parent + f"[SFTP] New SFTP pflag detected: {pflags!r} {self.data!r}"
)
log.msg(parent + " [SFTP] Entered Command: " + self.command.decode())
elif packet == "SSH_FXP_READ":
pass
elif packet == "SSH_FXP_WRITE":
if self.handle == self.extract_string():
self.offset = self.extract_int(8)
self.theFile = self.theFile[: self.offset] + self.extract_data()
elif packet == "SSH_FXP_HANDLE":
if self.ID == self.prevID:
self.handle = self.extract_string()
elif packet == "SSH_FXP_READDIR":
if self.handle == self.extract_string():
self.command = b"ls " + self.path
elif packet == "SSH_FXP_SETSTAT":
self.path = self.extract_string()
self.command = self.extract_attrs() + b" " + self.path
elif packet == "SSH_FXP_EXTENDED":
cmd = self.extract_string()
self.path = self.extract_string()
if cmd == b"statvfs@openssh.com":
self.command = b"df " + self.path
elif cmd == b"hardlink@openssh.com":
self.command = b"ln " + self.path + b" " + self.extract_string()
elif cmd == b"posix-rename@openssh.com":
self.command = b"mv " + self.path + b" " + self.extract_string()
else:
# UNKNOWN COMMAND
log.msg(
parent
+ f"[SFTP] New SFTP Extended Command detected: {cmd!r} {self.data!r}"
)
elif packet == "SSH_FXP_EXTENDED_REPLY":
log.msg(parent + "[SFTP] Entered Command: " + self.command.decode())
elif packet == "SSH_FXP_CLOSE":
if self.handle == self.extract_string():
if b"get" in self.command:
log.msg(
parent + " [SFTP] Finished Downloading: " + self.path.decode()
)
elif b"put" in self.command:
log.msg(
parent + " [SFTP] Finished Uploading: " + self.path.decode()
)
# if self.out.cfg.getboolean(['download', 'passive']):
# # self.out.make_downloads_folder()
# outfile = self.out.downloadFolder + datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")\
# + "-" + self.path.split('/')[-1]
# f = open(outfile, 'wb')
# f.write(self.theFile)
# f.close()
# #self.out.file_downloaded((self.uuid, True, self.path, outfile, None))
elif packet == "SSH_FXP_SYMLINK":
self.command = (
b"ln -s " + self.extract_string() + b" " + self.extract_string()
)
elif packet == "SSH_FXP_MKDIR":
self.command = b"mkdir " + self.extract_string()
elif packet == "SSH_FXP_REMOVE":
self.command = b"rm " + self.extract_string()
elif packet == "SSH_FXP_RMDIR":
self.command = b"rmdir " + self.extract_string()
elif packet == "SSH_FXP_STATUS":
if self.ID == self.prevID:
code = self.extract_int(4)
if code in [0, 1]:
if b"get" not in self.command and b"put" not in self.command:
log.msg(
parent + " [SFTP] Entered Command: " + self.command.decode()
)
else:
message = self.extract_string()
log.msg(
parent
+ " [SFTP] Failed Command: "
+ self.command.decode()
+ " Reason: "
+ message.decode()
)
def extract_attrs(self) -> bytes:
cmd: str = ""
flags: str = f"{self.extract_int(4):08b}"
if flags[5] == "1":
perms = f"{self.extract_int(4):09b}"
# log.msg(log.LPURPLE, self.parent + '[SFTP]', 'PERMS:' + perms)
chmod = (
str(int(perms[:3], 2))
+ str(int(perms[3:6], 2))
+ str(int(perms[6:], 2))
)
cmd = "chmod " + chmod
elif flags[6] == "1":
user = str(self.extract_int(4))
group = str(self.extract_int(4))
cmd = "chown " + user + ":" + group
else:
pass
# Unknown attribute
# log.msg(log.LRED, self.parent + '[SFTP]',
# 'New SFTP Attribute detected - Please raise a HonSSH issue on github with the details: %s %s' %
# (flags, self.data))
return cmd.encode()
"""
CLIENT SERVER
SSH_FXP_INIT -->
<-- SSH_FXP_VERSION
SSH_FXP_OPEN -->
<-- SSH_FXP_HANDLE (or SSH_FXP_STATUS if fail)
SSH_FXP_READ -->
<-- SSH_FXP_DATA (or SSH_FXP_STATUS if fail)
SSH_FXP_WRITE -->
<-- SSH_FXP_STATUS
SSH_FXP_REMOVE -->
<-- SSH_FXP_STATUS
SSH_FXP_RENAME -->
<-- SSH_FXP_STATUS
SSH_FXP_MKDIR -->
<-- SSH_FXP_STATUS
SSH_FXP_RMDIR -->
<-- SSH_FXP_STATUS
SSH_FXP_OPENDIR -->
<-- SSH_FXP_HANDLE (or SSH_FXP_STATUS if fail)
SSH_FXP_READDIR -->
<-- SSH_FXP_NAME (or SSH_FXP_STATUS if fail)
SSH_FXP_STAT --> //Follows symlinks
<-- SSH_FXP_ATTRS (or SSH_FXP_STATUS if fail)
SSH_FXP_LSTAT --> //Does not follow symlinks
<-- SSH_FXP_ATTRS (or SSH_FXP_STATUS if fail)
SSH_FXP_FSTAT --> //Works on an open file/handle not a file path like (L)STAT
<-- SSH_FXP_ATTRS (or SSH_FXP_STATUS if fail)
SSH_FXP_SETSTAT --> //Sets file attributes on path
<-- SSH_FXP_STATUS
SSH_FXP_FSETSTAT--> //Sets file attributes on a handle
<-- SSH_FXP_STATUS
SSH_FXP_READLINK --> //Used to find the target of a symlink
<-- SSH_FXP_NAME (or SSH_FXP_STATUS if fail)
SSH_FXP_SYMLINK --> //Used to create a symlink
<-- SSH_FXP_NAME (or SSH_FXP_STATUS if fail)
SSH_FXP_REALPATH --> //Relative path
<-- SSH_FXP_NAME (or SSH_FXP_STATUS if fail)
SSH_FXP_CLOSE --> //Closes handle not session
<-- SSH_FXP_STATUS
"""
| 13,833 | 39.332362 | 119 | py |
cowrie | cowrie-master/src/cowrie/ssh_proxy/protocols/base_protocol.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
class BaseProtocol:
data: bytes = b""
packetSize: int = 0
name: str = ""
uuid: str = ""
ttylog_file = None
def __init__(self, uuid=None, name=None, ssh=None):
if uuid is not None:
self.uuid = uuid
if name is not None:
self.name = name
if ssh is not None:
self.ssh = ssh
def parse_packet(self, parent: str, data: bytes) -> None:
# log.msg(parent + ' ' + repr(data))
# log.msg(parent + ' ' + '\'\\x' + "\\x".join("{:02x}".format(ord(c)) for c in self.data) + '\'')
pass
def channel_closed(self):
pass
def extract_int(self, length: int) -> int:
value = int.from_bytes(self.data[:length], byteorder="big")
self.packetSize = self.packetSize - length
self.data = self.data[length:]
return value
def put_int(self, number: int) -> bytes:
return number.to_bytes(4, byteorder="big")
def extract_string(self) -> bytes:
"""
note: this actually returns bytes!
"""
length: int = self.extract_int(4)
value: bytes = self.data[:length]
self.packetSize -= length
self.data = self.data[length:]
return value
def extract_bool(self) -> bool:
value = self.extract_int(1)
return bool(value)
def extract_data(self) -> bytes:
length = self.extract_int(4)
self.packetSize = length
value = self.data
self.packetSize -= len(value)
self.data = b""
return value
def __deepcopy__(self, memo):
return None
| 3,127 | 33.755556 | 105 | py |
cowrie | cowrie-master/src/cowrie/ssh_proxy/protocols/exec_term.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
import os
import time
from twisted.python import log
from cowrie.core import ttylog
from cowrie.core.config import CowrieConfig
from cowrie.ssh_proxy.protocols import base_protocol
class ExecTerm(base_protocol.BaseProtocol):
def __init__(self, uuid, channelName, ssh, channelId, command):
super().__init__(uuid, channelName, ssh)
try:
log.msg(
eventid="cowrie.command.input",
input=command.decode("utf8"),
format="CMD: %(input)s",
)
except UnicodeDecodeError:
log.err(f"Unusual execcmd: {command!r}")
self.transportId = ssh.server.transportId
self.channelId = channelId
self.startTime: float = time.time()
self.ttylogPath: str = CowrieConfig.get("honeypot", "ttylog_path")
self.ttylogEnabled: bool = CowrieConfig.getboolean(
"honeypot", "ttylog", fallback=True
)
self.ttylogSize: int = 0
if self.ttylogEnabled:
self.ttylogFile = "{}/{}-{}-{}e.log".format(
self.ttylogPath,
time.strftime("%Y%m%d-%H%M%S"),
self.transportId,
self.channelId,
)
ttylog.ttylog_open(self.ttylogFile, self.startTime)
def parse_packet(self, parent: str, data: bytes) -> None:
if self.ttylogEnabled:
ttylog.ttylog_write(
self.ttylogFile, len(data), ttylog.TYPE_OUTPUT, time.time(), data
)
self.ttylogSize += len(data)
def channel_closed(self):
if self.ttylogEnabled:
ttylog.ttylog_close(self.ttylogFile, time.time())
shasum = ttylog.ttylog_inputhash(self.ttylogFile)
shasumfile = os.path.join(self.ttylogPath, shasum)
if os.path.exists(shasumfile):
duplicate = True
os.remove(self.ttylogFile)
else:
duplicate = False
os.rename(self.ttylogFile, shasumfile)
umask = os.umask(0)
os.umask(umask)
os.chmod(shasumfile, 0o666 & ~umask)
log.msg(
eventid="cowrie.log.closed",
format="Closing TTY Log: %(ttylog)s after %(duration)d seconds",
ttylog=shasumfile,
size=self.ttylogSize,
shasum=shasum,
duplicate=duplicate,
duration=time.time() - self.startTime,
)
| 4,025 | 37.342857 | 81 | py |
cowrie | cowrie-master/src/cowrie/ssh_proxy/protocols/ssh.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
from typing import Any
import uuid
from twisted.python import log
from cowrie.core.config import CowrieConfig
from cowrie.ssh_proxy.protocols import (
base_protocol,
exec_term,
port_forward,
sftp,
term,
)
from cowrie.ssh_proxy.util import int_to_hex, string_to_hex
class SSH(base_protocol.BaseProtocol):
packetLayout = {
1: "SSH_MSG_DISCONNECT", # ['uint32', 'reason_code'], ['string', 'reason'], ['string', 'language_tag']
2: "SSH_MSG_IGNORE", # ['string', 'data']
3: "SSH_MSG_UNIMPLEMENTED", # ['uint32', 'seq_no']
4: "SSH_MSG_DEBUG", # ['boolean', 'always_display']
5: "SSH_MSG_SERVICE_REQUEST", # ['string', 'service_name']
6: "SSH_MSG_SERVICE_ACCEPT", # ['string', 'service_name']
20: "SSH_MSG_KEXINIT", # ['string', 'service_name']
21: "SSH_MSG_NEWKEYS",
50: "SSH_MSG_USERAUTH_REQUEST", # ['string', 'username'], ['string', 'service_name'], ['string', 'method_name']
51: "SSH_MSG_USERAUTH_FAILURE", # ['name-list', 'authentications'], ['boolean', 'partial_success']
52: "SSH_MSG_USERAUTH_SUCCESS", #
53: "SSH_MSG_USERAUTH_BANNER", # ['string', 'message'], ['string', 'language_tag']
60: "SSH_MSG_USERAUTH_INFO_REQUEST", # ['string', 'name'], ['string', 'instruction'],
# ['string', 'language_tag'], ['uint32', 'num-prompts'],
# ['string', 'prompt[x]'], ['boolean', 'echo[x]']
61: "SSH_MSG_USERAUTH_INFO_RESPONSE", # ['uint32', 'num-responses'], ['string', 'response[x]']
80: "SSH_MSG_GLOBAL_REQUEST", # ['string', 'request_name'], ['boolean', 'want_reply'] #tcpip-forward
81: "SSH_MSG_REQUEST_SUCCESS",
82: "SSH_MSG_REQUEST_FAILURE",
90: "SSH_MSG_CHANNEL_OPEN", # ['string', 'channel_type'], ['uint32', 'sender_channel'],
# ['uint32', 'initial_window_size'], ['uint32', 'maximum_packet_size'],
91: "SSH_MSG_CHANNEL_OPEN_CONFIRMATION", # ['uint32', 'recipient_channel'], ['uint32', 'sender_channel'],
# ['uint32', 'initial_window_size'], ['uint32', 'maximum_packet_size']
92: "SSH_MSG_CHANNEL_OPEN_FAILURE", # ['uint32', 'recipient_channel'], ['uint32', 'reason_code'],
# ['string', 'reason'], ['string', 'language_tag']
93: "SSH_MSG_CHANNEL_WINDOW_ADJUST", # ['uint32', 'recipient_channel'], ['uint32', 'additional_bytes']
94: "SSH_MSG_CHANNEL_DATA", # ['uint32', 'recipient_channel'], ['string', 'data']
95: "SSH_MSG_CHANNEL_EXTENDED_DATA", # ['uint32', 'recipient_channel'],
# ['uint32', 'data_type_code'], ['string', 'data']
96: "SSH_MSG_CHANNEL_EOF", # ['uint32', 'recipient_channel']
97: "SSH_MSG_CHANNEL_CLOSE", # ['uint32', 'recipient_channel']
98: "SSH_MSG_CHANNEL_REQUEST", # ['uint32', 'recipient_channel'], ['string', 'request_type'],
# ['boolean', 'want_reply']
99: "SSH_MSG_CHANNEL_SUCCESS",
100: "SSH_MSG_CHANNEL_FAILURE",
}
def __init__(self, server):
super().__init__()
self.channels: list[dict[str, Any]] = []
self.username = b""
self.password = b""
self.auth_type = b""
self.service = b""
self.sendOn = False
self.expect_password = 0
self.server = server
# self.client
def set_client(self, client):
self.client = client
def parse_num_packet(self, parent: str, message_num: int, payload: bytes) -> None:
self.data = payload
self.packetSize = len(payload)
self.sendOn = True
if message_num in self.packetLayout:
packet = self.packetLayout[message_num]
else:
packet = f"UNKNOWN_{message_num}"
if parent == "[SERVER]":
direction = "PROXY -> BACKEND"
else:
direction = "BACKEND -> PROXY"
# log raw packets if user sets so
if CowrieConfig.getboolean("proxy", "log_raw", fallback=False):
log.msg(
eventid="cowrie.proxy.ssh",
format="%(direction)s - %(packet)s - %(payload)s",
direction=direction,
packet=packet.ljust(37),
payload=repr(payload),
protocol="ssh",
)
if packet == "SSH_MSG_SERVICE_REQUEST":
service = self.extract_string()
if service == b"ssh-userauth":
self.sendOn = False
# - UserAuth
if packet == "SSH_MSG_USERAUTH_REQUEST":
self.sendOn = False
self.username = self.extract_string()
self.extract_string() # service
self.auth_type = self.extract_string()
if self.auth_type == b"password":
self.extract_bool()
self.password = self.extract_string()
# self.server.sendPacket(52, b'')
elif self.auth_type == b"publickey":
self.sendOn = False
self.server.sendPacket(51, string_to_hex("password") + chr(0).encode())
elif packet == "SSH_MSG_USERAUTH_FAILURE":
self.sendOn = False
auth_list = self.extract_string()
if b"publickey" in auth_list:
log.msg("[SSH] Detected Public Key Auth - Disabling!")
payload = string_to_hex("password") + chr(0).encode()
elif packet == "SSH_MSG_USERAUTH_SUCCESS":
self.sendOn = False
elif packet == "SSH_MSG_USERAUTH_INFO_REQUEST":
self.sendOn = False
self.auth_type = b"keyboard-interactive"
self.extract_string()
self.extract_string()
self.extract_string()
num_prompts = self.extract_int(4)
for i in range(0, num_prompts):
request = self.extract_string()
self.extract_bool()
if b"password" in request.lower():
self.expect_password = i
elif packet == "SSH_MSG_USERAUTH_INFO_RESPONSE":
self.sendOn = False
num_responses = self.extract_int(4)
for i in range(0, num_responses):
response = self.extract_string()
if i == self.expect_password:
self.password = response
# - End UserAuth
# - Channels
elif packet == "SSH_MSG_CHANNEL_OPEN":
channel_type = self.extract_string()
channel_id = self.extract_int(4)
log.msg(f"got channel {channel_type!r} request")
if channel_type == b"session":
# if using an interactive session reset frontend timeout
self.server.setTimeout(
CowrieConfig.getint("honeypot", "interactive_timeout", fallback=300)
)
self.create_channel(parent, channel_id, channel_type)
elif channel_type == b"direct-tcpip" or channel_type == b"forwarded-tcpip":
self.extract_int(4)
self.extract_int(4)
dst_ip = self.extract_string()
dst_port = self.extract_int(4)
src_ip = self.extract_string()
src_port = self.extract_int(4)
if CowrieConfig.getboolean("ssh", "forwarding"):
log.msg(
eventid="cowrie.direct-tcpip.request",
format="direct-tcp connection request to %(dst_ip)s:%(dst_port)s "
"from %(src_ip)s:%(src_port)s",
dst_ip=dst_ip,
dst_port=dst_port,
src_ip=src_ip,
src_port=src_port,
)
the_uuid = uuid.uuid4().hex
self.create_channel(parent, channel_id, channel_type)
if parent == "[SERVER]":
other_parent = "[CLIENT]"
the_name = "[LPRTF" + str(channel_id) + "]"
else:
other_parent = "[SERVER]"
the_name = "[RPRTF" + str(channel_id) + "]"
channel = self.get_channel(channel_id, other_parent)
channel["name"] = the_name
channel["session"] = port_forward.PortForward(
the_uuid, channel["name"], self
)
else:
log.msg("[SSH] Detected Port Forwarding Channel - Disabling!")
log.msg(
eventid="cowrie.direct-tcpip.data",
format="discarded direct-tcp forward request %(id)s to %(dst_ip)s:%(dst_port)s ",
dst_ip=dst_ip,
dst_port=dst_port,
)
self.sendOn = False
self.send_back(
parent,
92,
int_to_hex(channel_id)
+ int_to_hex(1)
+ string_to_hex("open failed")
+ int_to_hex(0),
)
else:
# UNKNOWN CHANNEL TYPE
if channel_type not in [b"exit-status"]:
log.msg(f"[SSH Unknown Channel Type Detected - {channel_type!r}")
elif packet == "SSH_MSG_CHANNEL_OPEN_CONFIRMATION":
channel = self.get_channel(self.extract_int(4), parent)
# SENDER
sender_id = self.extract_int(4)
if parent == "[SERVER]":
channel["serverID"] = sender_id
elif parent == "[CLIENT]":
channel["clientID"] = sender_id
# CHANNEL OPENED
elif packet == "SSH_MSG_CHANNEL_OPEN_FAILURE":
channel = self.get_channel(self.extract_int(4), parent)
self.channels.remove(channel)
# CHANNEL FAILED TO OPEN
elif packet == "SSH_MSG_CHANNEL_REQUEST":
channel = self.get_channel(self.extract_int(4), parent)
channel_type = self.extract_string()
the_uuid = uuid.uuid4().hex
if channel_type == b"shell":
channel["name"] = "[TERM" + str(channel["serverID"]) + "]"
channel["session"] = term.Term(
the_uuid, channel["name"], self, channel["clientID"]
)
elif channel_type == b"exec":
channel["name"] = "[EXEC" + str(channel["serverID"]) + "]"
self.extract_bool()
command = self.extract_string()
channel["session"] = exec_term.ExecTerm(
the_uuid, channel["name"], self, channel["serverID"], command
)
elif channel_type == b"subsystem":
self.extract_bool()
subsystem = self.extract_string()
if subsystem == b"sftp":
if CowrieConfig.getboolean("ssh", "sftp_enabled"):
channel["name"] = "[SFTP" + str(channel["serverID"]) + "]"
# self.out.channel_opened(the_uuid, channel['name'])
channel["session"] = sftp.SFTP(the_uuid, channel["name"], self)
else:
# log.msg(log.LPURPLE, '[SSH]', 'Detected SFTP Channel Request - Disabling!')
self.sendOn = False
self.send_back(parent, 100, int_to_hex(channel["serverID"]))
else:
# UNKNOWN SUBSYSTEM
log.msg(
"[SSH] Unknown Subsystem Type Detected - " + subsystem.decode()
)
else:
# UNKNOWN CHANNEL REQUEST TYPE
if channel_type not in [
b"window-change",
b"env",
b"pty-req",
b"exit-status",
b"exit-signal",
]:
log.msg(
f"[SSH] Unknown Channel Request Type Detected - {channel_type.decode()}"
)
elif packet == "SSH_MSG_CHANNEL_FAILURE":
pass
elif packet == "SSH_MSG_CHANNEL_CLOSE":
channel = self.get_channel(self.extract_int(4), parent)
# Is this needed?!
channel[parent] = True
if "[SERVER]" in channel and "[CLIENT]" in channel:
# CHANNEL CLOSED
if channel["session"] is not None:
log.msg("remote close")
channel["session"].channel_closed()
self.channels.remove(channel)
# - END Channels
# - ChannelData
elif packet == "SSH_MSG_CHANNEL_DATA":
channel = self.get_channel(self.extract_int(4), parent)
channel["session"].parse_packet(parent, self.extract_string())
elif packet == "SSH_MSG_CHANNEL_EXTENDED_DATA":
channel = self.get_channel(self.extract_int(4), parent)
self.extract_int(4)
channel["session"].parse_packet(parent, self.extract_string())
# - END ChannelData
elif packet == "SSH_MSG_GLOBAL_REQUEST":
channel_type = self.extract_string()
if channel_type == b"tcpip-forward":
if not CowrieConfig.getboolean("ssh", "forwarding"):
self.sendOn = False
self.send_back(parent, 82, "")
if self.sendOn:
if parent == "[SERVER]":
self.client.sendPacket(message_num, payload)
else:
self.server.sendPacket(message_num, payload)
def send_back(self, parent, message_num, payload):
packet = self.packetLayout[message_num]
if parent == "[SERVER]":
direction = "PROXY -> FRONTEND"
else:
direction = "PROXY -> BACKEND"
log.msg(
eventid="cowrie.proxy.ssh",
format="%(direction)s - %(packet)s - %(payload)s",
direction=direction,
packet=packet.ljust(37),
payload=repr(payload),
protocol="ssh",
)
if parent == "[SERVER]":
self.server.sendPacket(message_num, payload)
elif parent == "[CLIENT]":
self.client.sendPacket(message_num, payload)
def create_channel(self, parent, channel_id, channel_type, session=None):
if parent == "[SERVER]":
self.channels.append(
{"serverID": channel_id, "type": channel_type, "session": session}
)
elif parent == "[CLIENT]":
self.channels.append(
{"clientID": channel_id, "type": channel_type, "session": session}
)
def get_channel(self, channel_num: int, parent: str) -> dict[str, Any]:
the_channel = None
for channel in self.channels:
if parent == "[CLIENT]":
search = "serverID"
else:
search = "clientID"
if channel[search] == channel_num:
the_channel = channel
break
if the_channel is None:
raise KeyError
else:
return the_channel
| 16,858 | 39.820823 | 120 | py |
cowrie | cowrie-master/src/cowrie/ssh_proxy/protocols/term.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
import os
import time
from twisted.python import log
from cowrie.core import ttylog
from cowrie.core.config import CowrieConfig
from cowrie.ssh_proxy.protocols import base_protocol
class Term(base_protocol.BaseProtocol):
def __init__(self, uuid, chan_name, ssh, channelId):
super().__init__(uuid, chan_name, ssh)
self.command: bytes = b""
self.pointer: int = 0
self.tabPress: bool = False
self.upArrow: bool = False
self.transportId: int = ssh.server.transportId
self.channelId: int = channelId
self.startTime: float = time.time()
self.ttylogPath: str = CowrieConfig.get("honeypot", "ttylog_path")
self.ttylogEnabled: bool = CowrieConfig.getboolean(
"honeypot", "ttylog", fallback=True
)
self.ttylogSize: int = 0
if self.ttylogEnabled:
self.ttylogFile = "{}/{}-{}-{}i.log".format(
self.ttylogPath, time.strftime("%Y%m%d-%H%M%S"), uuid, self.channelId
)
ttylog.ttylog_open(self.ttylogFile, self.startTime)
def channel_closed(self) -> None:
if self.ttylogEnabled:
ttylog.ttylog_close(self.ttylogFile, time.time())
shasum = ttylog.ttylog_inputhash(self.ttylogFile)
shasumfile = os.path.join(self.ttylogPath, shasum)
if os.path.exists(shasumfile):
duplicate = True
os.remove(self.ttylogFile)
else:
duplicate = False
os.rename(self.ttylogFile, shasumfile)
umask = os.umask(0)
os.umask(umask)
os.chmod(shasumfile, 0o666 & ~umask)
log.msg(
eventid="cowrie.log.closed",
format="Closing TTY Log: %(ttylog)s after %(duration)d seconds",
ttylog=shasumfile,
size=self.ttylogSize,
shasum=shasum,
duplicate=duplicate,
duration=time.time() - self.startTime,
)
def parse_packet(self, parent: str, payload: bytes) -> None:
self.data: bytes = payload
if parent == "[SERVER]":
while len(self.data) > 0:
# If Tab Pressed
if self.data[:1] == b"\x09":
self.tabPress = True
self.data = self.data[1:]
# If Backspace Pressed
elif self.data[:1] == b"\x7f" or self.data[:1] == b"\x08":
if self.pointer > 0:
self.command = (
self.command[: self.pointer - 1]
+ self.command[self.pointer :]
)
self.pointer -= 1
self.data = self.data[1:]
# If enter or ctrl+c or newline
elif (
self.data[:1] == b"\x0d"
or self.data[:1] == b"\x03"
or self.data[:1] == b"\x0a"
):
if self.data[:1] == b"\x03":
self.command += b"^C"
self.data = self.data[1:]
try:
if self.command != b"":
log.msg(
eventid="cowrie.command.input",
input=self.command.decode("utf8"),
format="CMD: %(input)s",
)
except UnicodeDecodeError:
log.err(f"Unusual execcmd: {self.command!r}")
self.command = b""
self.pointer = 0
# If Home Pressed
elif self.data[:3] == b"\x1b\x4f\x48":
self.pointer = 0
self.data = self.data[3:]
# If End Pressed
elif self.data[:3] == b"\x1b\x4f\x46":
self.pointer = len(self.command)
self.data = self.data[3:]
# If Right Pressed
elif self.data[:3] == b"\x1b\x5b\x43":
if self.pointer != len(self.command):
self.pointer += 1
self.data = self.data[3:]
# If Left Pressed
elif self.data[:3] == b"\x1b\x5b\x44":
if self.pointer != 0:
self.pointer -= 1
self.data = self.data[3:]
# If up or down arrow
elif (
self.data[:3] == b"\x1b\x5b\x41" or self.data[:3] == b"\x1b\x5b\x42"
):
self.upArrow = True
self.data = self.data[3:]
else:
self.command = (
self.command[: self.pointer]
+ self.data[:1]
+ self.command[self.pointer :]
)
self.pointer += 1
self.data = self.data[1:]
if self.ttylogEnabled:
self.ttylogSize += len(payload)
ttylog.ttylog_write(
self.ttylogFile,
len(payload),
ttylog.TYPE_OUTPUT,
time.time(),
payload,
)
elif parent == "[CLIENT]":
if self.tabPress:
if not self.data.startswith(b"\x0d"):
if self.data != b"\x07":
self.command = self.command + self.data
self.tabPress = False
if self.upArrow:
while len(self.data) != 0:
# Backspace
if self.data[:1] == b"\x08":
self.command = self.command[:-1]
self.pointer -= 1
self.data = self.data[1:]
# ESC[K - Clear Line
elif self.data[:3] == b"\x1b\x5b\x4b":
self.command = self.command[: self.pointer]
self.data = self.data[3:]
elif self.data[:1] == b"\x0d":
self.pointer = 0
self.data = self.data[1:]
# Right Arrow
elif self.data[:3] == b"\x1b\x5b\x43":
self.pointer += 1
self.data = self.data[3:]
elif self.data[:2] == b"\x1b\x5b" and self.data[3:3] == b"\x50":
self.data = self.data[4:]
# Needed?!
elif self.data[:1] != b"\x07" and self.data[:1] != b"\x0d":
self.command = (
self.command[: self.pointer]
+ self.data[:1]
+ self.command[self.pointer :]
)
self.pointer += 1
self.data = self.data[1:]
else:
self.pointer += 1
self.data = self.data[1:]
self.upArrow = False
if self.ttylogEnabled:
self.ttylogSize += len(payload)
ttylog.ttylog_write(
self.ttylogFile,
len(payload),
ttylog.TYPE_INPUT,
time.time(),
payload,
)
| 9,070 | 38.960352 | 88 | py |
cowrie | cowrie-master/src/cowrie/ssh_proxy/protocols/port_forward.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# Inspiration and code snippets used from:
from __future__ import annotations
from cowrie.ssh_proxy.protocols import base_protocol
class PortForward(base_protocol.BaseProtocol):
def __init__(self, uuid, chan_name, ssh):
super().__init__(uuid, chan_name, ssh)
def parse_packet(self, parent: str, payload: bytes) -> None:
pass
| 1,927 | 43.837209 | 91 | py |
cowrie | cowrie-master/src/cowrie/commands/wc.py | # All rights reserved.
# All rights given to Cowrie project
"""
This module contains the wc commnad
"""
from __future__ import annotations
import getopt
import re
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_wc(HoneyPotCommand):
"""
wc command
"""
def version(self) -> None:
self.writeBytes(b"wc (GNU coreutils) 8.30\n")
self.writeBytes(b"Copyright (C) 2018 Free Software Foundation, Inc.\n")
self.writeBytes(
b"License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.\n"
)
self.writeBytes(
b"This is free software: you are free to change and redistribute it.\n"
)
self.writeBytes(b"There is NO WARRANTY, to the extent permitted by law.\n")
self.writeBytes(b"\n")
self.writeBytes(b"Written by Paul Rubin and David MacKenzie.\n")
def help(self) -> None:
self.writeBytes(b"Usage: wc [OPTION]... [FILE]...\n")
self.writeBytes(
b"Print newline, word, and byte counts for each FILE, and a total line if\n"
)
self.writeBytes(
b"more than one FILE is specified. A word is a non-zero-length sequence of\n"
)
self.writeBytes(b"characters delimited by white space.\n")
self.writeBytes(b"\n")
self.writeBytes(b"With no FILE, or when FILE is -, read standard input.\n")
self.writeBytes(b"\n")
self.writeBytes(
b"The options below may be used to select which counts are printed, always in\n"
)
self.writeBytes(
b"the following order: newline, word, character, byte, maximum line length.\n"
)
self.writeBytes(b"\t-c\tprint the byte counts\n")
self.writeBytes(b"\t-m\tprint the character counts\n")
self.writeBytes(b"\t-l\tprint the newline counts\n")
self.writeBytes(b"\t-w\tprint the word counts\n")
self.writeBytes(b"\t-h\tdisplay this help and exit\n")
self.writeBytes(b"\t-v\toutput version information and exit\n")
def wc_get_contents(self, filename: str, optlist: list[tuple[str, str]]) -> None:
try:
contents = self.fs.file_contents(filename)
self.wc_application(contents, optlist)
except Exception:
self.errorWrite(f"wc: {filename}: No such file or directory\n")
def wc_application(self, contents: bytes, optlist: list[tuple[str, str]]) -> None:
for opt, _arg in optlist:
if opt == "-l":
contentsplit = contents.split(b"\n")
self.write(f"{len(contentsplit) - 1}\n")
elif opt == "-w":
contentsplit = re.sub(b" +", b" ", contents.strip(b"\n").strip()).split(
b" "
)
self.write(f"{len(contentsplit)}\n")
elif opt == "-m" or opt == "-c":
self.write(f"{len(contents)}\n")
elif opt == "-v":
self.version()
else:
self.help()
def start(self) -> None:
if not self.args:
self.exit()
return
if self.args[0] == ">":
pass
else:
try:
optlist, args = getopt.getopt(self.args, "cmlLwhv")
except getopt.GetoptError as err:
self.errorWrite(f"wc: invalid option -- {err.opt}\n")
self.help()
self.exit()
return
for opt in optlist:
if opt[0] == "-v":
self.version()
self.exit()
return
if opt[0] == "-h":
self.help()
self.exit()
return
if not self.input_data:
files = self.check_arguments("wc", args[1:])
for pname in files:
self.wc_get_contents(pname, optlist)
else:
self.wc_application(self.input_data, optlist)
self.exit()
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.command.input",
realm="wc",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
def handle_CTRL_D(self) -> None:
self.exit()
commands["/usr/bin/wc"] = Command_wc
commands["/bin/wc"] = Command_wc
commands["wc"] = Command_wc
| 4,525 | 32.279412 | 96 | py |
cowrie | cowrie-master/src/cowrie/commands/nc.py | from __future__ import annotations
import getopt
import ipaddress
import re
import socket
import struct
from cowrie.core.config import CowrieConfig
from cowrie.shell.command import HoneyPotCommand
long = int
commands = {}
def makeMask(n: int) -> int:
"""
return a mask of n bits as a long integer
"""
return (long(2) << n - 1) - 1
def dottedQuadToNum(ip: str) -> int:
"""
convert decimal dotted quad string to long integer
this will throw builtins.OSError on failure
"""
ip32bit: bytes = socket.inet_aton(ip)
num: int = struct.unpack("I", ip32bit)[0]
return num
def networkMask(ip: str, bits: int) -> int:
"""
Convert a network address to a long integer
"""
return dottedQuadToNum(ip) & makeMask(bits)
def addressInNetwork(ip: int, net: int) -> int:
"""
Is an address in a network
"""
return ip & net == net
class Command_nc(HoneyPotCommand):
"""
netcat
"""
s: socket.socket
def help(self) -> None:
self.write(
"""This is nc from the netcat-openbsd package. An alternative nc is available
in the netcat-traditional package.
usage: nc [-46bCDdhjklnrStUuvZz] [-I length] [-i interval] [-O length]
[-P proxy_username] [-p source_port] [-q seconds] [-s source]
[-T toskeyword] [-V rtable] [-w timeout] [-X proxy_protocol]
[-x proxy_address[:port]] [destination] [port]\n"""
)
def start(self) -> None:
try:
optlist, args = getopt.getopt(
self.args, "46bCDdhklnrStUuvZzI:i:O:P:p:q:s:T:V:w:X:x:"
)
except getopt.GetoptError:
self.help()
self.exit()
return
if not args or len(args) < 2:
self.help()
self.exit()
return
host = args[0]
port = args[1]
if not re.match(r"^\d+$", port):
self.errorWrite(f"nc: port number invalid: {port}\n")
self.exit()
return
if re.match(r"^\d+$", host):
address = int(host)
elif re.match(r"^[\d\.]+$", host):
try:
address = dottedQuadToNum(host)
except OSError:
self.exit()
return
else:
# TODO: should do dns lookup
self.exit()
return
if ipaddress.ip_address(address).is_private:
self.exit()
return
out_addr = None
try:
out_addr = (CowrieConfig.get("honeypot", "out_addr"), 0)
except Exception:
out_addr = ("0.0.0.0", 0)
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.bind(out_addr)
try:
self.s.connect((host, int(port)))
self.recv_data()
except Exception:
self.exit()
def recv_data(self) -> None:
data = b""
while 1:
packet = self.s.recv(1024)
if packet == b"":
break
else:
data += packet
self.writeBytes(data)
self.s.close()
self.exit()
def lineReceived(self, line: str) -> None:
if hasattr(self, "s"):
self.s.send(line.encode("utf8"))
def handle_CTRL_C(self) -> None:
self.write("^C\n")
if hasattr(self, "s"):
self.s.close()
def handle_CTRL_D(self) -> None:
if hasattr(self, "s"):
self.s.close()
commands["/bin/nc"] = Command_nc
commands["nc"] = Command_nc
| 3,568 | 23.278912 | 89 | py |
cowrie | cowrie-master/src/cowrie/commands/base.py |
from __future__ import annotations
import codecs
import datetime
import getopt
import random
import re
import time
from typing import Optional
from collections.abc import Callable
from twisted.internet import error, reactor
from twisted.python import failure, log
from cowrie.core import utils
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.honeypot import HoneyPotShell
commands: dict[str, Callable] = {}
class Command_whoami(HoneyPotCommand):
def call(self) -> None:
self.write(f"{self.protocol.user.username}\n")
commands["/usr/bin/whoami"] = Command_whoami
commands["whoami"] = Command_whoami
commands["/usr/bin/users"] = Command_whoami
commands["users"] = Command_whoami
class Command_help(HoneyPotCommand):
def call(self) -> None:
self.write(
"""GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)
These shell commands are defined internally. Type `help' to see this list.
Type `help name' to find out more about the function `name'.
Use `info bash' to find out more about the shell in general.
Use `man -k' or `info' to find out more about commands not in this list.
A star (*) next to a name means that the command is disabled.
job_spec [&] history [-c] [-d offset] [n] or history -anrw [filename] or history -ps arg [arg...]
(( expression )) if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
. filename [arguments] jobs [-lnprs] [jobspec ...] or jobs -x command [args]
: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
[ arg... ] let arg [arg ...]
[[ expression ]] local [option] name[=value] ...
alias [-p] [name[=value] ... ] logout [n]
bg [job_spec ...] mapfile [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]
bind [-lpvsPVS] [-m keymap] [-f filename] [-q name] [-u name] [-r keyseq] [-x keyseq:shell-c> popd [-n] [+N | -N]
break [n] printf [-v var] format [arguments]
builtin [shell-builtin [arg ...]] pushd [-n] [+N | -N | dir]
caller [expr] pwd [-LP]
case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout>
cd [-L|[-P [-e]]] [dir] readarray [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]>
command [-pVv] command [arg ...] readonly [-aAf] [name[=value] ...] or readonly -p
compgen [-abcdefgjksuv] [-o option] [-A action] [-G globpat] [-W wordlist] [-F function] [> return [n]
complete [-abcdefgjksuv] [-pr] [-DE] [-o option] [-A action] [-G globpat] [-W wordlist] [-F> select NAME [in WORDS ... ;] do COMMANDS; done
compopt [-o|+o option] [-DE] [name ...] set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
continue [n] shift [n]
coproc [NAME] command [redirections] shopt [-pqsu] [-o] [optname ...]
declare [-aAfFgilrtux] [-p] [name[=value] ...] source filename [arguments]
dirs [-clpv] [+N] [-N] suspend [-f]
disown [-h] [-ar] [jobspec ...] test [expr]
echo [-neE] [arg ...] time [-p] pipeline
enable [-a] [-dnps] [-f filename] [name ...] times
eval [arg ...] trap [-lp] [[arg] signal_spec ...]
exec [-cl] [-a name] [command [arguments ...]] [redirection ...] true
exit [n] type [-afptP] name [name ...]
export [-fn] [name[=value] ...] or export -p typeset [-aAfFgilrtux] [-p] name[=value] ...
false ulimit [-SHacdefilmnpqrstuvx] [limit]
fc [-e ename] [-lnr] [first] [last] or fc -s [pat=rep] [command] umask [-p] [-S] [mode]
fg [job_spec] unalias [-a] name [name ...]
for NAME [in WORDS ... ] ; do COMMANDS; done unset [-f] [-v] [name ...]
for (( exp1; exp2; exp3 )); do COMMANDS; done until COMMANDS; do COMMANDS; done
function name { COMMANDS ; } or name () { COMMANDS ; } variables - Names and meanings of some shell variables
getopts optstring name [arg] wait [id]
hash [-lr] [-p pathname] [-dt] [name ...] while COMMANDS; do COMMANDS; done
help [-dms] [pattern ...] { COMMANDS ; }\n"""
)
commands["help"] = Command_help
class Command_w(HoneyPotCommand):
def call(self) -> None:
self.write(
" {} up {}, 1 user, load average: 0.00, 0.00, 0.00\n".format(
time.strftime("%H:%M:%S"), utils.uptime(self.protocol.uptime())
)
)
self.write(
"USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT\n"
)
self.write(
"%-8s pts/0 %s %s 0.00s 0.00s 0.00s w\n"
% (
self.protocol.user.username,
self.protocol.clientIP[:17].ljust(17),
time.strftime("%H:%M", time.localtime(self.protocol.logintime)),
)
)
commands["/usr/bin/w"] = Command_w
commands["w"] = Command_w
class Command_who(HoneyPotCommand):
def call(self) -> None:
self.write(
"%-8s pts/0 %s %s (%s)\n"
% (
self.protocol.user.username,
time.strftime("%Y-%m-%d", time.localtime(self.protocol.logintime)),
time.strftime("%H:%M", time.localtime(self.protocol.logintime)),
self.protocol.clientIP,
)
)
commands["/usr/bin/who"] = Command_who
commands["who"] = Command_who
class Command_echo(HoneyPotCommand):
def call(self) -> None:
newline = True
escape_decode = False
try:
optlist, args = getopt.getopt(self.args, "eEn")
for opt in optlist:
if opt[0] == "-e":
escape_decode = True
elif opt[0] == "-E":
escape_decode = False
elif opt[0] == "-n":
newline = False
except Exception:
args = self.args
try:
# replace r'\\x' with r'\x'
string = " ".join(args).replace(r"\\x", r"\x")
# replace single character escape \x0 with \x00
string = re.sub(
r"(?<=\\)x([0-9a-fA-F])(?=\\|\"|\'|\s|$)", r"x0\g<1>", string
)
# if the string ends with \c escape, strip it and set newline flag to False
if string.endswith("\\c"):
string = string[:-2]
newline = False
if newline is True:
string += "\n"
if escape_decode:
data: bytes = codecs.escape_decode(string)[0] # type: ignore
self.writeBytes(data)
else:
self.write(string)
except ValueError:
log.msg("echo command received Python incorrect hex escape")
commands["/bin/echo"] = Command_echo
commands["echo"] = Command_echo
class Command_printf(HoneyPotCommand):
def call(self) -> None:
if not self.args:
self.write("printf: usage: printf [-v var] format [arguments]\n")
else:
if "-v" not in self.args and len(self.args) < 2:
# replace r'\\x' with r'\x'
s = "".join(self.args[0]).replace("\\\\x", "\\x")
# replace single character escape \x0 with \x00
s = re.sub(r"(?<=\\)x([0-9a-fA-F])(?=\\|\"|\'|\s|$)", r"x0\g<1>", s)
# strip single and double quotes
s = s.strip("\"'")
# if the string ends with \c escape, strip it
if s.endswith("\\c"):
s = s[:-2]
data: bytes = codecs.escape_decode(s)[0] # type: ignore
self.writeBytes(data)
commands["/usr/bin/printf"] = Command_printf
commands["printf"] = Command_printf
class Command_exit(HoneyPotCommand):
def call(self) -> None:
stat = failure.Failure(error.ProcessDone(status=""))
self.protocol.terminal.transport.processEnded(stat)
def exit(self) -> None:
pass
commands["exit"] = Command_exit
commands["logout"] = Command_exit
class Command_clear(HoneyPotCommand):
def call(self) -> None:
self.protocol.terminal.reset()
commands["/usr/bin/clear"] = Command_clear
commands["clear"] = Command_clear
commands["/usr/bin/reset"] = Command_clear
commands["reset"] = Command_clear
class Command_hostname(HoneyPotCommand):
def call(self) -> None:
if self.args:
if self.protocol.user.username == "root":
self.protocol.hostname = self.args[0]
else:
self.write("hostname: you must be root to change the host name\n")
else:
self.write(f"{self.protocol.hostname}\n")
commands["/bin/hostname"] = Command_hostname
commands["hostname"] = Command_hostname
class Command_ps(HoneyPotCommand):
def call(self) -> None:
user = self.protocol.user.username
args = ""
if self.args:
args = self.args[0].strip()
(
_user,
_pid,
_cpu,
_mem,
_vsz,
_rss,
_tty,
_stat,
_start,
_time,
_command,
) = list(range(11))
output_array = []
output = (
"%s".ljust(15 - len("USER")) % "USER",
"%s".ljust(8 - len("PID")) % "PID",
"%s".ljust(13 - len("%CPU")) % "%CPU",
"%s".ljust(13 - len("%MEM")) % "%MEM",
"%s".ljust(12 - len("VSZ")) % "VSZ",
"%s".ljust(12 - len("RSS")) % "RSS",
"%s".ljust(10 - len("TTY")) % "TTY",
"%s".ljust(8 - len("STAT")) % "STAT",
"%s".ljust(8 - len("START")) % "START",
"%s".ljust(8 - len("TIME")) % "TIME",
"%s".ljust(30 - len("COMMAND")) % "COMMAND",
)
output_array.append(output)
if self.protocol.user.server.process:
for single_ps in self.protocol.user.server.process:
output = (
"%s".ljust(15 - len(str(single_ps["USER"])))
% str(single_ps["USER"]),
"%s".ljust(8 - len(str(single_ps["PID"]))) % str(single_ps["PID"]),
"%s".ljust(13 - len(str(round(single_ps["CPU"], 2))))
% str(round(single_ps["CPU"], 2)),
"%s".ljust(13 - len(str(round(single_ps["MEM"], 2))))
% str(round(single_ps["MEM"], 2)),
"%s".ljust(12 - len(str(single_ps["VSZ"]))) % str(single_ps["VSZ"]),
"%s".ljust(12 - len(str(single_ps["RSS"]))) % str(single_ps["RSS"]),
"%s".ljust(10 - len(str(single_ps["TTY"]))) % str(single_ps["TTY"]),
"%s".ljust(8 - len(str(single_ps["STAT"])))
% str(single_ps["STAT"]),
"%s".ljust(8 - len(str(single_ps["START"])))
% str(single_ps["START"]),
"%s".ljust(8 - len(str(single_ps["TIME"])))
% str(single_ps["TIME"]),
"%s".ljust(30 - len(str(single_ps["COMMAND"])))
% str(single_ps["COMMAND"]),
)
output_array.append(output)
process = random.randint(4000, 8000)
output = (
"%s".ljust(15 - len("root")) % "root",
"%s".ljust(8 - len(str(process))) % str(process),
"%s".ljust(13 - len("0.0")) % "0.0",
"%s".ljust(13 - len("0.1")) % "0.1",
"%s".ljust(12 - len("5416")) % "5416",
"%s".ljust(12 - len("1024")) % "1024",
"%s".ljust(10 - len("?")) % "?",
"%s".ljust(8 - len("Ss")) % "Ss",
"%s".ljust(8 - len("Jul22")) % "Jul22",
"%s".ljust(8 - len("0:00")) % "0:00",
"%s".ljust(30 - len("/usr/sbin/sshd: %s@pts/0"))
% "/usr/sbin/sshd: %s@pts/0"
% user,
)
output_array.append(output)
process = process + 5
output = (
"%s".ljust(15 - len(user)) % user,
"%s".ljust(8 - len(str(process))) % str(process),
"%s".ljust(13 - len("0.0")) % "0.0",
"%s".ljust(13 - len("0.1")) % "0.1",
"%s".ljust(12 - len("2925")) % "5416",
"%s".ljust(12 - len("1541")) % "1024",
"%s".ljust(10 - len("pts/0")) % "pts/0",
"%s".ljust(8 - len("Ss")) % "Ss",
"%s".ljust(8 - len("06:30")) % "06:30",
"%s".ljust(8 - len("0:00")) % "0:00",
"%s".ljust(30 - len("bash")) % "-bash",
)
output_array.append(output)
process = process + 2
output = (
"%s".ljust(15 - len(user)) % user,
"%s".ljust(8 - len(str(process))) % str(process),
"%s".ljust(13 - len("0.0")) % "0.0",
"%s".ljust(13 - len("0.1")) % "0.1",
"%s".ljust(12 - len("2435")) % "2435",
"%s".ljust(12 - len("929")) % "929",
"%s".ljust(10 - len("pts/0")) % "pts/0",
"%s".ljust(8 - len("Ss")) % "Ss",
"%s".ljust(8 - len("06:30")) % "06:30",
"%s".ljust(8 - len("0:00")) % "0:00",
"%s".ljust(30 - len("ps")) % "ps %s" % " ".join(self.args),
)
output_array.append(output)
else:
output_array = [
(
"USER ",
" PID",
" %CPU",
" %MEM",
" VSZ",
" RSS",
" TTY ",
"STAT ",
"START",
" TIME ",
"COMMAND",
),
(
"root ",
" 1",
" 0.0",
" 0.1",
" 2100",
" 688",
" ? ",
"Ss ",
"Nov06",
" 0:07 ",
"init [2] ",
),
(
"root ",
" 2",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[kthreadd]",
),
(
"root ",
" 3",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[migration/0]",
),
(
"root ",
" 4",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[ksoftirqd/0]",
),
(
"root ",
" 5",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[watchdog/0]",
),
(
"root ",
" 6",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:17 ",
"[events/0]",
),
(
"root ",
" 7",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[khelper]",
),
(
"root ",
" 39",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[kblockd/0]",
),
(
"root ",
" 41",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[kacpid]",
),
(
"root ",
" 42",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[kacpi_notify]",
),
(
"root ",
" 170",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[kseriod]",
),
(
"root ",
" 207",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S ",
"Nov06",
" 0:01 ",
"[pdflush]",
),
(
"root ",
" 208",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S ",
"Nov06",
" 0:00 ",
"[pdflush]",
),
(
"root ",
" 209",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[kswapd0]",
),
(
"root ",
" 210",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[aio/0]",
),
(
"root ",
" 748",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[ata/0]",
),
(
"root ",
" 749",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[ata_aux]",
),
(
"root ",
" 929",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[scsi_eh_0]",
),
(
"root ",
"1014",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"D< ",
"Nov06",
" 0:03 ",
"[kjournald]",
),
(
"root ",
"1087",
" 0.0",
" 0.1",
" 2288",
" 772",
" ? ",
"S<s ",
"Nov06",
" 0:00 ",
"udevd --daemon",
),
(
"root ",
"1553",
" 0.0",
" 0.0",
" 0",
" 0",
" ? ",
"S< ",
"Nov06",
" 0:00 ",
"[kpsmoused]",
),
(
"root ",
"2054",
" 0.0",
" 0.2",
" 28428",
" 1508",
" ? ",
"Sl ",
"Nov06",
" 0:01 ",
"/usr/sbin/rsyslogd -c3",
),
(
"root ",
"2103",
" 0.0",
" 0.2",
" 2628",
" 1196",
" tty1 ",
"Ss ",
"Nov06",
" 0:00 ",
"/bin/login -- ",
),
(
"root ",
"2105",
" 0.0",
" 0.0",
" 1764",
" 504",
" tty2 ",
"Ss+ ",
"Nov06",
" 0:00 ",
"/sbin/getty 38400 tty2",
),
(
"root ",
"2107",
" 0.0",
" 0.0",
" 1764",
" 504",
" tty3 ",
"Ss+ ",
"Nov06",
" 0:00 ",
"/sbin/getty 38400 tty3",
),
(
"root ",
"2109",
" 0.0",
" 0.0",
" 1764",
" 504",
" tty4 ",
"Ss+ ",
"Nov06",
" 0:00 ",
"/sbin/getty 38400 tty4",
),
(
"root ",
"2110",
" 0.0",
" 0.0",
" 1764",
" 504",
" tty5 ",
"Ss+ ",
"Nov06",
" 0:00 ",
"/sbin/getty 38400 tty5",
),
(
"root ",
"2112",
" 0.0",
" 0.0",
" 1764",
" 508",
" tty6 ",
"Ss+ ",
"Nov06",
" 0:00 ",
"/sbin/getty 38400 tty6",
),
(
"root ",
"2133",
" 0.0",
" 0.1",
" 2180",
" 620",
" ? ",
"S<s ",
"Nov06",
" 0:00 ",
"dhclient3 -pf /var/run/dhclient.eth0.pid -lf /var/lib/dhcp3/dhclien",
),
(
"root ",
"4969",
" 0.0",
" 0.1",
" 5416",
" 1024",
" ? ",
"Ss ",
"Nov08",
" 0:00 ",
"/usr/sbin/sshd: %s@pts/0" % user,
),
(
"%s".ljust(8) % user,
"5673",
" 0.0",
" 0.2",
" 2924",
" 1540",
" pts/0 ",
"Ss ",
"04:30",
" 0:00 ",
"-bash",
),
(
"%s".ljust(8) % user,
"5679",
" 0.0",
" 0.1",
" 2432",
" 928",
" pts/0 ",
"R+ ",
"04:32",
" 0:00 ",
"ps %s" % " ".join(self.args),
),
]
for i in range(len(output_array)):
if i != 0:
if "a" not in args and output_array[i][_user].strip() != user:
continue
elif (
"a" not in args
and "x" not in args
and output_array[i][_tty].strip() != "pts/0"
):
continue
line = [_pid, _tty, _time, _command]
if "a" in args or "x" in args:
line = [_pid, _tty, _stat, _time, _command]
if "u" in args:
line = [
_user,
_pid,
_cpu,
_mem,
_vsz,
_rss,
_tty,
_stat,
_start,
_time,
_command,
]
s = "".join([output_array[i][x] for x in line])
if "w" not in args:
s = s[
: (
int(self.environ["COLUMNS"])
if "COLUMNS" in self.environ
else 80
)
]
self.write(f"{s}\n")
commands["/bin/ps"] = Command_ps
commands["ps"] = Command_ps
class Command_id(HoneyPotCommand):
def call(self) -> None:
u = self.protocol.user
self.write(
"uid={}({}) gid={}({}) groups={}({})\n".format(
u.uid, u.username, u.gid, u.username, u.gid, u.username
)
)
commands["/usr/bin/id"] = Command_id
commands["id"] = Command_id
class Command_passwd(HoneyPotCommand):
def start(self) -> None:
self.write("Enter new UNIX password: ")
self.protocol.password_input = True
self.callbacks = [self.ask_again, self.finish]
self.passwd: Optional[str] = None
def ask_again(self, line: str) -> None:
self.passwd = line
self.write("Retype new UNIX password: ")
def finish(self, line: str) -> None:
self.protocol.password_input = False
if line != self.passwd or self.passwd == "*":
self.write("Sorry, passwords do not match\n")
else:
self.write("passwd: password updated successfully\n")
self.exit()
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.command.success",
realm="passwd",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
self.password = line.strip()
self.callbacks.pop(0)(line)
commands["/usr/bin/passwd"] = Command_passwd
commands["passwd"] = Command_passwd
class Command_shutdown(HoneyPotCommand):
def start(self) -> None:
if self.args and self.args[0].strip().count("--help"):
output = [
"Usage: shutdown [-akrhHPfnc] [-t secs] time [warning message]",
"-a: use /etc/shutdown.allow ",
"-k: don't really shutdown, only warn. ",
"-r: reboot after shutdown. ",
"-h: halt after shutdown. ",
"-P: halt action is to turn off power. ",
"-H: halt action is to just halt. ",
"-f: do a 'fast' reboot (skip fsck). ",
"-F: Force fsck on reboot. ",
'-n: do not go through "init" but go down real fast. ',
"-c: cancel a running shutdown. ",
"-t secs: delay between warning and kill signal. ",
'** the "time" argument is mandatory! (try "now") **',
]
for line in output:
self.write(f"{line}\n")
self.exit()
elif (
len(self.args) > 1
and self.args[0].strip().count("-h")
and self.args[1].strip().count("now")
):
self.write("\n")
self.write(
f"Broadcast message from root@{self.protocol.hostname} (pts/0) ({time.ctime()}):\n"
)
self.write("\n")
self.write("The system is going down for maintenance NOW!\n")
reactor.callLater(3, self.finish) # type: ignore[attr-defined]
elif (
len(self.args) > 1
and self.args[0].strip().count("-r")
and self.args[1].strip().count("now")
):
self.write("\n")
self.write(
f"Broadcast message from root@{self.protocol.hostname} (pts/0) ({time.ctime()}):\n"
)
self.write("\n")
self.write("The system is going down for reboot NOW!\n")
reactor.callLater(3, self.finish) # type: ignore[attr-defined]
else:
self.write("Try `shutdown --help' for more information.\n")
self.exit()
def finish(self) -> None:
stat = failure.Failure(error.ProcessDone(status=""))
self.protocol.terminal.transport.processEnded(stat)
commands["/sbin/shutdown"] = Command_shutdown
commands["shutdown"] = Command_shutdown
commands["/sbin/poweroff"] = Command_shutdown
commands["poweroff"] = Command_shutdown
commands["/sbin/halt"] = Command_shutdown
commands["halt"] = Command_shutdown
class Command_reboot(HoneyPotCommand):
def start(self) -> None:
self.write("\n")
self.write(
f"Broadcast message from root@{self.protocol.hostname} (pts/0) ({time.ctime()}):\n\n"
)
self.write("The system is going down for reboot NOW!\n")
reactor.callLater(3, self.finish) # type: ignore[attr-defined]
def finish(self) -> None:
stat = failure.Failure(error.ProcessDone(status=""))
self.protocol.terminal.transport.processEnded(stat)
commands["/sbin/reboot"] = Command_reboot
commands["reboot"] = Command_reboot
class Command_history(HoneyPotCommand):
def call(self) -> None:
try:
if self.args and self.args[0] == "-c":
self.protocol.historyLines = []
self.protocol.historyPosition = 0
return
count = 1
for line in self.protocol.historyLines:
self.write(f" {str(count).rjust(4)} {line}\n")
count += 1
except Exception:
# Non-interactive shell, do nothing
pass
commands["history"] = Command_history
class Command_date(HoneyPotCommand):
def call(self) -> None:
time = datetime.datetime.utcnow()
self.write("{}\n".format(time.strftime("%a %b %d %H:%M:%S UTC %Y")))
commands["/bin/date"] = Command_date
commands["date"] = Command_date
class Command_yes(HoneyPotCommand):
def start(self) -> None:
self.y()
def y(self) -> None:
if self.args:
self.write("{}\n".format(" ".join(self.args)))
else:
self.write("y\n")
self.scheduled = reactor.callLater(0.01, self.y) # type: ignore[attr-defined]
def handle_CTRL_C(self) -> None:
self.scheduled.cancel()
self.exit()
commands["/usr/bin/yes"] = Command_yes
commands["yes"] = Command_yes
class Command_sh(HoneyPotCommand):
def call(self) -> None:
if self.args and self.args[0].strip() == "-c":
line = " ".join(self.args[1:])
# it might be sh -c 'echo "sometext"', so don't use line.strip('\'\"')
if (line[0] == "'" and line[-1] == "'") or (
line[0] == '"' and line[-1] == '"'
):
line = line[1:-1]
self.execute_commands(line)
elif self.input_data:
self.execute_commands(self.input_data.decode("utf8"))
# TODO: handle spawning multiple shells, support other sh flags
def execute_commands(self, cmds: str) -> None:
# self.input_data holds commands passed via PIPE
# create new HoneyPotShell for our a new 'sh' shell
self.protocol.cmdstack.append(HoneyPotShell(self.protocol, interactive=False))
# call lineReceived method that indicates that we have some commands to parse
self.protocol.cmdstack[-1].lineReceived(cmds)
# remove the shell
self.protocol.cmdstack.pop()
commands["/bin/bash"] = Command_sh
commands["bash"] = Command_sh
commands["/bin/sh"] = Command_sh
commands["sh"] = Command_sh
class Command_php(HoneyPotCommand):
HELP = (
"Usage: php [options] [-f] <file> [--] [args...]\n"
" php [options] -r <code> [--] [args...]\n"
" php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]\n"
" php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]\n"
" php [options] -- [args...]\n"
" php [options] -a\n"
"\n"
" -a Run interactively\n"
" -c <path>|<file> Look for php.ini file in this directory\n"
" -n No php.ini file will be used\n"
" -d foo[=bar] Define INI entry foo with value 'bar'\n"
" -e Generate extended information for debugger/profiler\n"
" -f <file> Parse and execute <file>.\n"
" -h This help\n"
" -i PHP information\n"
" -l Syntax check only (lint)\n"
" -m Show compiled in modules\n"
" -r <code> Run PHP <code> without using script tags <?..?>\n"
" -B <begin_code> Run PHP <begin_code> before processing input lines\n"
" -R <code> Run PHP <code> for every input line\n"
" -F <file> Parse and execute <file> for every input line\n"
" -E <end_code> Run PHP <end_code> after processing all input lines\n"
" -H Hide any passed arguments from external tools.\n"
" -s Output HTML syntax highlighted source.\n"
" -v Version number\n"
" -w Output source with stripped comments and whitespace.\n"
" -z <file> Load Zend extension <file>.\n"
"\n"
" args... Arguments passed to script. Use -- args when first argument\n"
" starts with - or script is read from stdin\n"
"\n"
" --ini Show configuration file names\n"
"\n"
" --rf <name> Show information about function <name>.\n"
" --rc <name> Show information about class <name>.\n"
" --re <name> Show information about extension <name>.\n"
" --ri <name> Show configuration for extension <name>.\n"
"\n"
)
VERSION = "PHP 5.3.5 (cli)\n" "Copyright (c) 1997-2010 The PHP Group\n"
def start(self) -> None:
if self.args:
if self.args[0] == "-v":
self.write(Command_php.VERSION)
elif self.args[0] == "-h":
self.write(Command_php.HELP)
self.exit()
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.command.success",
realm="php",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
def handle_CTRL_D(self) -> None:
self.exit()
commands["/usr/bin/php"] = Command_php
commands["php"] = Command_php
class Command_chattr(HoneyPotCommand):
def call(self) -> None:
if len(self.args) < 1:
self.write("Usage: chattr [-RVf] [-+=AacDdeijsSu] [-v version] files...\n")
return
elif len(self.args) < 2:
self.write("Must use '-v', =, - or +'\n")
return
if not self.fs.exists(self.args[1]):
self.write(
"chattr: No such file or directory while trying to stat "
+ self.args[1]
+ "\n"
)
commands["/usr/bin/chattr"] = Command_chattr
commands["chattr"] = Command_chattr
class Command_set(HoneyPotCommand):
# Basic functionaltly (show only), need enhancements
# This will show ALL environ vars, not only the global ones
# With enhancements it should work like env when -o posix is used
def call(self) -> None:
for i in sorted(list(self.environ.keys())):
self.write(f"{i}={self.environ[i]}\n")
commands["set"] = Command_set
class Command_nop(HoneyPotCommand):
def call(self) -> None:
pass
commands["umask"] = Command_nop
commands["unset"] = Command_nop
commands["export"] = Command_nop
commands["alias"] = Command_nop
commands["jobs"] = Command_nop
commands["kill"] = Command_nop
commands["/bin/kill"] = Command_nop
commands["/bin/pkill"] = Command_nop
commands["/bin/killall"] = Command_nop
commands["/bin/killall5"] = Command_nop
commands["/bin/su"] = Command_nop
commands["su"] = Command_nop
commands["/bin/chown"] = Command_nop
commands["chown"] = Command_nop
commands["/bin/chgrp"] = Command_nop
commands["chgrp"] = Command_nop
commands["/usr/bin/chattr"] = Command_nop
commands["chattr"] = Command_nop
commands[":"] = Command_nop
commands["do"] = Command_nop
commands["done"] = Command_nop
| 41,589 | 34.486348 | 188 | py |
cowrie | cowrie-master/src/cowrie/commands/chpasswd.py | # All rights reserved.
# All rights given to Cowrie project
"""
This module contains the chpasswd commnad
"""
from __future__ import annotations
import getopt
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_chpasswd(HoneyPotCommand):
def help(self) -> None:
output = (
"Usage: chpasswd [options]",
"",
"Options:",
" -c, --crypt-method METHOD the crypt method (one of NONE DES MD5 SHA256 SHA512)",
" -e, --encrypted supplied passwords are encrypted",
" -h, --help display this help message and exit",
" -m, --md5 encrypt the clear text password using",
" the MD5 algorithm"
" -R, --root CHROOT_DIR directory to chroot into"
" -s, --sha-rounds number of SHA rounds for the SHA*"
" crypt algorithms",
)
for line in output:
self.write(line + "\n")
def chpasswd_application(self, contents: bytes) -> None:
c = 1
try:
for line in contents.split(b"\n"):
if len(line):
u, p = line.split(b":")
if not len(p):
self.write(f"chpasswd: line {c}: missing new password\n")
else:
pass
"""
TODO:
- update shadow file
- update userDB.txt (???)
- updte auth_random.json (if in use)
"""
c += 1
except Exception:
self.write(f"chpasswd: line {c}: missing new password\n")
def start(self) -> None:
try:
opts, args = getopt.getopt(
self.args,
"c:ehmr:s:",
["crypt-method", "encrypted", "help", "md5", "root", "sha-rounds"],
)
except getopt.GetoptError:
self.help()
self.exit()
return
# Parse options
for o, a in opts:
if o in "-h":
self.help()
self.exit()
return
elif o in "-c":
if a not in ["NONE", "DES", "MD5", "SHA256", "SHA512"]:
self.errorWrite(f"chpasswd: unsupported crypt method: {a}\n")
self.help()
self.exit()
if not self.input_data:
pass
else:
self.chpasswd_application(self.input_data)
self.exit()
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.command.input",
realm="chpasswd",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
self.chpasswd_application(line.encode())
def handle_CTRL_D(self) -> None:
self.exit()
commands["/usr/sbin/chpasswd"] = Command_chpasswd
commands["chpasswd"] = Command_chpasswd
| 3,241 | 30.475728 | 99 | py |
cowrie | cowrie-master/src/cowrie/commands/which.py |
from __future__ import annotations
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_which(HoneyPotCommand):
# Do not resolve args
resolve_args = False
def call(self) -> None:
"""
Look up all the arguments on PATH and print each (first) result
"""
# No arguments, just exit
if not len(self.args) or "PATH" not in self.environ:
return
# Look up each file
for f in self.args:
for path in self.environ["PATH"].split(":"):
resolved = self.fs.resolve_path(f, path)
if self.fs.exists(resolved):
self.write(f"{path}/{f}\n")
commands["which"] = Command_which
| 806 | 23.454545 | 72 | py |
cowrie | cowrie-master/src/cowrie/commands/sleep.py | # All rights reserved.
"""
This module contains the sleep command
"""
from __future__ import annotations
import re
from twisted.internet import reactor
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_sleep(HoneyPotCommand):
"""
Sleep
"""
pattern = re.compile(r"(\d+)[mhs]?")
def done(self) -> None:
self.exit()
def start(self) -> None:
if len(self.args) == 1:
m = re.match(r"(\d+)[mhs]?", self.args[0])
if m:
_time = int(m.group(1))
# Always sleep in seconds, not minutes or hours
self.scheduled = reactor.callLater(_time, self.done) # type: ignore[attr-defined]
else:
self.write("usage: sleep seconds\n")
self.exit()
else:
self.write("usage: sleep seconds\n")
self.exit()
commands["/bin/sleep"] = Command_sleep
commands["sleep"] = Command_sleep
| 1,038 | 21.586957 | 98 | py |
cowrie | cowrie-master/src/cowrie/commands/scp.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
import getopt
import hashlib
import os
import re
import time
from twisted.python import log
from cowrie.core.config import CowrieConfig
from cowrie.shell import fs
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_scp(HoneyPotCommand):
"""
scp command
"""
download_path = CowrieConfig.get("honeypot", "download_path")
download_path_uniq = CowrieConfig.get(
"honeypot", "download_path_uniq", fallback=download_path
)
out_dir: str = ""
def help(self) -> None:
self.write(
"""usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]
[-l limit] [-o ssh_option] [-P port] [-S program]
[[user@]host1:]file1 ... [[user@]host2:]file2\n"""
)
def start(self) -> None:
try:
optlist, args = getopt.getopt(self.args, "12346BCpqrvfstdv:cFiloPS:")
except getopt.GetoptError:
self.help()
self.exit()
return
self.out_dir = ""
for opt in optlist:
if opt[0] == "-d":
self.out_dir = args[0]
break
if self.out_dir:
outdir = self.fs.resolve_path(self.out_dir, self.protocol.cwd)
if not self.fs.exists(outdir):
self.errorWrite(f"-scp: {self.out_dir}: No such file or directory\n")
self.exit()
self.write("\x00")
self.write("\x00")
self.write("\x00")
self.write("\x00")
self.write("\x00")
self.write("\x00")
self.write("\x00")
self.write("\x00")
self.write("\x00")
self.write("\x00")
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.session.file_download",
realm="scp",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
self.protocol.terminal.write("\x00")
def drop_tmp_file(self, data: bytes, name: str) -> None:
tmp_fname = "{}-{}-{}-scp_{}".format(
time.strftime("%Y%m%d-%H%M%S"),
self.protocol.getProtoTransport().transportId,
self.protocol.terminal.transport.session.id,
re.sub("[^A-Za-z0-9]", "_", name),
)
self.safeoutfile = os.path.join(self.download_path, tmp_fname)
with open(self.safeoutfile, "wb+") as f:
f.write(data)
def save_file(self, data: bytes, fname: str) -> None:
self.drop_tmp_file(data, fname)
if os.path.exists(self.safeoutfile):
with open(self.safeoutfile, "rb"):
shasum = hashlib.sha256(data).hexdigest()
hash_path = os.path.join(self.download_path_uniq, shasum)
# If we have content already, delete temp file
if not os.path.exists(hash_path):
os.rename(self.safeoutfile, hash_path)
duplicate = False
else:
os.remove(self.safeoutfile)
duplicate = True
log.msg(
format='SCP Uploaded file "%(filename)s" to %(outfile)s',
eventid="cowrie.session.file_upload",
filename=os.path.basename(fname),
duplicate=duplicate,
url=fname,
outfile=shasum,
shasum=shasum,
destfile=fname,
)
# Update the honeyfs to point to downloaded file
self.fs.update_realfile(self.fs.getfile(fname), hash_path)
self.fs.chown(fname, self.protocol.user.uid, self.protocol.user.gid)
def parse_scp_data(self, data: bytes) -> bytes:
# scp data format:
# C0XXX filesize filename\nfile_data\x00
# 0XXX - file permissions
# filesize - size of file in bytes in decimal notation
pos = data.find(b"\n")
if pos != -1:
header = data[:pos]
pos += 1
if re.match(rb"^C0[\d]{3} [\d]+ [^\s]+$", header):
r = re.search(rb"C(0[\d]{3}) ([\d]+) ([^\s]+)", header)
if r and r.group(1) and r.group(2) and r.group(3):
dend = pos + int(r.group(2))
if dend > len(data):
dend = len(data)
d = data[pos:dend]
if self.out_dir:
fname = os.path.join(self.out_dir, r.group(3).decode())
else:
fname = r.group(3).decode()
outfile = self.fs.resolve_path(fname, self.protocol.cwd)
try:
self.fs.mkfile(outfile, 0, 0, r.group(2), r.group(1))
except fs.FileNotFound:
# The outfile locates at a non-existing directory.
self.errorWrite(f"-scp: {outfile}: No such file or directory\n")
return b""
self.save_file(d, outfile)
data = data[dend + 1 :] # cut saved data + \x00
else:
data = b""
else:
data = b""
return data
def handle_CTRL_D(self) -> None:
if (
self.protocol.terminal.stdinlogOpen
and self.protocol.terminal.stdinlogFile
and os.path.exists(self.protocol.terminal.stdinlogFile)
):
with open(self.protocol.terminal.stdinlogFile, "rb") as f:
data: bytes = f.read()
header: bytes = data[: data.find(b"\n")]
if re.match(rb"C0[\d]{3} [\d]+ [^\s]+", header):
content = data[data.find(b"\n") + 1 :]
else:
content = b""
if content:
with open(self.protocol.terminal.stdinlogFile, "wb") as f:
f.write(content)
self.exit()
commands["/usr/bin/scp"] = Command_scp
commands["scp"] = Command_scp
| 7,501 | 32.641256 | 88 | py |
cowrie | cowrie-master/src/cowrie/commands/free.py | # All rights reserved.
"""
This module ...
"""
from __future__ import annotations
import getopt
from math import floor
from cowrie.shell.command import HoneyPotCommand
commands = {}
FREE_OUTPUT = """ total used free shared buff/cache available
Mem:{MemTotal:>15}{calc_total_used:>12}{MemFree:>12}{Shmem:>12}{calc_total_buffers_and_cache:>12}{MemAvailable:>12}
Swap:{SwapTotal:>14}{calc_swap_used:>12}{SwapFree:>12}
"""
class Command_free(HoneyPotCommand):
"""
free
"""
def call(self) -> None:
# Parse options or display no files
try:
opts, args = getopt.getopt(self.args, "mh")
except getopt.GetoptError:
self.do_free()
return
# Parse options
for o, _a in opts:
if o in ("-h"):
self.do_free(fmt="human")
return
elif o in ("-m"):
self.do_free(fmt="megabytes")
return
self.do_free()
def do_free(self, fmt: str = "kilobytes") -> None:
"""
print free statistics
"""
# Get real host memstats and add the calculated fields
raw_mem_stats = self.get_free_stats()
raw_mem_stats["calc_total_buffers_and_cache"] = (
raw_mem_stats["Buffers"] + raw_mem_stats["Cached"]
)
raw_mem_stats["calc_total_used"] = raw_mem_stats["MemTotal"] - (
raw_mem_stats["MemFree"] + raw_mem_stats["calc_total_buffers_and_cache"]
)
raw_mem_stats["calc_swap_used"] = (
raw_mem_stats["SwapTotal"] - raw_mem_stats["SwapFree"]
)
if fmt == "megabytes":
# Transform KB to MB
for key, value in raw_mem_stats.items():
raw_mem_stats[key] = int(value / 1000)
if fmt == "human":
magnitude = ["B", "M", "G", "T", "Z"]
human_mem_stats = {}
for key, value in raw_mem_stats.items():
current_magnitude = 0
# Keep dividing until we get a sane magnitude
while value >= 1000 and current_magnitude < len(magnitude):
value = floor(float(value / 1000))
current_magnitude += 1
# Format to string and append value with new magnitude
human_mem_stats[key] = str(f"{value:g}{magnitude[current_magnitude]}")
self.write(FREE_OUTPUT.format(**human_mem_stats))
else:
self.write(FREE_OUTPUT.format(**raw_mem_stats))
def get_free_stats(self) -> dict[str, int]:
"""
Get the free stats from /proc
"""
needed_keys = [
"Buffers",
"Cached",
"MemTotal",
"MemFree",
"SwapTotal",
"SwapFree",
"Shmem",
"MemAvailable",
]
mem_info_map: dict[str, int] = {}
with open("/proc/meminfo") as proc_file:
for line in proc_file:
tokens = line.split(":")
# Later we are going to do some math on those numbers, better not include uneeded keys for performance
if tokens[0] in needed_keys:
mem_info_map[tokens[0]] = int(tokens[1].lstrip().split(" ")[0])
# Got a map with all tokens from /proc/meminfo and sizes in KBs
return mem_info_map
commands["/usr/bin/free"] = Command_free
commands["free"] = Command_free
| 3,550 | 29.878261 | 118 | py |
cowrie | cowrie-master/src/cowrie/commands/yum.py |
from __future__ import annotations
import hashlib
import random
import re
from typing import Any, Optional
from collections.abc import Callable
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
arch = "x86_64"
commands = {}
class Command_faked_package_class_factory:
@staticmethod
def getCommand(name: str) -> Callable:
class Command_faked_installation(HoneyPotCommand):
def call(self) -> None:
self.write(f"{name}: Segmentation fault\n")
return Command_faked_installation
class Command_yum(HoneyPotCommand):
"""
yum fake
suppports only the 'install PACKAGE' command & 'moo'.
Any installed packages, places a 'Segfault' at /usr/bin/PACKAGE.'''
"""
packages: dict[str, dict[str, Any]] = {}
def start(self) -> None:
if len(self.args) == 0:
self.do_help()
elif len(self.args) > 0 and self.args[0] == "version":
self.do_version()
elif len(self.args) > 0 and self.args[0] == "install":
self.do_install()
else:
self.do_locked()
def sleep(self, time: float, time2: Optional[float] = None) -> defer.Deferred:
d: defer.Deferred = defer.Deferred()
if time2:
time = random.randint(int(time * 100), int(time2 * 100)) / 100.0
reactor.callLater(time, d.callback, None) # type: ignore[attr-defined]
return d
@inlineCallbacks
def do_version(self):
self.write(
"Loaded plugins: changelog, kernel-module, ovl, priorities, tsflags, versionlock\n"
)
randnum = random.randint(100, 900)
randnum2 = random.randint(100, 900)
randhash = hashlib.sha1(f"{randnum}".encode()).hexdigest()
randhash2 = hashlib.sha1(f"{randnum2}".encode()).hexdigest()
yield self.sleep(1, 2)
self.write(f"Installed: 7/{arch} {random.randint(500, 800)}:{randhash}\n")
self.write(f"Group-Installed: yum 13:{randhash2}\n")
self.write("version\n")
self.exit()
@inlineCallbacks
def do_help(self):
yield self.sleep(1, 2)
self.write(
"""Loaded plugins: changelog, kernel-module, ovl, priorities, tsflags, versionlock
You need to give some command
Usage: yum [options] COMMAND
List of Commands:
changelog Display changelog data, since a specified time, on a group of packages
check Check for problems in the rpmdb
check-update Check for available package updates
clean Remove cached data
deplist List a package's dependencies
distribution-synchronization Synchronize installed packages to the latest available versions
downgrade downgrade a package
erase Remove a package or packages from your system
fs Acts on the filesystem data of the host, mainly for removing docs/lanuages for minimal hosts.
fssnapshot Creates filesystem snapshots, or lists/deletes current snapshots.
groups Display, or use, the groups information
help Display a helpful usage message
history Display, or use, the transaction history
info Display details about a package or group of packages
install Install a package or packages on your system
list List a package or groups of packages
load-transaction load a saved transaction from filename
makecache Generate the metadata cache
provides Find what package provides the given value
reinstall reinstall a package
repo-pkgs Treat a repo. as a group of packages, so we can install/remove all of them
repolist Display the configured software repositories
search Search package details for the given string
shell Run an interactive yum shell
swap Simple way to swap packages, instead of using shell
update Update a package or packages on your system
update-minimal Works like upgrade, but goes to the 'newest' package match which fixes a problem that affects your system
updateinfo Acts on repository update information
upgrade Update packages taking obsoletes into account
version Display a version for the machine and/or available repos.
versionlock Control package version locks.
Options:
-h, --help show this help message and exit
-t, --tolerant be tolerant of errors
-C, --cacheonly run entirely from system cache, don't update cache
-c [config file], --config=[config file]
config file location
-R [minutes], --randomwait=[minutes]
maximum command wait time
-d [debug level], --debuglevel=[debug level]
debugging output level
--showduplicates show duplicates, in repos, in list/search commands
-e [error level], --errorlevel=[error level]
error output level
--rpmverbosity=[debug level name]
debugging output level for rpm
-q, --quiet quiet operation
-v, --verbose verbose operation
-y, --assumeyes answer yes for all questions
--assumeno answer no for all questions
--version show Yum version and exit
--installroot=[path] set install root
--enablerepo=[repo] enable one or more repositories (wildcards allowed)
--disablerepo=[repo] disable one or more repositories (wildcards allowed)
-x [package], --exclude=[package]
exclude package(s) by name or glob
--disableexcludes=[repo]
disable exclude from main, for a repo or for
everything
--disableincludes=[repo]
disable includepkgs for a repo or for everything
--obsoletes enable obsoletes processing during updates
--noplugins disable Yum plugins
--nogpgcheck disable gpg signature checking
--disableplugin=[plugin]
disable plugins by name
--enableplugin=[plugin]
enable plugins by name
--skip-broken skip packages with depsolving problems
--color=COLOR control whether color is used
--releasever=RELEASEVER
set value of $releasever in yum config and repo files
--downloadonly don't update, just download
--downloaddir=DLDIR specifies an alternate directory to store packages
--setopt=SETOPTS set arbitrary config and repo options
--bugfix Include bugfix relevant packages, in updates
--security Include security relevant packages, in updates
--advisory=ADVS, --advisories=ADVS
Include packages needed to fix the given advisory, in
updates
--bzs=BZS Include packages needed to fix the given BZ, in
updates
--cves=CVES Include packages needed to fix the given CVE, in
updates
--sec-severity=SEVS, --secseverity=SEVS
Include security relevant packages matching the
severity, in updates
--tsflags=TSFLAGS
Plugin Options:
--changelog Show changelog delta of updated packages
--samearch-priorities
Priority-exclude packages based on name + arch\n"""
)
self.exit()
@inlineCallbacks
def do_install(self, *args):
if len(self.args) <= 1:
yield self.sleep(1, 2)
self.write(
"Loaded plugins: changelog, kernel-module, ovl, priorities, tsflags, versionlock\n"
)
yield self.sleep(1, 2)
self.write("Error: Need to pass a list of pkgs to install\n")
self.write(" Mini usage:\n")
self.write("install PACKAGE...\n")
self.write("Install a package or packages on your system\n")
self.write("aliases: install-n, install-na, install-nevra\n")
self.exit()
return
for y in [re.sub("[^A-Za-z0-9]", "", x) for x in self.args[1:]]:
self.packages[y] = {
"version": "{}.{}-{}".format(
random.choice([0, 1]), random.randint(1, 40), random.randint(1, 10)
),
"size": random.randint(100, 900),
"release": f"{random.randint(1, 15)}.el7",
}
totalsize: int = sum(self.packages[x]["size"] for x in self.packages)
repository = "base"
yield self.sleep(1)
self.write(
"Loaded plugins: changelog, kernel-module, ovl, priorities, tsflags, versionlock\n"
)
yield self.sleep(2.2)
self.write(
"{} packages excluded due to repository priority protections\n".format(
random.randint(200, 300)
)
)
yield self.sleep(0.9)
self.write("Resolving Dependencies\n")
self.write("--> Running transaction check\n")
for p in self.packages:
self.write(
"---> Package {}.{} {}.{} will be installed\n".format(
p, self.packages[p]["version"], arch, self.packages[p]["release"]
)
)
self.write("--> Finished Dependency Resolution\n")
self.write("Beginning Kernel Module Plugin\n")
self.write("Finished Kernel Module Plugin\n\n")
self.write("Dependencies Resolved\n\n")
# TODO: Is this working on all screens?
self.write("{}\n".format("=" * 176))
# 195 characters
self.write(" Package\t\t\tArch\t\t\tVersion\t\t\t\tRepository\t\t\tSize\n")
self.write("{}\n".format("=" * 176))
self.write("Installing:\n")
for p in self.packages:
self.write(
" {}\t\t\t\t{}\t\t\t{}-{}\t\t\t{}\t\t\t\t{} k\n".format(
p,
arch,
self.packages[p]["version"],
self.packages[p]["release"],
repository,
self.packages[p]["size"],
)
)
self.write("\n")
self.write("Transaction Summary\n")
self.write("{}\n".format("=" * 176))
self.write(f"Install {len(self.packages)} Packages\n\n")
self.write(f"Total download size: {totalsize} k\n")
self.write(f"Installed size: {0.0032*totalsize:.1f} M\n")
self.write("Is this ok [y/d/N]: ")
# Assume 'yes'
@inlineCallbacks
def lineReceived(self, line):
log.msg("INPUT (yum):", line)
self.write("Downloading packages:\n")
yield self.sleep(0.5, 1)
self.write("Running transaction check\n")
yield self.sleep(0.5, 1)
self.write("Running transaction test\n")
self.write("Transaction test succeeded\n")
self.write("Running transaction\n")
i = 1
for p in self.packages:
self.write(
" Installing : {}-{}-{}.{} \t\t\t\t {}/{} \n".format(
p,
self.packages[p]["version"],
self.packages[p]["release"],
arch,
i,
len(self.packages),
)
)
yield self.sleep(0.5, 1)
i += 1
i = 1
for p in self.packages:
self.write(
" Verifying : {}-{}-{}.{} \t\t\t\t {}/{} \n".format(
p,
self.packages[p]["version"],
self.packages[p]["release"],
arch,
i,
len(self.packages),
)
)
yield self.sleep(0.5, 1)
i += 1
self.write("\n")
self.write("Installed:\n")
for p in self.packages:
self.write(
" {}.{} {}:{}-{} \t\t".format(
p,
arch,
random.randint(0, 2),
self.packages[p]["version"],
self.packages[p]["release"],
)
)
self.write("\n")
self.write("Complete!\n")
self.exit()
def do_locked(self) -> None:
self.errorWrite(
"Loaded plugins: changelog, kernel-module, ovl, priorities, tsflags, versionlock\n"
)
self.errorWrite("ovl: Error while doing RPMdb copy-up:\n")
self.errorWrite("[Errno 13] Permission denied: '/var/lib/rpm/.dbenv.lock' \n")
self.errorWrite("You need to be root to perform this command.\n")
self.exit()
commands["/usr/bin/yum"] = Command_yum
commands["yum"] = Command_yum
| 12,980 | 38.099398 | 120 | py |
cowrie | cowrie-master/src/cowrie/commands/curl.py |
from __future__ import annotations
import getopt
import ipaddress
import os
from typing import Optional
from twisted.internet import error
from twisted.python import compat, log
import treq
from cowrie.core.artifact import Artifact
from cowrie.core.config import CowrieConfig
from cowrie.shell.command import HoneyPotCommand
commands = {}
CURL_HELP = """Usage: curl [options...] <url>
Options: (H) means HTTP/HTTPS only, (F) means FTP only
--anyauth Pick "any" authentication method (H)
-a, --append Append to target file when uploading (F/SFTP)
--basic Use HTTP Basic Authentication (H)
--cacert FILE CA certificate to verify peer against (SSL)
--capath DIR CA directory to verify peer against (SSL)
-E, --cert CERT[:PASSWD] Client certificate file and password (SSL)
--cert-type TYPE Certificate file type (DER/PEM/ENG) (SSL)
--ciphers LIST SSL ciphers to use (SSL)
--compressed Request compressed response (using deflate or gzip)
-K, --config FILE Specify which config file to read
--connect-timeout SECONDS Maximum time allowed for connection
-C, --continue-at OFFSET Resumed transfer offset
-b, --cookie STRING/FILE String or file to read cookies from (H)
-c, --cookie-jar FILE Write cookies to this file after operation (H)
--create-dirs Create necessary local directory hierarchy
--crlf Convert LF to CRLF in upload
--crlfile FILE Get a CRL list in PEM format from the given file
-d, --data DATA HTTP POST data (H)
--data-ascii DATA HTTP POST ASCII data (H)
--data-binary DATA HTTP POST binary data (H)
--data-urlencode DATA HTTP POST data url encoded (H)
--delegation STRING GSS-API delegation permission
--digest Use HTTP Digest Authentication (H)
--disable-eprt Inhibit using EPRT or LPRT (F)
--disable-epsv Inhibit using EPSV (F)
-D, --dump-header FILE Write the headers to this file
--egd-file FILE EGD socket path for random data (SSL)
--engine ENGINGE Crypto engine (SSL). "--engine list" for list
-f, --fail Fail silently (no output at all) on HTTP errors (H)
-F, --form CONTENT Specify HTTP multipart POST data (H)
--form-string STRING Specify HTTP multipart POST data (H)
--ftp-account DATA Account data string (F)
--ftp-alternative-to-user COMMAND String to replace "USER [name]" (F)
--ftp-create-dirs Create the remote dirs if not present (F)
--ftp-method [MULTICWD/NOCWD/SINGLECWD] Control CWD usage (F)
--ftp-pasv Use PASV/EPSV instead of PORT (F)
-P, --ftp-port ADR Use PORT with given address instead of PASV (F)
--ftp-skip-pasv-ip Skip the IP address for PASV (F)
--ftp-pret Send PRET before PASV (for drftpd) (F)
--ftp-ssl-ccc Send CCC after authenticating (F)
--ftp-ssl-ccc-mode ACTIVE/PASSIVE Set CCC mode (F)
--ftp-ssl-control Require SSL/TLS for ftp login, clear for transfer (F)
-G, --get Send the -d data with a HTTP GET (H)
-g, --globoff Disable URL sequences and ranges using {} and []
-H, --header LINE Custom header to pass to server (H)
-I, --head Show document info only
-h, --help This help text
--hostpubmd5 MD5 Hex encoded MD5 string of the host public key. (SSH)
-0, --http1.0 Use HTTP 1.0 (H)
--ignore-content-length Ignore the HTTP Content-Length header
-i, --include Include protocol headers in the output (H/F)
-k, --insecure Allow connections to SSL sites without certs (H)
--interface INTERFACE Specify network interface/address to use
-4, --ipv4 Resolve name to IPv4 address
-6, --ipv6 Resolve name to IPv6 address
-j, --junk-session-cookies Ignore session cookies read from file (H)
--keepalive-time SECONDS Interval between keepalive probes
--key KEY Private key file name (SSL/SSH)
--key-type TYPE Private key file type (DER/PEM/ENG) (SSL)
--krb LEVEL Enable Kerberos with specified security level (F)
--libcurl FILE Dump libcurl equivalent code of this command line
--limit-rate RATE Limit transfer speed to this rate
-l, --list-only List only names of an FTP directory (F)
--local-port RANGE Force use of these local port numbers
-L, --location Follow redirects (H)
--location-trusted like --location and send auth to other hosts (H)
-M, --manual Display the full manual
--mail-from FROM Mail from this address
--mail-rcpt TO Mail to this receiver(s)
--mail-auth AUTH Originator address of the original email
--max-filesize BYTES Maximum file size to download (H/F)
--max-redirs NUM Maximum number of redirects allowed (H)
-m, --max-time SECONDS Maximum time allowed for the transfer
--negotiate Use HTTP Negotiate Authentication (H)
-n, --netrc Must read .netrc for user name and password
--netrc-optional Use either .netrc or URL; overrides -n
--netrc-file FILE Set up the netrc filename to use
-N, --no-buffer Disable buffering of the output stream
--no-keepalive Disable keepalive use on the connection
--no-sessionid Disable SSL session-ID reusing (SSL)
--noproxy List of hosts which do not use proxy
--ntlm Use HTTP NTLM authentication (H)
-o, --output FILE Write output to <file> instead of stdout
--pass PASS Pass phrase for the private key (SSL/SSH)
--post301 Do not switch to GET after following a 301 redirect (H)
--post302 Do not switch to GET after following a 302 redirect (H)
--post303 Do not switch to GET after following a 303 redirect (H)
-#, --progress-bar Display transfer progress as a progress bar
--proto PROTOCOLS Enable/disable specified protocols
--proto-redir PROTOCOLS Enable/disable specified protocols on redirect
-x, --proxy [PROTOCOL://]HOST[:PORT] Use proxy on given port
--proxy-anyauth Pick "any" proxy authentication method (H)
--proxy-basic Use Basic authentication on the proxy (H)
--proxy-digest Use Digest authentication on the proxy (H)
--proxy-negotiate Use Negotiate authentication on the proxy (H)
--proxy-ntlm Use NTLM authentication on the proxy (H)
-U, --proxy-user USER[:PASSWORD] Proxy user and password
--proxy1.0 HOST[:PORT] Use HTTP/1.0 proxy on given port
-p, --proxytunnel Operate through a HTTP proxy tunnel (using CONNECT)
--pubkey KEY Public key file name (SSH)
-Q, --quote CMD Send command(s) to server before transfer (F/SFTP)
--random-file FILE File for reading random data from (SSL)
-r, --range RANGE Retrieve only the bytes within a range
--raw Do HTTP "raw", without any transfer decoding (H)
-e, --referer Referer URL (H)
-J, --remote-header-name Use the header-provided filename (H)
-O, --remote-name Write output to a file named as the remote file
--remote-name-all Use the remote file name for all URLs
-R, --remote-time Set the remote file's time on the local output
-X, --request COMMAND Specify request command to use
--resolve HOST:PORT:ADDRESS Force resolve of HOST:PORT to ADDRESS
--retry NUM Retry request NUM times if transient problems occur
--retry-delay SECONDS When retrying, wait this many seconds between each
--retry-max-time SECONDS Retry only within this period
-S, --show-error Show error. With -s, make curl show errors when they occur
-s, --silent Silent mode. Don't output anything
--socks4 HOST[:PORT] SOCKS4 proxy on given host + port
--socks4a HOST[:PORT] SOCKS4a proxy on given host + port
--socks5 HOST[:PORT] SOCKS5 proxy on given host + port
--socks5-hostname HOST[:PORT] SOCKS5 proxy, pass host name to proxy
--socks5-gssapi-service NAME SOCKS5 proxy service name for gssapi
--socks5-gssapi-nec Compatibility with NEC SOCKS5 server
-Y, --speed-limit RATE Stop transfers below speed-limit for 'speed-time' secs
-y, --speed-time SECONDS Time for trig speed-limit abort. Defaults to 30
--ssl Try SSL/TLS (FTP, IMAP, POP3, SMTP)
--ssl-reqd Require SSL/TLS (FTP, IMAP, POP3, SMTP)
-2, --sslv2 Use SSLv2 (SSL)
-3, --sslv3 Use SSLv3 (SSL)
--ssl-allow-beast Allow security flaw to improve interop (SSL)
--stderr FILE Where to redirect stderr. - means stdout
--tcp-nodelay Use the TCP_NODELAY option
-t, --telnet-option OPT=VAL Set telnet option
--tftp-blksize VALUE Set TFTP BLKSIZE option (must be >512)
-z, --time-cond TIME Transfer based on a time condition
-1, --tlsv1 Use TLSv1 (SSL)
--trace FILE Write a debug trace to the given file
--trace-ascii FILE Like --trace but without the hex output
--trace-time Add time stamps to trace/verbose output
--tr-encoding Request compressed transfer encoding (H)
-T, --upload-file FILE Transfer FILE to destination
--url URL URL to work with
-B, --use-ascii Use ASCII/text transfer
-u, --user USER[:PASSWORD] Server user and password
--tlsuser USER TLS username
--tlspassword STRING TLS password
--tlsauthtype STRING TLS authentication type (default SRP)
-A, --user-agent STRING User-Agent to send to server (H)
-v, --verbose Make the operation more talkative
-V, --version Show version number and quit
-w, --write-out FORMAT What to output after completion
--xattr Store metadata in extended file attributes
-q If used as the first parameter disables .curlrc
"""
class Command_curl(HoneyPotCommand):
"""
curl command
"""
limit_size: int = CowrieConfig.getint("honeypot", "download_limit_size", fallback=0)
outfile: Optional[str] = None # outfile is the file saved inside the honeypot
artifact: Artifact # artifact is the file saved for forensics in the real file system
currentlength: int = 0 # partial size during download
totallength: int = 0 # total length
silent: bool = False
url: bytes
host: str
port: int
def start(self) -> None:
try:
optlist, args = getopt.getopt(
self.args, "sho:O", ["help", "manual", "silent"]
)
except getopt.GetoptError as err:
# TODO: should be 'unknown' instead of 'not recognized'
self.write(f"curl: {err}\n")
self.write(
"curl: try 'curl --help' or 'curl --manual' for more information\n"
)
self.exit()
return
for opt in optlist:
if opt[0] == "-h" or opt[0] == "--help":
self.write(CURL_HELP)
self.exit()
return
elif opt[0] == "-s" or opt[0] == "--silent":
self.silent = True
if len(args):
if args[0] is not None:
url = str(args[0]).strip()
else:
self.write(
"curl: try 'curl --help' or 'curl --manual' for more information\n"
)
self.exit()
return
if "://" not in url:
url = "http://" + url
urldata = compat.urllib_parse.urlparse(url)
for opt in optlist:
if opt[0] == "-o":
self.outfile = opt[1]
if opt[0] == "-O":
self.outfile = urldata.path.split("/")[-1]
if (
self.outfile is None
or not len(self.outfile.strip())
or not urldata.path.count("/")
):
self.write("curl: Remote file name has no length!\n")
self.exit()
return
if self.outfile:
self.outfile = self.fs.resolve_path(self.outfile, self.protocol.cwd)
if self.outfile:
path = os.path.dirname(self.outfile)
if not path or not self.fs.exists(path) or not self.fs.isdir(path):
self.write(
f"curl: {self.outfile}: Cannot open: No such file or directory\n"
)
self.exit()
return
self.url = url.encode("ascii")
parsed = compat.urllib_parse.urlparse(url)
if parsed.scheme:
scheme = parsed.scheme
if scheme != "http" and scheme != "https":
self.errorWrite(
f'curl: (1) Protocol "{scheme}" not supported or disabled in libcurl\n'
)
self.exit()
return
if parsed.hostname:
self.host = parsed.hostname
else:
self.errorWrite(
f'curl: (1) Protocol "{scheme}" not supported or disabled in libcurl\n'
)
self.exit()
self.port = parsed.port or (443 if scheme == "https" else 80)
# TODO: need to do full name resolution in case someon passes DNS name pointing to local address
try:
if ipaddress.ip_address(self.host).is_private:
self.errorWrite(f"curl: (6) Could not resolve host: {self.host}\n")
self.exit()
return None
except ValueError:
pass
self.artifact = Artifact("curl-download")
self.deferred = self.treqDownload(url)
if self.deferred:
self.deferred.addCallback(self.success)
self.deferred.addErrback(self.error)
def treqDownload(self, url):
"""
Download `url`
"""
headers = {"User-Agent": ["curl/7.38.0"]}
# TODO: use designated outbound interface
# out_addr = None
# if CowrieConfig.has_option("honeypot", "out_addr"):
# out_addr = (CowrieConfig.get("honeypot", "out_addr"), 0)
deferred = treq.get(url=url, allow_redirects=False, headers=headers, timeout=10)
return deferred
def handle_CTRL_C(self) -> None:
self.write("^C\n")
self.exit()
def success(self, response):
"""
successful treq get
"""
self.totallength = response.length
# TODO possible this is UNKNOWN_LENGTH
if self.limit_size > 0 and self.totallength > self.limit_size:
log.msg(
f"Not saving URL ({self.url.decode()}) (size: {self.totallength}) exceeds file size limit ({self.limit_size})"
)
self.exit()
return
if self.outfile and not self.silent:
self.write(
" % Total % Received % Xferd Average Speed Time Time Time Current\n"
)
self.write(
" Dload Upload Total Spent Left Speed\n"
)
deferred = treq.collect(response, self.collect)
deferred.addCallback(self.collectioncomplete)
return deferred
def collect(self, data: bytes) -> None:
"""
partial collect
"""
self.currentlength += len(data)
if self.limit_size > 0 and self.currentlength > self.limit_size:
log.msg(
f"Not saving URL ({self.url.decode()}) (size: {self.currentlength}) exceeds file size limit ({self.limit_size})"
)
self.exit()
return
self.artifact.write(data)
if self.outfile and not self.silent:
self.write(
"\r100 {} 100 {} 0 0 {} 0 --:--:-- --:--:-- --:--:-- {}".format(
self.currentlength, self.currentlength, 63673, 65181
)
)
if not self.outfile:
self.writeBytes(data)
def collectioncomplete(self, data: None) -> None:
"""
this gets called once collection is complete
"""
self.artifact.close()
if self.outfile and not self.silent:
self.write("\n")
# Update the honeyfs to point to artifact file if output is to file
if self.outfile:
self.fs.mkfile(self.outfile, 0, 0, self.currentlength, 33188)
self.fs.chown(self.outfile, self.protocol.user.uid, self.protocol.user.gid)
self.fs.update_realfile(
self.fs.getfile(self.outfile), self.artifact.shasumFilename
)
self.protocol.logDispatch(
eventid="cowrie.session.file_download",
format="Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s",
url=self.url.decode(),
outfile=self.artifact.shasumFilename,
shasum=self.artifact.shasum,
)
log.msg(
eventid="cowrie.session.file_download",
format="Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s",
url=self.url.decode(),
outfile=self.artifact.shasumFilename,
shasum=self.artifact.shasum,
)
self.exit()
def error(self, response):
"""
handle any exceptions
"""
self.protocol.logDispatch(
eventid="cowrie.session.file_download.failed",
format="Attempt to download file(s) from URL (%(url)s) failed",
url=self.url.decode(),
)
log.msg(
eventid="cowrie.session.file_download.failed",
format="Attempt to download file(s) from URL (%(url)s) failed",
url=self.url.decode(),
)
if response.check(error.DNSLookupError) is not None:
self.write(f"curl: (6) Could not resolve host: {self.host}\n")
self.exit()
return
elif response.check(error.ConnectingCancelledError) is not None:
self.write(
f"curl: (7) Failed to connect to {self.host} port {self.port}: Operation timed out\n"
)
self.exit()
return
elif response.check(error.ConnectionRefusedError) is not None:
self.write(
f"curl: (7) Failed to connect to {self.host} port {self.port}: Connection refused\n"
)
self.exit()
return
# possible errors:
# defer.CancelledError,
# error.ConnectingCancelledError,
log.msg(response.printTraceback())
if hasattr(response, "getErrorMessage"): # Exceptions
errormsg = response.getErrorMessage()
log.msg(errormsg)
self.write("\n")
self.exit()
commands["/usr/bin/curl"] = Command_curl
commands["curl"] = Command_curl
| 18,683 | 41.367347 | 128 | py |
cowrie | cowrie-master/src/cowrie/commands/iptables.py |
from __future__ import annotations
import optparse
from typing import Any, Optional
from cowrie.shell.command import HoneyPotCommand
commands = {}
class OptionParsingError(RuntimeError):
def __init__(self, msg: str) -> None:
self.msg = msg
class OptionParsingExit(Exception):
def __init__(self, status: int, msg: Optional[str]) -> None:
self.msg = msg
self.status = status
class ModifiedOptionParser(optparse.OptionParser):
def error(self, msg: str) -> None:
raise OptionParsingError(msg)
def exit(self, status: int = 0, msg: Optional[str] = None) -> None:
raise OptionParsingExit(status, msg)
class Command_iptables(HoneyPotCommand):
# Do not resolve args
resolve_args = False
# iptables app name
APP_NAME = "iptables"
# iptables app version, used in help messages etc.
APP_VERSION = "v1.4.14"
# Default iptable table
DEFAULT_TABLE = "filter"
table: str = DEFAULT_TABLE
tables: dict[str, dict[str, list[Any]]]
current_table: dict[str, list[Any]]
def user_is_root(self) -> bool:
out: bool = self.protocol.user.username == "root"
return out
def start(self) -> None:
"""
Emulate iptables commands, including permission checking.
Verified examples:
* iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
* iptables -A INPUT -i eth0 -p tcp -s "127.0.0.1" -j DROP
Others:
* iptables
* iptables [[-t | --table] <name>] [-h | --help]
* iptables [[-t | --table] <name>] [-v | --version]
* iptables [[-t | --table] <name>] [-F | --flush] <chain>
* iptables [[-t | --table] <name>] [-L | --list] <chain>
* iptables [[-t | --table] <name>] [-S | --list-rules] <chain>
* iptables --this-is-invalid
"""
# In case of no arguments
if len(self.args) == 0:
self.no_command()
return
# Utils
def optional_arg(arg_default):
def func(option, opt_str, value, parser):
if parser.rargs and not parser.rargs[0].startswith("-"):
val = parser.rargs[0]
parser.rargs.pop(0)
else:
val = arg_default
setattr(parser.values, option.dest, val)
return func
# Initialize options
parser = ModifiedOptionParser(add_help_option=False)
parser.add_option("-h", "--help", dest="help", action="store_true")
parser.add_option("-V", "--version", dest="version", action="store_true")
parser.add_option("-v", "--verbose", dest="verbose", action="store_true")
parser.add_option("-x", "--exact", dest="exact", action="store_true")
parser.add_option("--line-numbers", dest="line_numbers", action="store_true")
parser.add_option("-n", "--numeric", dest="numeric", action="store_true")
parser.add_option("--modprobe", dest="modprobe", action="store")
parser.add_option(
"-t",
"--table",
dest="table",
action="store",
default=Command_iptables.DEFAULT_TABLE,
)
parser.add_option(
"-F",
"--flush",
dest="flush",
action="callback",
callback=optional_arg(True),
)
parser.add_option(
"-Z", "--zero", dest="zero", action="callback", callback=optional_arg(True)
)
parser.add_option(
"-S",
"--list-rules",
dest="list_rules",
action="callback",
callback=optional_arg(True),
)
parser.add_option(
"-L", "--list", dest="list", action="callback", callback=optional_arg(True)
)
parser.add_option("-A", "--append", dest="append", action="store")
parser.add_option("-D", "--delete", dest="delete", action="store")
parser.add_option("-I", "--insert", dest="insert", action="store")
parser.add_option("-R", "--replace", dest="replace", action="store")
parser.add_option("-N", "--new-chain", dest="new_chain", action="store")
parser.add_option("-X", "--delete-chain", dest="delete_chain", action="store")
parser.add_option("-P", "--policy", dest="policy", action="store")
parser.add_option("-E", "--rename-chain", dest="rename_chain", action="store")
parser.add_option("-p", "--protocol", dest="protocol", action="store")
parser.add_option("-s", "--source", dest="source", action="store")
parser.add_option("-d", "--destination", dest="destination", action="store")
parser.add_option("-j", "--jump", dest="jump", action="store")
parser.add_option("-g", "--goto", dest="goto", action="store")
parser.add_option("-i", "--in-interface", dest="in_interface", action="store")
parser.add_option("-o", "--out-interface", dest="out_interface", action="store")
parser.add_option("-f", "--fragment", dest="fragment", action="store_true")
parser.add_option("-c", "--set-counters", dest="set_counters", action="store")
parser.add_option("-m", "--match", dest="match", action="store")
parser.add_option(
"--sport", "--source-ports", dest="source_ports", action="store"
)
parser.add_option(
"--dport", "--destination-ports", dest="dest_ports", action="store"
)
parser.add_option("--ports", dest="ports", action="store")
parser.add_option("--state", dest="state", action="store")
# Parse options or display no files
try:
(opts, args) = parser.parse_args(list(self.args))
except OptionParsingError:
self.bad_argument(self.args[0])
return
except OptionParsingExit as e:
self.unknown_option(e)
return
# Initialize table
if not self.setup_table(opts.table):
return
# Parse options
if opts.help:
self.show_help()
return
elif opts.version:
self.show_version()
return
elif opts.flush:
self.flush("" if opts.flush else opts.flush)
return
elif opts.list:
self.list("" if opts.list else opts.list)
return
elif opts.list_rules:
self.list_rules("" if opts.list_rules else opts.list_rules)
return
# Done
self.exit()
def setup_table(self, table: str) -> bool:
"""
Called during startup to make sure the current environment has some
fake rules in memory.
"""
# Create fresh tables on start
if not hasattr(self.protocol.user.server, "iptables"):
self.protocol.user.server.iptables = {
"raw": {"PREROUTING": [], "OUTPUT": []},
"filter": {
"INPUT": [
(
"ACCEPT",
"tcp",
"--",
"anywhere",
"anywhere",
"tcp",
"dpt:ssh",
),
("DROP", "all", "--", "anywhere", "anywhere", "", ""),
],
"FORWARD": [],
"OUTPUT": [],
},
"mangle": {
"PREROUTING": [],
"INPUT": [],
"FORWARD": [],
"OUTPUT": [],
"POSTROUTING": [],
},
"nat": {"PREROUTING": [], "OUTPUT": []},
}
# Get the tables
self.tables: dict[
str, dict[str, list[Any]]
] = self.protocol.user.server.iptables
# Verify selected table
if not self.is_valid_table(table):
return False
# Set table
self.current_table = self.tables[table]
# Done
return True
def is_valid_table(self, table: str) -> bool:
if self.user_is_root():
# Verify table existence
if table not in self.tables.keys():
self.write(
"""{}: can\'t initialize iptables table \'{}\': Table does not exist (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.\n""".format(
Command_iptables.APP_NAME, table
)
)
self.exit()
else:
return True
else:
self.no_permission()
# Failed
return False
def is_valid_chain(self, chain: str) -> bool:
# Verify chain existence. Requires valid table first
if chain not in list(self.current_table.keys()):
self.write(
"%s: No chain/target/match by that name.\n" % Command_iptables.APP_NAME
)
self.exit()
return False
# Exists
return True
def show_version(self) -> None:
"""
Show version and exit
"""
self.write(f"{Command_iptables.APP_NAME} {Command_iptables.APP_VERSION}\n")
self.exit()
def show_help(self) -> None:
"""
Show help and exit
"""
self.write(
"""{} {}'
Usage: iptables -[AD] chain rule-specification [options]
iptables -I chain [rulenum] rule-specification [options]
iptables -R chain rulenum rule-specification [options]
iptables -D chain rulenum [options]
iptables -[LS] [chain [rulenum]] [options]
iptables -[FZ] [chain] [options]
iptables -[NX] chain
iptables -E old-chain-name new-chain-name
iptables -P chain target [options]
iptables -h (print this help information)
Commands:
Either long or short options are allowed.
--append -A chain Append to chain
--delete -D chain Delete matching rule from chain
--delete -D chain rulenum
Delete rule rulenum (1 = first) from chain
--insert -I chain [rulenum]
Insert in chain as rulenum (default 1=first)
--replace -R chain rulenum
Replace rule rulenum (1 = first) in chain
--list -L [chain [rulenum]]
List the rules in a chain or all chains
--list-rules -S [chain [rulenum]]
Print the rules in a chain or all chains
--flush -F [chain] Delete all rules in chain or all chains
--zero -Z [chain [rulenum]]
Zero counters in chain or all chains
--new -N chain Create a new user-defined chain
--delete-chain
-X [chain] Delete a user-defined chain
--policy -P chain target
Change policy on chain to target
--rename-chain
-E old-chain new-chain
Change chain name, (moving any references)
Options:
[!] --proto -p proto protocol: by number or name, eg. \'tcp\'
[!] --source -s address[/mask][...]
source specification
[!] --destination -d address[/mask][...]
destination specification
[!] --in-interface -i input name[+]
network interface name ([+] for wildcard)
--jump -j target
target for rule (may load target extension)
--goto -g chain
jump to chain with no return
--match -m match
extended match (may load extension)
--numeric -n numeric output of addresses and ports
[!] --out-interface -o output name[+]
network interface name ([+] for wildcard)
--table -t table table to manipulate (default: \'filter\')
--verbose -v verbose mode
--line-numbers print line numbers when listing
--exact -x expand numbers (display exact values)
[!] --fragment -f match second or further fragments only
--modprobe=<command> try to insert modules using this command
--set-counters PKTS BYTES set the counter during insert/append
[!] --version -V print package version.\n""".format(
Command_iptables.APP_NAME, Command_iptables.APP_VERSION
)
)
self.exit()
def list_rules(self, chain: str) -> None:
"""
List current rules as commands
"""
if self.user_is_root():
if len(chain) > 0:
# Check chain
if not self.is_valid_chain(chain):
return
chains = [chain]
else:
chains = list(self.current_table.keys())
# Output buffer
output = []
for chain in chains:
output.append("-P %s ACCEPT" % chain)
# Done
self.write("{}\n".format("\n".join(output)))
self.exit()
else:
self.no_permission()
def list(self, chain: str) -> None:
"""
List current rules
"""
if self.user_is_root():
if len(chain) > 0:
# Check chain
if not self.is_valid_chain(chain):
return
chains = [chain]
else:
chains = list(self.current_table.keys())
# Output buffer
output = []
for chain in chains:
# Chain table header
chain_output = [
"Chain %s (policy ACCEPT)" % chain,
"target prot opt source destination",
]
# Format the rules
for rule in self.current_table[chain]:
chain_output.append(
"%-10s %-4s %-3s %-20s %-20s %s %s" % rule,
)
# Create one string
output.append("\n".join(chain_output))
# Done
self.write("{}\n".format("\n\n".join(output)))
self.exit()
else:
self.no_permission()
def flush(self, chain: str) -> None:
"""
Mark rules as flushed
"""
if self.user_is_root():
if len(chain) > 0:
# Check chain
if not self.is_valid_chain(chain):
return
chains = [chain]
else:
chains = list(self.current_table.keys())
# Flush
for chain in chains:
self.current_table[chain] = []
self.exit()
else:
self.no_permission()
def no_permission(self) -> None:
self.write(
f"{Command_iptables.APP_NAME} {Command_iptables.APP_VERSION}: "
+ "can't initialize iptables table 'filter': "
+ "Permission denied (you must be root)\n"
+ "Perhaps iptables or your kernel needs to be upgraded.\n"
)
self.exit()
def no_command(self) -> None:
"""
Print no command message and exit
"""
self.write(
"{} {}: no command specified'\nTry `iptables -h' or 'iptables --help' for more information.\n".format(
Command_iptables.APP_NAME, Command_iptables.APP_VERSION
)
)
self.exit()
def unknown_option(self, option: OptionParsingExit) -> None:
"""
Print unknown option message and exit
"""
self.write(
"{} {}: unknown option '{}''\nTry `iptables -h' or 'iptables --help' for more information.\n".format(
Command_iptables.APP_NAME, Command_iptables.APP_VERSION, option
)
)
self.exit()
def bad_argument(self, argument: str) -> None:
"""
Print bad argument and exit
"""
self.write(
"Bad argument '{}'\nTry `iptables -h' or 'iptables --help' for more information.\n".format(
argument
)
)
self.exit()
commands["/sbin/iptables"] = Command_iptables
commands["iptables"] = Command_iptables
| 16,309 | 32.150407 | 114 | py |
cowrie | cowrie-master/src/cowrie/commands/ftpget.py |
from __future__ import annotations
import ftplib
import getopt
import os
import socket
from typing import Optional, Union
from twisted.python import log
from cowrie.core.artifact import Artifact
from cowrie.core.config import CowrieConfig
from cowrie.shell.command import HoneyPotCommand
commands = {}
class FTP(ftplib.FTP):
def __init__(self, *args, **kwargs):
self.source_address = kwargs.pop("source_address", None)
ftplib.FTP.__init__(self, *args, **kwargs)
def connect(
self,
host: str = "",
port: int = 0,
timeout: float = -999.0,
source_address: Optional[tuple[str, int]] = None,
) -> str:
if host != "":
self.host = host
if port > 0:
self.port = port
if timeout != -999.0:
self.timeout: int = int(timeout)
if source_address is not None:
self.source_address = source_address
self.sock = socket.create_connection(
(self.host, self.port), self.timeout, self.source_address
)
self.af = self.sock.family
self.file = self.sock.makefile(mode="r")
self.welcome = self.getresp()
return self.welcome
def ntransfercmd(
self, cmd: str, rest: Union[int, str, None] = None
) -> tuple[socket.socket, int]:
size = 0
if self.passiveserver:
host, port = self.makepasv()
conn = socket.create_connection(
(host, port), self.timeout, self.source_address
)
try:
if rest is not None:
self.sendcmd(f"REST {rest}")
resp = self.sendcmd(cmd)
if resp[0] == "2":
resp = self.getresp()
if resp[0] != "1":
raise ftplib.error_reply(resp)
except Exception:
conn.close()
raise
else:
sock = self.makeport()
try:
if rest is not None:
self.sendcmd(f"REST {rest}")
resp = self.sendcmd(cmd)
if resp[0] == "2":
resp = self.getresp()
if resp[0] != "1":
raise ftplib.error_reply(resp)
conn, sockaddr = sock.accept()
if self.timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: # type: ignore
conn.settimeout(self.timeout)
finally:
sock.close()
if resp[:3] == "150":
sz = ftplib.parse150(resp)
if sz:
size = sz
return conn, size
class Command_ftpget(HoneyPotCommand):
"""
ftpget command
"""
download_path = CowrieConfig.get("honeypot", "download_path")
verbose: bool
host: str
port: int
username: str
password: str
remote_path: str
remote_dir: str
remote_file: str
artifactFile: Artifact
def help(self) -> None:
self.write(
"""BusyBox v1.20.2 (2016-06-22 15:12:53 EDT) multi-call binary.
Usage: ftpget [OPTIONS] HOST [LOCAL_FILE] REMOTE_FILE
Download a file via FTP
-c Continue previous transfer
-v Verbose
-u USER Username
-p PASS Password
-P NUM Port\n\n"""
)
def start(self) -> None:
try:
optlist, args = getopt.getopt(self.args, "cvu:p:P:")
except getopt.GetoptError:
self.help()
self.exit()
return
if len(args) < 2:
self.help()
self.exit()
return
self.verbose = False
self.username = ""
self.password = ""
self.port = 21
self.host = ""
self.local_file = ""
self.remote_path = ""
for opt in optlist:
if opt[0] == "-v":
self.verbose = True
elif opt[0] == "-u":
self.username = opt[1]
elif opt[0] == "-p":
self.password = opt[1]
elif opt[0] == "-P":
try:
self.port = int(opt[1])
except ValueError:
pass
if len(args) == 2:
self.host, self.remote_path = args
elif len(args) >= 3:
self.host, self.local_file, self.remote_path = args[:3]
self.remote_dir = os.path.dirname(self.remote_path)
self.remote_file = os.path.basename(self.remote_path)
if not self.local_file:
self.local_file = self.remote_file
fakeoutfile = self.fs.resolve_path(self.local_file, self.protocol.cwd)
path = os.path.dirname(fakeoutfile)
if not path or not self.fs.exists(path) or not self.fs.isdir(path):
self.write(
"ftpget: can't open '{}': No such file or directory".format(
self.local_file
)
)
self.exit()
return
self.url_log = "ftp://"
if self.username:
self.url_log = f"{self.url_log}{self.username}"
if self.password:
self.url_log = f"{self.url_log}:{self.password}"
self.url_log = f"{self.url_log}@"
self.url_log = f"{self.url_log}{self.host}"
if self.port != 21:
self.url_log = f"{self.url_log}:{self.port}"
self.url_log = f"{self.url_log}/{self.remote_path}"
self.artifactFile = Artifact(self.local_file)
result = self.ftp_download()
self.artifactFile.close()
if not result:
# log to cowrie.log
log.msg(
format="Attempt to download file(s) from URL (%(url)s) failed",
url=self.url_log,
)
self.protocol.logDispatch(
eventid="cowrie.session.file_download.failed",
format="Attempt to download file(s) from URL (%(url)s) failed",
url=self.url_log,
)
self.exit()
return
# log to cowrie.log
log.msg(
format="Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s",
url=self.url_log,
outfile=self.artifactFile.shasumFilename,
shasum=self.artifactFile.shasum,
)
self.protocol.logDispatch(
eventid="cowrie.session.file_download",
format="Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s",
url=self.url_log,
outfile=self.artifactFile.shasumFilename,
shasum=self.artifactFile.shasum,
destfile=self.local_file,
)
# Update the honeyfs to point to downloaded file
self.fs.mkfile(
fakeoutfile, 0, 0, os.path.getsize(self.artifactFile.shasumFilename), 33188
)
self.fs.update_realfile(
self.fs.getfile(fakeoutfile), self.artifactFile.shasumFilename
)
self.fs.chown(fakeoutfile, self.protocol.user.uid, self.protocol.user.gid)
self.exit()
def ftp_download(self) -> bool:
out_addr = ("", 0)
if CowrieConfig.has_option("honeypot", "out_addr"):
out_addr = (CowrieConfig.get("honeypot", "out_addr"), 0)
ftp = FTP(source_address=out_addr)
# connect
if self.verbose:
self.write(
f"Connecting to {self.host}\n"
) # TODO: add its IP address after the host
try:
ftp.connect(host=self.host, port=self.port, timeout=30)
except Exception as e:
log.msg(
"FTP connect failed: host={}, port={}, err={}".format(
self.host, self.port, str(e)
)
)
self.write("ftpget: can't connect to remote host: Connection refused\n")
return False
# login
if self.verbose:
self.write("ftpget: cmd (null) (null)\n")
if self.username:
self.write(f"ftpget: cmd USER {self.username}\n")
else:
self.write("ftpget: cmd USER anonymous\n")
if self.password:
self.write(f"ftpget: cmd PASS {self.password}\n")
else:
self.write("ftpget: cmd PASS busybox@\n")
try:
ftp.login(user=self.username, passwd=self.password)
except Exception as e:
log.msg(
"FTP login failed: user={}, passwd={}, err={}".format(
self.username, self.password, str(e)
)
)
self.write(f"ftpget: unexpected server response to USER: {e!s}\n")
try:
ftp.quit()
except socket.timeout:
pass
return False
# download
if self.verbose:
self.write("ftpget: cmd TYPE I (null)\n")
self.write("ftpget: cmd PASV (null)\n")
self.write(f"ftpget: cmd SIZE {self.remote_path}\n")
self.write(f"ftpget: cmd RETR {self.remote_path}\n")
try:
ftp.cwd(self.remote_dir)
ftp.retrbinary(f"RETR {self.remote_file}", self.artifactFile.write)
except Exception as e:
log.msg(f"FTP retrieval failed: {e!s}")
self.write(f"ftpget: unexpected server response to USER: {e!s}\n")
try:
ftp.quit()
except socket.timeout:
pass
return False
# quit
if self.verbose:
self.write("ftpget: cmd (null) (null)\n")
self.write("ftpget: cmd QUIT (null)\n")
try:
ftp.quit()
except socket.timeout:
pass
return True
commands["/usr/bin/ftpget"] = Command_ftpget
commands["ftpget"] = Command_ftpget
| 9,880 | 29.781931 | 87 | py |
cowrie | cowrie-master/src/cowrie/commands/perl.py | # All rights reserved.
"""
This module contains the perl command
"""
from __future__ import annotations
import getopt
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_perl(HoneyPotCommand):
def version(self) -> None:
output = (
"",
"This is perl 5, version 14, subversion 2 (v5.14.2) built for x86_64-linux-thread-multi",
"",
"Copyright 1987-2014, Larry Wall",
"",
"Perl may be copied only under the terms of either the Artistic License or the",
"GNU General Public License, which may be found in the Perl 5 source kit.",
"",
"Complete documentation for Perl, including FAQ lists, should be found on",
'this system using "man perl" or "perldoc perl". If you have access to the',
"Internet, point your browser at http://www.perl.org/, the Perl Home Page.",
"",
)
for line in output:
self.write(line + "\n")
def help(self) -> None:
output = (
"",
"Usage: perl [switches] [--] [programfile] [arguments]",
" -0[octal] specify record separator (\\0, if no argument)",
" -a autosplit mode with -n or -p (splits $_ into @F)",
" -C[number/list] enables the listed Unicode features",
" -c check syntax only (runs BEGIN and CHECK blocks)",
" -d[:debugger] run program under debugger",
" -D[number/list] set debugging flags (argument is a bit mask or alphabets)",
" -e program one line of program (several -e's allowed, omit programfile)",
" -E program like -e, but enables all optional features",
" -f don't do $sitelib/sitecustomize.pl at startup",
" -F/pattern/ split() pattern for -a switch (//'s are optional)",
" -i[extension] edit <> files in place (makes backup if extension supplied)",
" -Idirectory specify @INC/#include directory (several -I's allowed)",
" -l[octal] enable line ending processing, specifies line terminator",
' -[mM][-]module execute "use/no module..." before executing program',
' -n assume "while (<>) { ... }" loop around program',
" -p assume loop like -n but print line also, like sed",
" -s enable rudimentary parsing for switches after programfile",
" -S look for programfile using PATH environment variable",
" -t enable tainting warnings",
" -T enable tainting checks",
" -u dump core after parsing program",
" -U allow unsafe operations",
" -v print version, subversion (includes VERY IMPORTANT perl info)",
" -V[:variable] print configuration summary (or a single Config.pm variable)",
" -w enable many useful warnings (RECOMMENDED)",
" -W enable all warnings",
" -x[directory] strip off text before #!perl line and perhaps cd to directory",
" -X disable all warnings",
"",
)
for line in output:
self.write(line + "\n")
def start(self) -> None:
try:
opts, args = getopt.gnu_getopt(
self.args, "acfhnpsStTuUvwWXC:D:e:E:F:i:I:l:m:M:V:X:"
)
except getopt.GetoptError as err:
self.write(
"Unrecognized switch: -" + err.opt + " (-h will show valid options).\n"
)
self.exit()
# Parse options
for o, _a in opts:
if o in ("-v"):
self.version()
self.exit()
return
elif o in ("-h"):
self.help()
self.exit()
return
for value in args:
sourcefile = self.fs.resolve_path(value, self.protocol.cwd)
if self.fs.exists(sourcefile):
self.exit()
else:
self.write(
'Can\'t open perl script "{}": No such file or directory\n'.format(
value
)
)
self.exit()
if not len(self.args):
pass
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.command.input",
realm="perl",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
def handle_CTRL_D(self) -> None:
self.exit()
commands["/usr/bin/perl"] = Command_perl
commands["perl"] = Command_perl
| 5,032 | 38.629921 | 101 | py |
cowrie | cowrie-master/src/cowrie/commands/fs.py |
"""
Filesystem related commands
"""
from __future__ import annotations
import copy
import getopt
import os.path
import re
from collections.abc import Callable
from twisted.python import log
from cowrie.shell import fs
from cowrie.shell.command import HoneyPotCommand
commands: dict[str, Callable] = {}
class Command_grep(HoneyPotCommand):
"""
grep command
"""
def grep_get_contents(self, filename: str, match: str) -> None:
try:
contents = self.fs.file_contents(filename)
self.grep_application(contents, match)
except Exception:
self.errorWrite(f"grep: {filename}: No such file or directory\n")
def grep_application(self, contents: bytes, match: str) -> None:
bmatch = os.path.basename(match).replace('"', "").encode("utf8")
matches = re.compile(bmatch)
contentsplit = contents.split(b"\n")
for line in contentsplit:
if matches.search(line):
self.writeBytes(line + b"\n")
def help(self) -> None:
self.writeBytes(
b"usage: grep [-abcDEFGHhIiJLlmnOoPqRSsUVvwxZ] [-A num] [-B num] [-C[num]]\n"
)
self.writeBytes(
b"\t[-e pattern] [-f file] [--binary-files=value] [--color=when]\n"
)
self.writeBytes(
b"\t[--context[=num]] [--directories=action] [--label] [--line-buffered]\n"
)
self.writeBytes(b"\t[--null] [pattern] [file ...]\n")
def start(self) -> None:
if not self.args:
self.help()
self.exit()
return
self.n = 10
if self.args[0] == ">":
pass
else:
try:
optlist, args = getopt.getopt(
self.args, "abcDEFGHhIiJLlmnOoPqRSsUVvwxZA:B:C:e:f:"
)
except getopt.GetoptError as err:
self.errorWrite(f"grep: invalid option -- {err.opt}\n")
self.help()
self.exit()
return
for opt, _arg in optlist:
if opt == "-h":
self.help()
if not self.input_data:
files = self.check_arguments("grep", args[1:])
for pname in files:
self.grep_get_contents(pname, args[0])
else:
self.grep_application(self.input_data, args[0])
self.exit()
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.command.input",
realm="grep",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
def handle_CTRL_D(self) -> None:
self.exit()
commands["/bin/grep"] = Command_grep
commands["grep"] = Command_grep
commands["/bin/egrep"] = Command_grep
commands["/bin/fgrep"] = Command_grep
class Command_tail(HoneyPotCommand):
"""
tail command
"""
n: int = 10
def tail_get_contents(self, filename: str) -> None:
try:
contents = self.fs.file_contents(filename)
self.tail_application(contents)
except Exception:
self.errorWrite(
f"tail: cannot open `{filename}' for reading: No such file or directory\n"
)
def tail_application(self, contents: bytes) -> None:
contentsplit = contents.split(b"\n")
lines = int(len(contentsplit))
if lines < self.n:
self.n = lines - 1
i = 0
for j in range((lines - self.n - 1), lines):
self.writeBytes(contentsplit[j])
if i < self.n:
self.write("\n")
i += 1
def start(self) -> None:
if not self.args or self.args[0] == ">":
return
else:
try:
optlist, args = getopt.getopt(self.args, "n:")
except getopt.GetoptError as err:
self.errorWrite(f"tail: invalid option -- '{err.opt}'\n")
self.exit()
return
for opt in optlist:
if opt[0] == "-n":
if not opt[1].isdigit():
self.errorWrite(f"tail: illegal offset -- {opt[1]}\n")
else:
self.n = int(opt[1])
if not self.input_data:
files = self.check_arguments("tail", args)
for pname in files:
self.tail_get_contents(pname)
else:
self.tail_application(self.input_data)
self.exit()
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.command.input",
realm="tail",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
def handle_CTRL_D(self) -> None:
self.exit()
commands["/bin/tail"] = Command_tail
commands["/usr/bin/tail"] = Command_tail
commands["tail"] = Command_tail
class Command_head(HoneyPotCommand):
"""
head command
"""
n: int = 10
def head_application(self, contents: bytes) -> None:
i = 0
contentsplit = contents.split(b"\n")
for line in contentsplit:
if i < self.n:
self.writeBytes(line + b"\n")
i += 1
def head_get_file_contents(self, filename: str) -> None:
try:
contents = self.fs.file_contents(filename)
self.head_application(contents)
except Exception:
self.errorWrite(
f"head: cannot open `{filename}' for reading: No such file or directory\n"
)
def start(self) -> None:
self.n = 10
if not self.args or self.args[0] == ">":
return
else:
try:
optlist, args = getopt.getopt(self.args, "n:")
except getopt.GetoptError as err:
self.errorWrite(f"head: invalid option -- '{err.opt}'\n")
self.exit()
return
for opt in optlist:
if opt[0] == "-n":
if not opt[1].isdigit():
self.errorWrite(f"head: illegal offset -- {opt[1]}\n")
else:
self.n = int(opt[1])
if not self.input_data:
files = self.check_arguments("head", args)
for pname in files:
self.head_get_file_contents(pname)
else:
self.head_application(self.input_data)
self.exit()
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.command.input",
realm="head",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
def handle_CTRL_D(self) -> None:
self.exit()
commands["/bin/head"] = Command_head
commands["/usr/bin/head"] = Command_head
commands["head"] = Command_head
class Command_cd(HoneyPotCommand):
"""
cd command
"""
def call(self) -> None:
if not self.args or self.args[0] == "~":
pname = self.protocol.user.avatar.home
else:
pname = self.args[0]
try:
newpath = self.fs.resolve_path(pname, self.protocol.cwd)
inode = self.fs.getfile(newpath)
except Exception:
pass
if pname == "-":
self.errorWrite("bash: cd: OLDPWD not set\n")
return
if inode is None or inode is False:
self.errorWrite(f"bash: cd: {pname}: No such file or directory\n")
return
if inode[fs.A_TYPE] != fs.T_DIR:
self.errorWrite(f"bash: cd: {pname}: Not a directory\n")
return
self.protocol.cwd = newpath
commands["cd"] = Command_cd
class Command_rm(HoneyPotCommand):
"""
rm command
"""
def help(self) -> None:
self.write(
"""Usage: rm [OPTION]... [FILE]...
Remove (unlink) the FILE(s).
-f, --force ignore nonexistent files and arguments, never prompt
-i prompt before every removal
-I prompt once before removing more than three files, or
when removing recursively; less intrusive than -i,
while still giving protection against most mistakes
--interactive[=WHEN] prompt according to WHEN: never, once (-I), or
always (-i); without WHEN, prompt always
--one-file-system when removing a hierarchy recursively, skip any
directory that is on a file system different from
that of the corresponding command line argument
--no-preserve-root do not treat '/' specially
--preserve-root do not remove '/' (default)
-r, -R, --recursive remove directories and their contents recursively
-d, --dir remove empty directories
-v, --verbose explain what is being done
--help display this help and exit
--version output version information and exit
By default, rm does not remove directories. Use the --recursive (-r or -R)
option to remove each listed directory, too, along with all of its contents.
To remove a file whose name starts with a '-', for example '-foo',
use one of these commands:
rm -- -foo
rm ./-foo
Note that if you use rm to remove a file, it might be possible to recover
some of its contents, given sufficient expertise and/or time. For greater
assurance that the contents are truly unrecoverable, consider using shred.
GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
Full documentation at: <http://www.gnu.org/software/coreutils/rm>
or available locally via: info '(coreutils) rm invocation'\n"""
)
def paramError(self) -> None:
self.errorWrite("Try 'rm --help' for more information\n")
def call(self) -> None:
recursive = False
force = False
verbose = False
if not self.args:
self.errorWrite("rm: missing operand\n")
self.paramError()
return
try:
optlist, args = getopt.gnu_getopt(
self.args, "rTfvh", ["help", "recursive", "force", "verbose"]
)
except getopt.GetoptError as err:
self.errorWrite(f"rm: invalid option -- '{err.opt}'\n")
self.paramError()
self.exit()
return
for o, _a in optlist:
if o in ("--recursive", "-r", "-R"):
recursive = True
elif o in ("--force", "-f"):
force = True
elif o in ("--verbose", "-v"):
verbose = True
elif o in ("--help", "-h"):
self.help()
return
for f in args:
pname = self.fs.resolve_path(f, self.protocol.cwd)
try:
# verify path to file exists
dir = self.fs.get_path("/".join(pname.split("/")[:-1]))
# verify that the file itself exists
self.fs.get_path(pname)
except (IndexError, fs.FileNotFound):
if not force:
self.errorWrite(
f"rm: cannot remove `{f}': No such file or directory\n"
)
continue
basename = pname.split("/")[-1]
for i in dir[:]:
if i[fs.A_NAME] == basename:
if i[fs.A_TYPE] == fs.T_DIR and not recursive:
self.errorWrite(
"rm: cannot remove `{}': Is a directory\n".format(
i[fs.A_NAME]
)
)
else:
dir.remove(i)
if verbose:
if i[fs.A_TYPE] == fs.T_DIR:
self.write(f"removed directory '{i[fs.A_NAME]}'\n")
else:
self.write(f"removed '{i[fs.A_NAME]}'\n")
commands["/bin/rm"] = Command_rm
commands["rm"] = Command_rm
class Command_cp(HoneyPotCommand):
"""
cp command
"""
def call(self) -> None:
if not len(self.args):
self.errorWrite("cp: missing file operand\n")
self.errorWrite("Try `cp --help' for more information.\n")
return
try:
optlist, args = getopt.gnu_getopt(self.args, "-abdfiHlLPpRrsStTuvx")
except getopt.GetoptError:
self.errorWrite("Unrecognized option\n")
return
recursive = False
for opt in optlist:
if opt[0] in ("-r", "-a", "-R"):
recursive = True
def resolv(pname: str) -> str:
rsv: str = self.fs.resolve_path(pname, self.protocol.cwd)
return rsv
if len(args) < 2:
self.errorWrite(
f"cp: missing destination file operand after `{self.args[0]}'\n"
)
self.errorWrite("Try `cp --help' for more information.\n")
return
sources, dest = args[:-1], args[-1]
if len(sources) > 1 and not self.fs.isdir(resolv(dest)):
self.errorWrite(f"cp: target `{dest}' is not a directory\n")
return
if dest[-1] == "/" and not self.fs.exists(resolv(dest)) and not recursive:
self.errorWrite(
f"cp: cannot create regular file `{dest}': Is a directory\n"
)
return
if self.fs.isdir(resolv(dest)):
isdir = True
else:
isdir = False
parent = os.path.dirname(resolv(dest))
if not self.fs.exists(parent):
self.errorWrite(
"cp: cannot create regular file "
+ f"`{dest}': No such file or directory\n"
)
return
for src in sources:
if not self.fs.exists(resolv(src)):
self.errorWrite(f"cp: cannot stat `{src}': No such file or directory\n")
continue
if not recursive and self.fs.isdir(resolv(src)):
self.errorWrite(f"cp: omitting directory `{src}'\n")
continue
s = copy.deepcopy(self.fs.getfile(resolv(src)))
if isdir:
dir = self.fs.get_path(resolv(dest))
outfile = os.path.basename(src)
else:
dir = self.fs.get_path(os.path.dirname(resolv(dest)))
outfile = os.path.basename(dest.rstrip("/"))
if outfile in [x[fs.A_NAME] for x in dir]:
dir.remove([x for x in dir if x[fs.A_NAME] == outfile][0])
s[fs.A_NAME] = outfile
dir.append(s)
commands["/bin/cp"] = Command_cp
commands["cp"] = Command_cp
class Command_mv(HoneyPotCommand):
"""
mv command
"""
def call(self) -> None:
if not len(self.args):
self.errorWrite("mv: missing file operand\n")
self.errorWrite("Try `mv --help' for more information.\n")
return
try:
optlist, args = getopt.gnu_getopt(self.args, "-bfiStTuv")
except getopt.GetoptError:
self.errorWrite("Unrecognized option\n")
self.exit()
def resolv(pname: str) -> str:
rsv: str = self.fs.resolve_path(pname, self.protocol.cwd)
return rsv
if len(args) < 2:
self.errorWrite(
f"mv: missing destination file operand after `{self.args[0]}'\n"
)
self.errorWrite("Try `mv --help' for more information.\n")
return
sources, dest = args[:-1], args[-1]
if len(sources) > 1 and not self.fs.isdir(resolv(dest)):
self.errorWrite(f"mv: target `{dest}' is not a directory\n")
return
if dest[-1] == "/" and not self.fs.exists(resolv(dest)) and len(sources) != 1:
self.errorWrite(
f"mv: cannot create regular file `{dest}': Is a directory\n"
)
return
if self.fs.isdir(resolv(dest)):
isdir = True
else:
isdir = False
parent = os.path.dirname(resolv(dest))
if not self.fs.exists(parent):
self.errorWrite(
"mv: cannot create regular file "
+ f"`{dest}': No such file or directory\n"
)
return
for src in sources:
if not self.fs.exists(resolv(src)):
self.errorWrite(f"mv: cannot stat `{src}': No such file or directory\n")
continue
s = self.fs.getfile(resolv(src))
if isdir:
dir = self.fs.get_path(resolv(dest))
outfile = os.path.basename(src)
else:
dir = self.fs.get_path(os.path.dirname(resolv(dest)))
outfile = os.path.basename(dest)
if dir != os.path.dirname(resolv(src)):
s[fs.A_NAME] = outfile
dir.append(s)
sdir = self.fs.get_path(os.path.dirname(resolv(src)))
sdir.remove(s)
else:
s[fs.A_NAME] = outfile
commands["/bin/mv"] = Command_mv
commands["mv"] = Command_mv
class Command_mkdir(HoneyPotCommand):
"""
mkdir command
"""
def call(self) -> None:
for f in self.args:
pname = self.fs.resolve_path(f, self.protocol.cwd)
if self.fs.exists(pname):
self.errorWrite(f"mkdir: cannot create directory `{f}': File exists\n")
return
try:
self.fs.mkdir(pname, 0, 0, 4096, 16877)
except (fs.FileNotFound):
self.errorWrite(
f"mkdir: cannot create directory `{f}': No such file or directory\n"
)
return
commands["/bin/mkdir"] = Command_mkdir
commands["mkdir"] = Command_mkdir
class Command_rmdir(HoneyPotCommand):
"""
rmdir command
"""
def call(self) -> None:
for f in self.args:
pname = self.fs.resolve_path(f, self.protocol.cwd)
try:
if len(self.fs.get_path(pname)):
self.errorWrite(
f"rmdir: failed to remove `{f}': Directory not empty\n"
)
continue
dir = self.fs.get_path("/".join(pname.split("/")[:-1]))
except (IndexError, fs.FileNotFound):
dir = None
fname = os.path.basename(f)
if not dir or fname not in [x[fs.A_NAME] for x in dir]:
self.errorWrite(
f"rmdir: failed to remove `{f}': No such file or directory\n"
)
continue
for i in dir[:]:
if i[fs.A_NAME] == fname:
if i[fs.A_TYPE] != fs.T_DIR:
self.errorWrite(
f"rmdir: failed to remove '{f}': Not a directory\n"
)
return
dir.remove(i)
break
commands["/bin/rmdir"] = Command_rmdir
commands["rmdir"] = Command_rmdir
class Command_pwd(HoneyPotCommand):
"""
pwd command
"""
def call(self) -> None:
self.write(self.protocol.cwd + "\n")
commands["/bin/pwd"] = Command_pwd
commands["pwd"] = Command_pwd
class Command_touch(HoneyPotCommand):
"""
touch command
"""
def call(self) -> None:
if not len(self.args):
self.errorWrite("touch: missing file operand\n")
self.errorWrite("Try `touch --help' for more information.\n")
return
for f in self.args:
pname = self.fs.resolve_path(f, self.protocol.cwd)
if not self.fs.exists(os.path.dirname(pname)):
self.errorWrite(
f"touch: cannot touch `{pname}`: No such file or directory\n"
)
return
if self.fs.exists(pname):
# FIXME: modify the timestamp here
continue
# can't touch in special directories
if any([pname.startswith(_p) for _p in fs.SPECIAL_PATHS]):
self.errorWrite(f"touch: cannot touch `{pname}`: Permission denied\n")
return
self.fs.mkfile(pname, 0, 0, 0, 33188)
commands["/bin/touch"] = Command_touch
commands["touch"] = Command_touch
commands[">"] = Command_touch
| 20,701 | 30.947531 | 90 | py |
cowrie | cowrie-master/src/cowrie/commands/apt.py |
from __future__ import annotations
import random
import re
from typing import Any, Optional
from collections.abc import Callable
from twisted.internet import defer, reactor
from twisted.internet.defer import inlineCallbacks
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_faked_package_class_factory:
@staticmethod
def getCommand(name: str) -> Callable:
class Command_faked_installation(HoneyPotCommand):
def call(self) -> None:
self.write(f"{name}: Segmentation fault\n")
return Command_faked_installation
class Command_aptget(HoneyPotCommand):
"""
apt-get fake
suppports only the 'install PACKAGE' command & 'moo'.
Any installed packages, places a 'Segfault' at /usr/bin/PACKAGE.'''
"""
packages: dict[str, dict[str, Any]] = {}
def start(self) -> None:
if len(self.args) == 0:
self.do_help()
elif len(self.args) > 0 and self.args[0] == "-v":
self.do_version()
elif len(self.args) > 0 and self.args[0] == "install":
self.do_install()
elif len(self.args) > 0 and self.args[0] == "moo":
self.do_moo()
else:
self.do_locked()
def sleep(self, time: float, time2: Optional[float] = None) -> defer.Deferred:
d: defer.Deferred = defer.Deferred()
if time2:
time = random.randint(int(time * 100), int(time2 * 100.0)) / 100.0
reactor.callLater(time, d.callback, None) # type: ignore[attr-defined]
return d
def do_version(self) -> None:
self.write(
"""apt 1.0.9.8.1 for amd64 compiled on Jun 10 2015 09:42:06
Supported modules:
*Ver: Standard .deb
*Pkg: Debian dpkg interface (Priority 30)
Pkg: Debian APT solver interface (Priority -1000)
S.L: 'deb' Standard Debian binary tree
S.L: 'deb-src' Standard Debian source tree
Idx: Debian Source Index
Idx: Debian Package Index
Idx: Debian Translation Index
Idx: Debian dpkg status file
Idx: EDSP scenario file\n"""
)
self.exit()
def do_help(self) -> None:
self.write(
"""apt 1.0.9.8.1 for amd64 compiled on Jun 10 2015 09:42:06
Usage: apt-get [options] command
apt-get [options] install|remove pkg1 [pkg2 ...]
apt-get [options] source pkg1 [pkg2 ...]
apt-get is a simple command line interface for downloading and
installing packages. The most frequently used commands are update
and install.
Commands:
update - Retrieve new lists of packages
upgrade - Perform an upgrade
install - Install new packages (pkg is libc6 not libc6.deb)
remove - Remove packages
autoremove - Remove automatically all unused packages
purge - Remove packages and config files
source - Download source archives
build-dep - Configure build-dependencies for source packages
dist-upgrade - Distribution upgrade, see apt-get(8)
dselect-upgrade - Follow dselect selections
clean - Erase downloaded archive files
autoclean - Erase old downloaded archive files
check - Verify that there are no broken dependencies
changelog - Download and display the changelog for the given package
download - Download the binary package into the current directory
Options:
-h This help text.
-q Loggable output - no progress indicator
-qq No output except for errors
-d Download only - do NOT install or unpack archives
-s No-act. Perform ordering simulation
-y Assume Yes to all queries and do not prompt
-f Attempt to correct a system with broken dependencies in place
-m Attempt to continue if archives are unlocatable
-u Show a list of upgraded packages as well
-b Build the source package after fetching it
-V Show verbose version numbers
-c=? Read this configuration file
-o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp
See the apt-get(8), sources.list(5) and apt.conf(5) manual
pages for more information and options.
This APT has Super Cow Powers.\n"""
)
self.exit()
@inlineCallbacks
def do_install(self, *args):
if len(self.args) <= 1:
msg = "0 upgraded, 0 newly installed, 0 to remove and {0} not upgraded.\n"
self.write(msg.format(random.randint(200, 300)))
self.exit()
return
for y in [re.sub("[^A-Za-z0-9]", "", x) for x in self.args[1:]]:
self.packages[y] = {
"version": "{}.{}-{}".format(
random.choice([0, 1]), random.randint(1, 40), random.randint(1, 10)
),
"size": random.randint(100, 900),
}
totalsize: int = sum(self.packages[x]["size"] for x in self.packages)
self.write("Reading package lists... Done\n")
self.write("Building dependency tree\n")
self.write("Reading state information... Done\n")
self.write("The following NEW packages will be installed:\n")
self.write(" %s " % " ".join(self.packages) + "\n")
self.write(
"0 upgraded, %d newly installed, 0 to remove and 259 not upgraded.\n"
% len(self.packages)
)
self.write("Need to get %s.2kB of archives.\n" % (totalsize))
self.write(
"After this operation, {:.1f}kB of additional disk space will be used.\n".format(
totalsize * 2.2
)
)
i = 1
for p in self.packages:
self.write(
"Get:%d http://ftp.debian.org stable/main %s %s [%s.2kB]\n"
% (i, p, self.packages[p]["version"], self.packages[p]["size"])
)
i += 1
yield self.sleep(1, 2)
self.write(f"Fetched {totalsize}.2kB in 1s (4493B/s)\n")
self.write("Reading package fields... Done\n")
yield self.sleep(1, 2)
self.write("Reading package status... Done\n")
self.write(
"(Reading database ... 177887 files and directories currently installed.)\n"
)
yield self.sleep(1, 2)
for p in self.packages:
self.write(
"Unpacking {} (from .../archives/{}_{}_i386.deb) ...\n".format(
p, p, self.packages[p]["version"]
)
)
yield self.sleep(1, 2)
self.write("Processing triggers for man-db ...\n")
yield self.sleep(2)
for p in self.packages:
self.write(
"Setting up {} ({}) ...\n".format(p, self.packages[p]["version"])
)
self.fs.mkfile("/usr/bin/%s" % p, 0, 0, random.randint(10000, 90000), 33188)
self.protocol.commands[
"/usr/bin/%s" % p
] = Command_faked_package_class_factory.getCommand(p)
yield self.sleep(2)
self.exit()
def do_moo(self) -> None:
self.write(" (__)\n")
self.write(" (oo)\n")
self.write(" /------\\/\n")
self.write(" / | ||\n")
self.write(" * /\\---/\\ \n")
self.write(" ~~ ~~\n")
self.write('...."Have you mooed today?"...\n')
self.exit()
def do_locked(self) -> None:
self.errorWrite(
"E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)\n"
)
self.errorWrite("E: Unable to lock the list directory\n")
self.exit()
commands["/usr/bin/apt-get"] = Command_aptget
commands["apt-get"] = Command_aptget
| 7,618 | 35.109005 | 98 | py |
cowrie | cowrie-master/src/cowrie/commands/sudo.py | from __future__ import annotations
import getopt
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.honeypot import StdOutStdErrEmulationProtocol
commands = {}
sudo_shorthelp = (
(
"""
sudo: Only one of the -e, -h, -i, -K, -l, -s, -v or -V options may be specified
usage: sudo [-D level] -h | -K | -k | -V
usage: sudo -v [-AknS] [-D level] [-g groupname|#gid] [-p prompt] [-u user name|#uid]
usage: sudo -l[l] [-AknS] [-D level] [-g groupname|#gid] [-p prompt] [-U user name] [-u user name|#uid] [-g groupname|#gid] [command]
usage: sudo [-AbEHknPS] [-r role] [-t type] [-C fd] [-D level] [-g groupname|#gid] [-p prompt] [-u user name|#uid] [-g groupname|#gid] [VAR=value] [-i|-s] [<command>]
usage: sudo -e [-AknS] [-r role] [-t type] [-C fd] [-D level] [-g groupname|#gid] [-p prompt] [-u user name|#uid] file ...
"""
)
.strip()
.split("\n")
)
sudo_longhelp = (
(
"""
sudo - execute a command as another user
usage: sudo [-D level] -h | -K | -k | -V
usage: sudo -v [-AknS] [-D level] [-g groupname|#gid] [-p prompt] [-u user name|#uid]
usage: sudo -l[l] [-AknS] [-D level] [-g groupname|#gid] [-p prompt] [-U user name] [-u user name|#uid] [-g groupname|#gid] [command]
usage: sudo [-AbEHknPS] [-r role] [-t type] [-C fd] [-D level] [-g groupname|#gid] [-p prompt] [-u user name|#uid] [-g groupname|#gid] [VAR=value] [-i|-s] [<command>]
usage: sudo -e [-AknS] [-r role] [-t type] [-C fd] [-D level] [-g groupname|#gid] [-p prompt] [-u user name|#uid] file ...
Options:
-a type use specified BSD authentication type
-b run command in the background
-C fd close all file descriptors >= fd
-E preserve user environment when executing command
-e edit files instead of running a command
-g group execute command as the specified group
-H set HOME variable to target user's home dir.
-h display help message and exit
-i [command] run a login shell as target user
-K remove timestamp file completely
-k invalidate timestamp file
-l[l] command list user's available commands
-n non-interactive mode, will not prompt user
-P preserve group vector instead of setting to target's
-p prompt use specified password prompt
-r role create SELinux security context with specified role
-S read password from standard input
-s [command] run a shell as target user
-t type create SELinux security context with specified role
-U user when listing, list specified user's privileges
-u user run command (or edit file) as specified user
-V display version information and exit
-v update user's timestamp without running a command
-- stop processing command line arguments
"""
)
.strip()
.split("\n")
)
class Command_sudo(HoneyPotCommand):
def short_help(self) -> None:
for ln in sudo_shorthelp:
self.errorWrite(f"{ln}\n")
self.exit()
def long_help(self) -> None:
for ln in sudo_longhelp:
self.errorWrite(f"{ln}\n")
self.exit()
def version(self) -> None:
self.errorWrite(
"""Sudo version 1.8.5p2
Sudoers policy plugin version 1.8.5p2
Sudoers file grammar version 41
Sudoers I/O plugin version 1.8.5p2\n"""
)
self.exit()
def start(self) -> None:
start_value = None
parsed_arguments = []
for count in range(0, len(self.args)):
class_found = self.protocol.getCommand(
self.args[count], self.environ["PATH"].split(":")
)
if class_found:
start_value = count
break
if start_value is not None:
for index_2 in range(start_value, len(self.args)):
parsed_arguments.append(self.args[index_2])
try:
optlist, args = getopt.getopt(
self.args[0:start_value], "bEeHhKknPSVva:C:g:i:l:p:r:s:t:U:u:"
)
except getopt.GetoptError as err:
self.errorWrite("sudo: illegal option -- " + err.opt + "\n")
self.short_help()
return
for o, _a in optlist:
if o in ("-V"):
self.version()
return
elif o in ("-h"):
self.long_help()
return
if len(parsed_arguments) > 0:
cmd = parsed_arguments[0]
cmdclass = self.protocol.getCommand(cmd, self.environ["PATH"].split(":"))
if cmdclass:
command = StdOutStdErrEmulationProtocol(
self.protocol, cmdclass, parsed_arguments[1:], None, None
)
self.protocol.pp.insert_command(command)
# this needs to go here so it doesn't write it out....
if self.input_data:
self.writeBytes(self.input_data)
self.exit()
else:
self.short_help()
else:
self.short_help()
commands["sudo"] = Command_sudo
| 5,193 | 36.637681 | 166 | py |
cowrie | cowrie-master/src/cowrie/commands/uniq.py |
"""
uniq command
"""
from __future__ import annotations
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
commands = {}
UNIQ_HELP = """Usage: uniq [OPTION]... [INPUT [OUTPUT]]
Filter adjacent matching lines from INPUT (or standard input),
writing to OUTPUT (or standard output).
With no options, matching lines are merged to the first occurrence.
Mandatory arguments to long options are mandatory for short options too.
-c, --count prefix lines by the number of occurrences
-d, --repeated only print duplicate lines, one for each group
-D print all duplicate lines
--all-repeated[=METHOD] like -D, but allow separating groups
with an empty line;
METHOD={none(default),prepend,separate}
-f, --skip-fields=N avoid comparing the first N fields
--group[=METHOD] show all items, separating groups with an empty line;
METHOD={separate(default),prepend,append,both}
-i, --ignore-case ignore differences in case when comparing
-s, --skip-chars=N avoid comparing the first N characters
-u, --unique only print unique lines
-z, --zero-terminated line delimiter is NUL, not newline
-w, --check-chars=N compare no more than N characters in lines
--help display this help and exit
--version output version information and exit
A field is a run of blanks (usually spaces and/or TABs), then non-blank
characters. Fields are skipped before chars.
Note: 'uniq' does not detect repeated lines unless they are adjacent.
You may want to sort the input first, or use 'sort -u' without 'uniq'.
Also, comparisons honor the rules specified by 'LC_COLLATE'.
GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation at: <https://www.gnu.org/software/coreutils/uniq>
or available locally via: info '(coreutils) uniq invocation'
"""
class Command_uniq(HoneyPotCommand):
last_line = None
def start(self) -> None:
if "--help" in self.args:
self.writeBytes(UNIQ_HELP.encode())
self.exit()
elif self.input_data:
lines = self.input_data.split(b"\n")
if not lines[-1]:
lines.pop()
for line in lines:
self.grep_input(line)
self.exit()
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.command.input",
realm="uniq",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
self.grep_input(line.encode())
def handle_CTRL_D(self) -> None:
self.exit()
def grep_input(self, line: bytes) -> None:
if not line == self.last_line:
self.writeBytes(line + b"\n")
self.last_line = line
commands["/usr/bin/uniq"] = Command_uniq
commands["uniq"] = Command_uniq
| 3,069 | 33.494382 | 77 | py |
cowrie | cowrie-master/src/cowrie/commands/awk.py | # Contributor: Fosocles
"""
awk command
limited implementation that only supports `print` command.
"""
from __future__ import annotations
import getopt
import re
from typing import Optional
from re import Match
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.fs import FileNotFound
commands = {}
class Command_awk(HoneyPotCommand):
"""
awk command
"""
# code is an array of dictionaries contain the regexes to match and the code to execute
code: list[dict[str, str]] = []
def start(self) -> None:
try:
optlist, args = getopt.gnu_getopt(self.args, "Fvf", ["version"])
except getopt.GetoptError as err:
self.errorWrite(
"awk: invalid option -- '{}'\nTry 'awk --help' for more information.\n".format(
err.opt
)
)
self.exit()
return
for o, _a in optlist:
if o in "--help":
self.help()
self.exit()
return
elif o in "--version":
self.version()
self.exit()
return
elif o in ("-n", "--number"):
pass
# first argument is program (generally between quotes if contains spaces)
# second and onward arguments are files to operate on
if len(args) == 0:
self.help()
self.exit()
return
self.code = self.awk_parser(args.pop(0))
if len(args) > 0:
for arg in args:
if arg == "-":
self.output(self.input_data)
continue
pname = self.fs.resolve_path(arg, self.protocol.cwd)
if self.fs.isdir(pname):
self.errorWrite(f"awk: {arg}: Is a directory\n")
continue
try:
contents = self.fs.file_contents(pname)
if contents:
self.output(contents)
else:
raise FileNotFound
except FileNotFound:
self.errorWrite(f"awk: {arg}: No such file or directory\n")
else:
self.output(self.input_data)
self.exit()
def awk_parser(self, program: str) -> list[dict[str, str]]:
"""
search for awk execution patterns, either direct {} code or only executed for a certain regex
{ }
/regex/ { }
"""
code = []
re1 = r"\s*(\/(?P<pattern>\S+)\/\s+)?\{\s*(?P<code>[^\}]+)\}\s*"
matches = re.findall(re1, program)
for m in matches:
code.append({"regex": m[1], "code": m[2]})
return code
def awk_print(self, words: str) -> None:
"""
This is the awk `print` command that operates on a single line only
"""
self.write(words)
self.write("\n")
def output(self, inb: Optional[bytes]) -> None:
"""
This is the awk output.
"""
if inb:
inp = inb.decode("utf-8")
else:
return
inputlines = inp.split("\n")
if inputlines[-1] == "":
inputlines.pop()
def repl(m: Match) -> str:
try:
return words[int(m.group(1))]
except IndexError:
return ""
for inputline in inputlines:
# split by whitespace and add full line in $0 as awk does.
# TODO: change here to use custom field separator
words = inputline.split()
words.insert(0, inputline)
for c in self.code:
if re.match(c["regex"], inputline):
line = c["code"]
line = re.sub(r"\$(\d+)", repl, line)
# print("LINE1: {}".format(line))
if re.match(r"^print\s*", line):
# remove `print` at the start
line = re.sub(r"^\s*print\s+", "", line)
# remove whitespace at the end
line = re.sub(r"[;\s]*$", "", line)
# replace whitespace and comma by single space
line = re.sub(r"(,|\s+)", " ", line)
# print("LINE2: {}".format(line))
self.awk_print(line)
def lineReceived(self, line: str) -> None:
"""
This function logs standard input from the user send to awk
"""
log.msg(
eventid="cowrie.session.input",
realm="awk",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
self.output(line.encode())
def handle_CTRL_D(self) -> None:
"""
ctrl-d is end-of-file, time to terminate
"""
self.exit()
def help(self) -> None:
self.write(
"""Usage: awk [POSIX or GNU style options] -f progfile [--] file ...
Usage: awk [POSIX or GNU style options] [--] 'program' file ...
POSIX options: GNU long options: (standard)
-f progfile --file=progfile
-F fs --field-separator=fs
-v var=val --assign=var=val
Short options: GNU long options: (extensions)
-b --characters-as-bytes
-c --traditional
-C --copyright
-d[file] --dump-variables[=file]
-D[file] --debug[=file]
-e 'program-text' --source='program-text'
-E file --exec=file
-g --gen-pot
-h --help
-i includefile --include=includefile
-l library --load=library
-L[fatal|invalid] --lint[=fatal|invalid]
-M --bignum
-N --use-lc-numeric
-n --non-decimal-data
-o[file] --pretty-print[=file]
-O --optimize
-p[file] --profile[=file]
-P --posix
-r --re-interval
-S --sandbox
-t --lint-old
-V --version
To report bugs, see node `Bugs' in `gawk.info', which is
section `Reporting Problems and Bugs' in the printed version.
gawk is a pattern scanning and processing language.
By default it reads standard input and writes standard output.
Examples:
gawk '{ sum += $1 }; END { print sum }' file
gawk -F: '{ print $1 }' /etc/passwd
"""
)
def version(self) -> None:
self.write(
"""GNU Awk 4.1.4, API: 1.1 (GNU MPFR 4.0.1, GNU MP 6.1.2)
Copyright (C) 1989, 1991-2016 Free Software Foundation.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
"""
)
commands["/bin/awk"] = Command_awk
commands["awk"] = Command_awk
| 7,810 | 31.410788 | 101 | py |
cowrie | cowrie-master/src/cowrie/commands/finger.py | from __future__ import annotations
from cowrie.shell.command import HoneyPotCommand
import datetime
import getopt
commands = {}
FINGER_HELP = """Usage:"""
class Command_finger(HoneyPotCommand):
def call(self):
time = datetime.datetime.utcnow()
user_data = []
# Get all user data and convert to string
all_users_byte = self.fs.file_contents("/etc/passwd")
all_users = all_users_byte.decode("utf-8")
# Convert all new lines to : character
all_users = all_users.replace("\n", ":")
# Convert into list by splitting string
all_users_list = all_users.split(":")
# Loop over the data in sets of 7
for i in range(0, len(all_users_list), 7):
x = i
# Ensure any added list contains data and is not a blank space by >
if len(all_users_list[x : x + 7]) != 1:
# Take the next 7 elements and put them a list, then add to 2d>
user_data.append(all_users_list[x : x + 7])
# THIS CODE IS FOR DEBUGGING self.write(str(user_data))
# If finger called without args
if len(self.args) == 0:
self.write("Login\tName\tTty Idle\tLogin Time Office Office Phone\n")
for i in range(len(user_data)):
if len(str(user_data[i][0])) > 6:
if len(str(user_data[i][4])) > 6:
self.write(
"{}+ {}+ *:{}\t\t{} (:{})\n".format(
str(user_data[i][0])[:6],
str(user_data[i][4])[:6],
str(user_data[i][2]),
str(time.strftime("%b %d %H:%M")),
str(user_data[i][3]),
)
)
else:
self.write(
"{}+ {}\t*:{}\t\t{} (:{})\n".format(
str(user_data[i][0])[:6],
str(user_data[i][4]),
str(user_data[i][2]),
str(time.strftime("%b %d %H:%M")),
str(user_data[i][3]),
)
)
else:
if len(str(user_data[i][4])) > 6:
self.write(
"{}\t{}+ *:{}\t\t{} (:{})\n".format(
str(user_data[i][0]),
str(user_data[i][4])[:6],
str(user_data[i][2]),
str(time.strftime("%b %d %H:%M")),
str(user_data[i][3]),
)
)
else:
self.write(
"{}\t{}\t*:{}\t\t{} (:{})\n".format(
str(user_data[i][0]),
str(user_data[i][4]),
str(user_data[i][2]),
str(time.strftime("%b %d %H:%M")),
str(user_data[i][3]),
)
)
# self.write(f"name: %20." + str(user_data[i][0]) + "\n") >
# time = datetime.datetime.utcnow()
# self.write("{}\n".format(time.strftime("%a %b %d %H:%M:%S UTC %Y">
return
if len(self.args):
try:
opts, args = getopt.gnu_getopt(self.args, "")
except getopt.GetoptError as err:
self.errorWrite(
f"""finger: invalid option -- '{err.opt}'
usage: finger [-lmps] [login ...]\n"""
)
return
# If args given not any predefined, assume is username
if len(args) > 0:
for i in range(len(user_data)):
# Run if check to check if user is real
if args[0] == user_data[i][0]:
# Display user data
self.write(
"""Login: """
+ str(user_data[i][0])
+ """ Name: """
+ str(user_data[i][4])
+ """
Directory: """
+ str(user_data[i][5])
+ """ Shell: """
+ str(user_data[i][6])
+ """
On since """
+ str(time.strftime("%a %b %d %H:%M"))
+ """ (UTC) on :0 from :0 (messages off)
No mail.
No Plan.
"""
)
return
# If user is NOT real inform user
self.write(f"finger: {args[0]}: no such user\n")
# IF TIME ALLOWS: Seperate into multiple functions
# IF TIME ALLOWS: Make my comments more concise and remove debuggi>
return
# Base.py has some helpful stuff
return
commands["bin/finger"] = Command_finger
commands["finger"] = Command_finger
| 5,199 | 39.310078 | 84 | py |
cowrie | cowrie-master/src/cowrie/commands/ulimit.py | # All rights reserved.
"""
This module ...
"""
from __future__ import annotations
import getopt
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_ulimit(HoneyPotCommand):
"""
ulimit
ulimit: usage: ulimit [-SHacdfilmnpqstuvx] [limit]
"""
def call(self) -> None:
# Parse options or display no files
try:
opts, args = getopt.getopt(self.args, "SHacdfilmnpqstuvx")
except getopt.GetoptError as err:
self.errorWrite(f"-bash: ulimit: {err}\n")
self.write("ulimit: usage: ulimit [-SHacdfilmnpqstuvx] [limit]\n")
return
# Parse options
for o, a in opts:
if o in ("-c"):
self.do_ulimit(key="core", value=int(a))
return
elif o in ("-a"):
self.do_ulimit(key="all")
return
self.do_ulimit()
def do_ulimit(self, key: str = "core", value: int = 0) -> None:
pass
commands["ulimit"] = Command_ulimit
| 1,100 | 21.9375 | 78 | py |
cowrie | cowrie-master/src/cowrie/commands/ls.py |
from __future__ import annotations
import getopt
import os.path
import stat
import time
from cowrie.shell import fs
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.pwd import Group, Passwd
commands = {}
class Command_ls(HoneyPotCommand):
def uid2name(self, uid: int) -> str:
try:
name: str = Passwd().getpwuid(uid)["pw_name"]
return name
except Exception:
return str(uid)
def gid2name(self, gid: int) -> str:
try:
group: str = Group().getgrgid(gid)["gr_name"]
return group
except Exception:
return str(gid)
def call(self) -> None:
path = self.protocol.cwd
paths = []
self.showHidden = False
self.showDirectories = False
func = self.do_ls_normal
# Parse options or display no files
try:
opts, args = getopt.gnu_getopt(
self.args,
"1@ABCFGHLOPRSTUWabcdefghiklmnopqrstuvwx",
["help", "version", "param"],
)
except getopt.GetoptError as err:
self.write(f"ls: {err}\n")
self.write("Try 'ls --help' for more information.\n")
return
for x, _a in opts:
if x in ("-l"):
func = self.do_ls_l
if x in ("-a"):
self.showHidden = True
if x in ("-d"):
self.showDirectories = True
for arg in args:
paths.append(self.protocol.fs.resolve_path(arg, self.protocol.cwd))
if not paths:
func(path)
else:
for path in paths:
func(path)
def get_dir_files(self, path):
try:
if self.protocol.fs.isdir(path) and not self.showDirectories:
files = self.protocol.fs.get_path(path)[:]
if self.showHidden:
dot = self.protocol.fs.getfile(path)[:]
dot[fs.A_NAME] = "."
files.append(dot)
dotdot = self.protocol.fs.getfile(os.path.split(path)[0])[:]
if not dotdot:
dotdot = self.protocol.fs.getfile(path)[:]
dotdot[fs.A_NAME] = ".."
files.append(dotdot)
else:
files = [x for x in files if not x[fs.A_NAME].startswith(".")]
files.sort()
else:
files = (self.protocol.fs.getfile(path)[:],)
except Exception:
self.write(f"ls: cannot access {path}: No such file or directory\n")
return
return files
def do_ls_normal(self, path: str) -> None:
files = self.get_dir_files(path)
if not files:
return
line = [x[fs.A_NAME] for x in files]
if not line:
return
count = 0
maxlen = max(len(x) for x in line)
try:
wincols = self.protocol.user.windowSize[1]
except AttributeError:
wincols = 80
perline = int(wincols / (maxlen + 1))
for f in line:
if count == perline:
count = 0
self.write("\n")
self.write(f.ljust(maxlen + 1))
count += 1
self.write("\n")
def do_ls_l(self, path: str) -> None:
files = self.get_dir_files(path)
if not files:
return
filesize_str_extent = 0
if len(files):
filesize_str_extent = max(len(str(x[fs.A_SIZE])) for x in files)
user_name_str_extent = 0
if len(files):
user_name_str_extent = max(len(self.uid2name(x[fs.A_UID])) for x in files)
group_name_str_extent = 0
if len(files):
group_name_str_extent = max(len(self.gid2name(x[fs.A_GID])) for x in files)
for file in files:
if file[fs.A_NAME].startswith(".") and not self.showHidden:
continue
perms = ["-"] * 10
if file[fs.A_MODE] & stat.S_IRUSR:
perms[1] = "r"
if file[fs.A_MODE] & stat.S_IWUSR:
perms[2] = "w"
if file[fs.A_MODE] & stat.S_IXUSR:
perms[3] = "x"
if file[fs.A_MODE] & stat.S_ISUID:
perms[3] = "S"
if file[fs.A_MODE] & stat.S_IXUSR and file[fs.A_MODE] & stat.S_ISUID:
perms[3] = "s"
if file[fs.A_MODE] & stat.S_IRGRP:
perms[4] = "r"
if file[fs.A_MODE] & stat.S_IWGRP:
perms[5] = "w"
if file[fs.A_MODE] & stat.S_IXGRP:
perms[6] = "x"
if file[fs.A_MODE] & stat.S_ISGID:
perms[6] = "S"
if file[fs.A_MODE] & stat.S_IXGRP and file[fs.A_MODE] & stat.S_ISGID:
perms[6] = "s"
if file[fs.A_MODE] & stat.S_IROTH:
perms[7] = "r"
if file[fs.A_MODE] & stat.S_IWOTH:
perms[8] = "w"
if file[fs.A_MODE] & stat.S_IXOTH:
perms[9] = "x"
if file[fs.A_MODE] & stat.S_ISVTX:
perms[9] = "T"
if file[fs.A_MODE] & stat.S_IXOTH and file[fs.A_MODE] & stat.S_ISVTX:
perms[9] = "t"
linktarget = ""
if file[fs.A_TYPE] == fs.T_DIR:
perms[0] = "d"
elif file[fs.A_TYPE] == fs.T_LINK:
perms[0] = "l"
linktarget = f" -> {file[fs.A_TARGET]}"
permstr = "".join(perms)
ctime = time.localtime(file[fs.A_CTIME])
line = "{} 1 {} {} {} {} {}{}".format(
permstr,
self.uid2name(file[fs.A_UID]).ljust(user_name_str_extent),
self.gid2name(file[fs.A_GID]).ljust(group_name_str_extent),
str(file[fs.A_SIZE]).rjust(filesize_str_extent),
time.strftime("%Y-%m-%d %H:%M", ctime),
file[fs.A_NAME],
linktarget,
)
self.write(f"{line}\n")
commands["/bin/ls"] = Command_ls
commands["ls"] = Command_ls
commands["/bin/dir"] = Command_ls
commands["dir"] = Command_ls
| 6,339 | 30.7 | 87 | py |
cowrie | cowrie-master/src/cowrie/commands/cat.py |
"""
cat command
"""
from __future__ import annotations
import getopt
from typing import Optional
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.fs import FileNotFound
commands = {}
class Command_cat(HoneyPotCommand):
"""
cat command
"""
number = False
linenumber = 1
def start(self) -> None:
try:
optlist, args = getopt.gnu_getopt(
self.args, "AbeEnstTuv", ["help", "number", "version"]
)
except getopt.GetoptError as err:
self.errorWrite(
f"cat: invalid option -- '{err.opt}'\nTry 'cat --help' for more information.\n"
)
self.exit()
return
for o, _a in optlist:
if o in ("--help"):
self.help()
self.exit()
return
elif o in ("-n", "--number"):
self.number = True
if len(args) > 0:
for arg in args:
if arg == "-":
self.output(self.input_data)
continue
pname = self.fs.resolve_path(arg, self.protocol.cwd)
if self.fs.isdir(pname):
self.errorWrite(f"cat: {arg}: Is a directory\n")
continue
try:
contents = self.fs.file_contents(pname)
if contents:
self.output(contents)
else:
raise FileNotFound
except FileNotFound:
self.errorWrite(f"cat: {arg}: No such file or directory\n")
self.exit()
elif self.input_data is not None:
self.output(self.input_data)
self.exit()
def output(self, inb: Optional[bytes]) -> None:
"""
This is the cat output, with optional line numbering
"""
if inb is None:
return
lines = inb.split(b"\n")
if lines[-1] == b"":
lines.pop()
for line in lines:
if self.number:
self.write(f"{self.linenumber:>6} ")
self.linenumber = self.linenumber + 1
self.writeBytes(line + b"\n")
def lineReceived(self, line: str) -> None:
"""
This function logs standard input from the user send to cat
"""
log.msg(
eventid="cowrie.session.input",
realm="cat",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
self.output(line.encode("utf-8"))
def handle_CTRL_D(self) -> None:
"""
ctrl-d is end-of-file, time to terminate
"""
self.exit()
def help(self) -> None:
self.write(
"""Usage: cat [OPTION]... [FILE]...
Concatenate FILE(s) to standard output.
With no FILE, or when FILE is -, read standard input.
-A, --show-all equivalent to -vET
-b, --number-nonblank number nonempty output lines, overrides -n
-e equivalent to -vE
-E, --show-ends display $ at end of each line
-n, --number number all output lines
-s, --squeeze-blank suppress repeated empty output lines
-t equivalent to -vT
-T, --show-tabs display TAB characters as ^I
-u (ignored)
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
--help display this help and exit
--version output version information and exit
Examples:
cat f - g Output f's contents, then standard input, then g's contents.
cat Copy standard input to standard output.
GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
Full documentation at: <http://www.gnu.org/software/coreutils/cat>
or available locally via: info '(coreutils) cat invocation'
"""
)
commands["/bin/cat"] = Command_cat
commands["cat"] = Command_cat
| 4,155 | 28.062937 | 95 | py |
cowrie | cowrie-master/src/cowrie/commands/ping.py |
from __future__ import annotations
import getopt
import hashlib
import random
import re
import socket
from typing import Any
from twisted.internet import reactor
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_ping(HoneyPotCommand):
"""
ping command
"""
host: str
ip: str
count: int
max: int
running: bool
scheduled: Any
def valid_ip(self, address: str) -> bool:
try:
socket.inet_aton(address)
return True
except Exception:
return False
def start(self) -> None:
self.host = ""
self.max = 0
self.running = False
try:
optlist, args = getopt.gnu_getopt(self.args, "c:")
except getopt.GetoptError as err:
self.write(f"ping: {err}\n")
self.exit()
return
for opt in optlist:
if opt[0] == "-c":
try:
self.max = int(opt[1])
except Exception:
self.max = 0
if self.max <= 0:
self.write("ping: bad number of packets to transmit.\n")
self.exit()
return
if len(args) == 0:
for line in (
"Usage: ping [-LRUbdfnqrvVaA] [-c count] [-i interval] [-w deadline]",
" [-p pattern] [-s packetsize] [-t ttl] [-I interface or address]",
" [-M mtu discovery hint] [-S sndbuf]",
" [ -T timestamp option ] [ -Q tos ] [hop1 ...] destination",
):
self.write(f"{line}\n")
self.exit()
return
self.host = args[0].strip()
if re.match("^[0-9.]+$", self.host):
if self.valid_ip(self.host):
self.ip = self.host
else:
self.write(f"ping: unknown host {self.host}\n")
self.exit()
else:
s = hashlib.md5((self.host).encode("utf-8")).hexdigest()
self.ip = ".".join(
[str(int(x, 16)) for x in (s[0:2], s[2:4], s[4:6], s[6:8])]
)
self.running = True
self.write(f"PING {self.host} ({self.ip}) 56(84) bytes of data.\n")
self.scheduled = reactor.callLater(0.2, self.showreply) # type: ignore[attr-defined]
self.count = 0
def showreply(self) -> None:
ms = 40 + random.random() * 10
self.write(
"64 bytes from {} ({}): icmp_seq={} ttl=50 time={:.1f} ms\n".format(
self.host, self.ip, self.count + 1, ms
)
)
self.count += 1
if self.count == self.max:
self.running = False
self.write("\n")
self.printstatistics()
self.exit()
else:
self.scheduled = reactor.callLater(1, self.showreply) # type: ignore[attr-defined]
def printstatistics(self) -> None:
self.write(f"--- {self.host} ping statistics ---\n")
self.write(
"%d packets transmitted, %d received, 0%% packet loss, time 907ms\n"
% (self.count, self.count)
)
self.write("rtt min/avg/max/mdev = 48.264/50.352/52.441/2.100 ms\n")
def handle_CTRL_C(self) -> None:
if self.running is False:
return HoneyPotCommand.handle_CTRL_C(self)
else:
self.write("^C\n")
self.scheduled.cancel()
self.printstatistics()
self.exit()
commands["/bin/ping"] = Command_ping
commands["ping"] = Command_ping
| 3,730 | 28.377953 | 95 | py |
cowrie | cowrie-master/src/cowrie/commands/netstat.py | # Based on work by Peter Reuteras (https://bitbucket.org/reuteras/kippo/)
from __future__ import annotations
import socket
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_netstat(HoneyPotCommand):
def show_version(self) -> None:
self.write("net-tools 1.60\n")
self.write("netstat 1.42 (2001-04-15)\n")
self.write(
"Fred Baumgarten, Alan Cox, Bernd Eckenfels, Phil Blundell, Tuan Hoang and others\n"
)
self.write("+NEW_ADDRT +RTF_IRTT +RTF_REJECT +FW_MASQUERADE +I18N\n")
self.write(
"AF: (inet) +UNIX +INET +INET6 +IPX +AX25 +NETROM +X25 +ATALK +ECONET +ROSE\n"
)
self.write(
"HW: +ETHER +ARC +SLIP +PPP +TUNNEL +TR +AX25 +NETROM +X25"
+ "+FR +ROSE +ASH +SIT +FDDI +HIPPI +HDLC/LAPB +EUI64\n"
)
def show_help(self) -> None:
self.write(
"""
usage: netstat [-vWeenNcCF] [<Af>] -r netstat {-V|--version|-h|--help}
netstat [-vWnNcaeol] [<Socket> ...]
netstat { [-vWeenNac] -i | [-cWnNe] -M | -s }
-r, --route display routing table
-i, --interfaces display interface table
-g, --groups display multicast group memberships
-s, --statistics display networking statistics (like SNMP)
-M, --masquerade display masqueraded connections
-v, --verbose be verbose
-W, --wide don\'t truncate IP addresses
-n, --numeric don\'t resolve names
--numeric-hosts don\'t resolve host names
--numeric-ports don\'t resolve port names
--numeric-users don\'t resolve user names
-N, --symbolic resolve hardware names
-e, --extend display other/more information
-p, --programs display PID/Program name for sockets
-c, --continuous continuous listing
-l, --listening display listening server sockets
-o, --timers display timers
-F, --fib display Forwarding Information Base (default)
-C, --cache display routing cache instead of FIB
<Socket>={-t|--tcp} {-u|--udp} {-w|--raw} {-x|--unix} --ax25 --ipx --netrom
<AF>=Use \'-6|-4\' or \'-A <af>\' or \'--<af>\'; default: inet
List of possible address families (which support routing):
inet (DARPA Internet) inet6 (IPv6) ax25 (AMPR AX.25)
netrom (AMPR NET/ROM) ipx (Novell IPX) ddp (Appletalk DDP)
x25 (CCITT X.25)
"""
)
def do_netstat_route(self) -> None:
self.write(
"""Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface\n"""
)
if self.show_numeric:
default = "default"
lgateway = "0.0.0.0"
else:
default = "0.0.0.0"
lgateway = "*"
destination = self.protocol.kippoIP.rsplit(".", 1)[0] + ".0"
gateway = self.protocol.kippoIP.rsplit(".", 1)[0] + ".1"
l1 = "{}{}0.0.0.0 UG 0 0 0 eth0".format(
f"{default:<16}",
f"{gateway:<16}",
)
l2 = "{}{}255.255.255.0 U 0 0 0 eth0".format(
f"{destination:<16}",
f"{lgateway:<16}",
)
self.write(f"{l1}\n")
self.write(f"{l2}\n")
def do_netstat_normal(self) -> None:
self.write(
"""Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State\n"""
)
s_name = self.protocol.hostname
c_port = str(self.protocol.realClientPort)
if self.show_numeric:
s_port = "22"
c_name = str(self.protocol.clientIP)
s_name = str(self.protocol.kippoIP)
else:
s_port = "ssh"
try:
c_name = socket.gethostbyaddr(self.protocol.clientIP)[0][:17]
except Exception:
c_name = self.protocol.clientIP
if self.show_listen or self.show_all:
self.write(
"tcp 0 0 *:ssh *:* LISTEN\n"
)
if not self.show_listen or self.show_all:
line = "tcp 0 308 {}:{}{}{}:{}{}{}".format(
s_name,
s_port,
" " * (24 - len(s_name + s_port) - 1),
c_name,
c_port,
" " * (24 - len(c_name + c_port) - 1),
"ESTABLISHED",
)
self.write(f"{line}\n")
if self.show_listen or self.show_all:
self.write(
"tcp6 0 0 [::]:ssh [::]:* LISTEN\n"
)
self.write(
"""Active UNIX domain sockets (only servers)
Proto RefCnt Flags Type State I-Node Path\n"""
)
if self.show_listen:
self.write(
"""unix 2 [ ACC ] STREAM LISTENING 8969 /var/run/acpid.socket
unix 2 [ ACC ] STREAM LISTENING 6807 @/com/ubuntu/upstart
unix 2 [ ACC ] STREAM LISTENING 7299 /var/run/dbus/system_bus_socket
unix 2 [ ACC ] SEQPACKET LISTENING 7159 /run/udev/control\n"""
)
elif self.show_all:
self.write(
"""unix 2 [ ACC ] STREAM LISTENING 8969 /var/run/acpid.socket
unix 4 [ ] DGRAM 7445 /dev/log
unix 2 [ ACC ] STREAM LISTENING 6807 @/com/ubuntu/upstart
unix 2 [ ACC ] STREAM LISTENING 7299 /var/run/dbus/system_bus_socket
unix 2 [ ACC ] SEQPACKET LISTENING 7159 /run/udev/control
unix 3 [ ] STREAM CONNECTED 7323
unix 3 [ ] STREAM CONNECTED 7348 /var/run/dbus/system_bus_socket
unix 3 [ ] STREAM CONNECTED 7330
unix 2 [ ] DGRAM 8966
unix 3 [ ] STREAM CONNECTED 7424 /var/run/dbus/system_bus_socket
unix 3 [ ] STREAM CONNECTED 7140
unix 3 [ ] STREAM CONNECTED 7145 @/com/ubuntu/upstart
unix 3 [ ] DGRAM 7199
unix 3 [ ] STREAM CONNECTED 7347
unix 3 [ ] STREAM CONNECTED 8594
unix 3 [ ] STREAM CONNECTED 7331
unix 3 [ ] STREAM CONNECTED 7364 @/com/ubuntu/upstart
unix 3 [ ] STREAM CONNECTED 7423
unix 3 [ ] DGRAM 7198
unix 2 [ ] DGRAM 9570
unix 3 [ ] STREAM CONNECTED 8619 @/com/ubuntu/upstart\n"""
)
else:
self.write(
"""unix 4 [ ] DGRAM 7445 /dev/log
unix 3 [ ] STREAM CONNECTED 7323
unix 3 [ ] STREAM CONNECTED 7348 /var/run/dbus/system_bus_socket
unix 3 [ ] STREAM CONNECTED 7330
unix 2 [ ] DGRAM 8966
unix 3 [ ] STREAM CONNECTED 7424 /var/run/dbus/system_bus_socket
unix 3 [ ] STREAM CONNECTED 7140
unix 3 [ ] STREAM CONNECTED 7145 @/com/ubuntu/upstart
unix 3 [ ] DGRAM 7199
unix 3 [ ] STREAM CONNECTED 7347
unix 3 [ ] STREAM CONNECTED 8594
unix 3 [ ] STREAM CONNECTED 7331
unix 3 [ ] STREAM CONNECTED 7364 @/com/ubuntu/upstart
unix 3 [ ] STREAM CONNECTED 7423
unix 3 [ ] DGRAM 7198
unix 2 [ ] DGRAM 9570
unix 3 [ ] STREAM CONNECTED 8619 @/com/ubuntu/upstart\n"""
)
def call(self) -> None:
self.show_all = False
self.show_numeric = False
self.show_listen = False
func = self.do_netstat_normal
for x in self.args:
if x.startswith("-") and x.count("a"):
self.show_all = True
if x.startswith("-") and x.count("n"):
self.show_numeric = True
if x.startswith("-") and x.count("l"):
self.show_listen = True
if x.startswith("-") and x.count("r"):
func = self.do_netstat_route
if x.startswith("-") and x.count("h"):
func = self.show_help
if x.startswith("-") and x.count("V"):
func = self.show_version
func()
commands["/bin/netstat"] = Command_netstat
commands["netstat"] = Command_netstat
| 9,000 | 42.694175 | 99 | py |
cowrie | cowrie-master/src/cowrie/commands/ssh.py |
from __future__ import annotations
import getopt
import hashlib
import re
import socket
import time
from collections.abc import Callable
from twisted.internet import reactor
from twisted.python import log
from cowrie.core.config import CowrieConfig
from cowrie.shell.command import HoneyPotCommand
commands = {}
OUTPUT = [
"usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]",
" [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]",
" [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]",
" [-i identity_file] [-J [user@]host[:port]] [-L address]",
" [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]",
" [-Q query_option] [-R address] [-S ctl_path] [-W host:port]",
" [-w local_tun[:remote_tun]] destination [command]",
]
class Command_ssh(HoneyPotCommand):
"""
ssh
"""
host: str
callbacks: list[Callable]
def valid_ip(self, address: str) -> bool:
try:
socket.inet_aton(address)
return True
except Exception:
return False
def start(self) -> None:
try:
options = "-1246AaCfgKkMNnqsTtVvXxYb:c:D:e:F:i:L:l:m:O:o:p:R:S:w:"
optlist, args = getopt.getopt(self.args, options)
except getopt.GetoptError:
self.write("Unrecognized option\n")
self.exit()
for opt in optlist:
if opt[0] == "-V":
self.write(
CowrieConfig.get(
"shell",
"ssh_version",
fallback="OpenSSH_7.9p1, OpenSSL 1.1.1a 20 Nov 2018",
)
+ "\n"
)
self.exit()
return
if not len(args):
for line in OUTPUT:
self.write(f"{line}\n")
self.exit()
return
user, host = "root", args[0]
for opt in optlist:
if opt[0] == "-l":
user = opt[1]
if args[0].count("@"):
user, host = args[0].split("@", 1)
if re.match("^[0-9.]+$", host):
if self.valid_ip(host):
self.ip = host
else:
self.write(
"ssh: Could not resolve hostname {}: \
Name or service not known\n".format(
host
)
)
self.exit()
else:
s = hashlib.md5(host.encode()).hexdigest()
self.ip = ".".join(
[str(int(x, 16)) for x in (s[0:2], s[2:4], s[4:6], s[6:8])]
)
self.host = host
self.user = user
self.write(
"The authenticity of host '{} ({})' \
can't be established.\n".format(
self.host, self.ip
)
)
self.write(
"RSA key fingerprint is \
9d:30:97:8a:9e:48:0d:de:04:8d:76:3a:7b:4b:30:f8.\n"
)
self.write("Are you sure you want to continue connecting (yes/no)? ")
self.callbacks = [self.yesno, self.wait]
def yesno(self, line: str) -> None:
self.write(
"Warning: Permanently added '{}' (RSA) to the \
list of known hosts.\n".format(
self.host
)
)
self.write(f"{self.user}@{self.host}'s password: ")
self.protocol.password_input = True
def wait(self, line: str) -> None:
reactor.callLater(2, self.finish, line) # type: ignore[attr-defined]
def finish(self, line: str) -> None:
self.pause = False
rests = self.host.strip().split(".")
if len(rests) and rests[0].isalpha():
host = rests[0]
else:
host = "localhost"
self.protocol.hostname = host
self.protocol.cwd = "/root"
if not self.fs.exists(self.protocol.cwd):
self.protocol.cwd = "/"
self.protocol.password_input = False
self.write(
"Linux {} 2.6.26-2-686 #1 SMP Wed Nov 4 20:45:37 \
UTC 2009 i686\n".format(
self.protocol.hostname
)
)
self.write(f"Last login: {time.ctime(time.time() - 123123)} from 192.168.9.4\n")
self.exit()
def lineReceived(self, line: str) -> None:
log.msg("INPUT (ssh):", line)
if len(self.callbacks):
self.callbacks.pop(0)(line)
commands["/usr/bin/ssh"] = Command_ssh
commands["ssh"] = Command_ssh
| 4,706 | 29.367742 | 88 | py |
cowrie | cowrie-master/src/cowrie/commands/tar.py |
from __future__ import annotations
import os
import tarfile
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.fs import A_REALFILE
commands = {}
class Command_tar(HoneyPotCommand):
def mkfullpath(self, path: str, f: tarfile.TarInfo) -> None:
components, d = path.split("/"), []
while len(components):
d.append(components.pop(0))
p = "/".join(d)
if p and not self.fs.exists(p):
self.fs.mkdir(p, 0, 0, 4096, f.mode, f.mtime)
def call(self) -> None:
if len(self.args) < 2:
self.write("tar: You must specify one of the `-Acdtrux' options\n")
self.write("Try `tar --help' or `tar --usage' for more information.\n")
return
filename = self.args[1]
extract = False
if "x" in self.args[0]:
extract = True
verbose = False
if "v" in self.args[0]:
verbose = True
path = self.fs.resolve_path(filename, self.protocol.cwd)
if not path or not self.protocol.fs.exists(path):
self.write(f"tar: {filename}: Cannot open: No such file or directory\n")
self.write("tar: Error is not recoverable: exiting now\n")
self.write("tar: Child returned status 2\n")
self.write("tar: Error exit delayed from previous errors\n")
return
hpf = self.fs.getfile(path)
if not hpf[A_REALFILE]:
self.write("tar: this does not look like a tar archive\n")
self.write("tar: skipping to next header\n")
self.write("tar: error exit delayed from previous errors\n")
return
try:
t = tarfile.open(hpf[A_REALFILE])
except Exception:
self.write("tar: this does not look like a tar archive\n")
self.write("tar: skipping to next header\n")
self.write("tar: error exit delayed from previous errors\n")
return
for f in t:
dest = self.fs.resolve_path(f.name.strip("/"), self.protocol.cwd)
if verbose:
self.write(f"{f.name}\n")
if not extract or not len(dest):
continue
if f.isdir():
self.fs.mkdir(dest, 0, 0, 4096, f.mode, f.mtime)
elif f.isfile():
self.mkfullpath(os.path.dirname(dest), f)
self.fs.mkfile(dest, 0, 0, f.size, f.mode, f.mtime)
else:
log.msg(f"tar: skipping [{f.name}]")
commands["/bin/tar"] = Command_tar
commands["tar"] = Command_tar
| 2,737 | 32.802469 | 84 | py |
cowrie | cowrie-master/src/cowrie/commands/groups.py | from __future__ import annotations
import getopt
from cowrie.shell.command import HoneyPotCommand
commands = {}
GROUPS_HELP = """Usage: groups [OPTION]... [USERNAME]...
Print group memberships for each USERNAME or, if no USERNAME is specified, for
the current process (which may differ if the groups database has changed).
--help display this help and exit
--version output version information and exit
GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation at: <https://www.gnu.org/software/coreutils/groups>
or available locally via: info '(coreutils) groups invocation'\n"""
GROUPS_VERSION = """groups (GNU coreutils) 8.30
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by David MacKenzie and James Youngman.\n"""
class Command_groups(HoneyPotCommand):
def call(self):
if len(self.args):
try:
opts, args = getopt.gnu_getopt(
self.args, "hvr:", ["help", "version", "regexp="]
)
except getopt.GetoptError as err:
self.errorWrite(
f"groups: invalid option -- '{err.opt}'\nTry 'groups --help' for more information.\n"
)
return
for vars in opts:
if vars[0] == "-h" or vars[0] == "--help":
self.write(GROUPS_HELP)
return
elif vars[0] == "-v" or vars[0] == "--version":
self.write(GROUPS_VERSION)
return
if len(args) > 0:
file_content = self.fs.file_contents("/etc/group")
self.output(file_content, args[0])
else:
content = self.fs.file_contents("/etc/group")
self.output(content, "")
def output(self, file_content, username):
groups_string = bytes("", encoding="utf-8")
if not username:
username = self.protocol.user.username
else:
if not self.check_valid_user(username):
self.write(f"groups: '{username}': no such user\n")
return
else:
ss = username + " : "
groups_string = bytes(ss, encoding="utf-8")
groups_list = []
lines = file_content.split(b"\n")
usr_string = bytes(username, encoding="utf-8")
for line in lines:
if usr_string in line:
members = line.split(b":")
groups_list.append(members[0])
for g in groups_list:
groups_string += g + b" "
self.writeBytes(groups_string + b"\n")
def check_valid_user(self, username):
usr_byte = bytes(username, encoding="utf-8")
users = self.fs.file_contents("/etc/shadow")
lines = users.split(b"\n")
for line in lines:
usr_arr = line.split(b":")
if usr_arr[0] == usr_byte:
return True
return False
commands["groups"] = Command_groups
commands["/bin/groups"] = Command_groups
| 3,266 | 34.129032 | 105 | py |
cowrie | cowrie-master/src/cowrie/commands/busybox.py | from __future__ import annotations
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.honeypot import StdOutStdErrEmulationProtocol
commands = {}
busybox_help = (
(
"""
BusyBox v1.20.2 (Debian 1:1.20.0-7) multi-call binary.
Copyright (C) 1998-2011 Erik Andersen, Rob Landley, Denys Vlasenko
and others. Licensed under GPLv2.
See source distribution for full notice.
Usage: busybox [function] [arguments]...
or: busybox --list[-full]
or: busybox --install [-s] [DIR]
or: function [arguments]...
BusyBox is a multi-call binary that combines many common Unix
utilities into a single executable. Most people will create a
link to busybox for each function they wish to use and BusyBox
will act like whatever it was invoked as.
Currently defined functions:
[, [[, adjtimex, ar, arp, arping, ash, awk, basename, blockdev, brctl,
bunzip2, bzcat, bzip2, cal, cat, chgrp, chmod, chown, chroot, chvt,
clear, cmp, cp, cpio, cttyhack, cut, date, dc, dd, deallocvt, depmod,
df, diff, dirname, dmesg, dnsdomainname, dos2unix, du, dumpkmap,
dumpleases, echo, egrep, env, expand, expr, false, fgrep, find, fold,
free, freeramdisk, ftpget, ftpput, getopt, getty, grep, groups, gunzip,
gzip, halt, head, hexdump, hostid, hostname, httpd, hwclock, id,
ifconfig, init, insmod, ionice, ip, ipcalc, kill, killall, klogd, last,
less, ln, loadfont, loadkmap, logger, login, logname, logread, losetup,
ls, lsmod, lzcat, lzma, md5sum, mdev, microcom, mkdir, mkfifo, mknod,
mkswap, mktemp, modinfo, modprobe, more, mount, mt, mv, nameif, nc,
netstat, nslookup, od, openvt, patch, pidof, ping, ping6, pivot_root,
poweroff, printf, ps, pwd, rdate, readlink, realpath, reboot, renice,
reset, rev, rm, rmdir, rmmod, route, rpm, rpm2cpio, run-parts, sed, seq,
setkeycodes, setsid, sh, sha1sum, sha256sum, sha512sum, sleep, sort,
start-stop-daemon, stat, strings, stty, swapoff, swapon, switch_root,
sync, sysctl, syslogd, tac, tail, tar, taskset, tee, telnet, test, tftp,
time, timeout, top, touch, tr, traceroute, traceroute6, true, tty,
udhcpc, udhcpd, umount, uname, uncompress, unexpand, uniq, unix2dos,
unlzma, unxz, unzip, uptime, usleep, uudecode, uuencode, vconfig, vi,
watch, watchdog, wc, wget, which, who, whoami, xargs, xz, xzcat, yes,
zcat
"""
)
.strip()
.split("\n")
)
class Command_busybox(HoneyPotCommand):
"""
Fixed by Ivan Korolev (@fe7ch)
The command should never call self.exit(), cause it will corrupt cmdstack
"""
def help(self) -> None:
for ln in busybox_help:
self.errorWrite(f"{ln}\n")
def call(self) -> None:
if len(self.args) == 0:
self.help()
return
line = " ".join(self.args)
cmd = self.args[0]
cmdclass = self.protocol.getCommand(cmd, self.environ["PATH"].split(":"))
if cmdclass:
# log found command
log.msg(
eventid="cowrie.command.success",
input=line,
format="Command found: %(input)s",
)
# prepare command arguments
pp = StdOutStdErrEmulationProtocol(
self.protocol,
cmdclass,
self.protocol.pp.cmdargs[1:],
self.input_data,
None,
)
# insert the command as we do when chaining commands with pipes
self.protocol.pp.insert_command(pp)
# invoke inserted command
self.protocol.pp.outConnectionLost()
# Place this here so it doesn't write out only if last statement
if self.input_data:
self.writeBytes(self.input_data)
else:
self.write(f"{cmd}: applet not found\n")
commands["/bin/busybox"] = Command_busybox
commands["busybox"] = Command_busybox
| 3,963 | 35.703704 | 81 | py |
cowrie | cowrie-master/src/cowrie/commands/crontab.py | # All rights reserved.
# All rights given to Cowrie project
"""
This module contains the crontab commnad
"""
from __future__ import annotations
import getopt
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_crontab(HoneyPotCommand):
def help(self) -> None:
output = (
"usage: crontab [-u user] file",
" crontab [-u user] [-i] {-e | -l | -r}",
" (default operation is replace, per 1003.2)",
" -e (edit user's crontab)",
" -l (list user's crontab)",
" -r (delete user's crontab)",
" -i (prompt before deleting user's crontab)",
)
for line in output:
self.write(line + "\n")
def start(self) -> None:
try:
opts, args = getopt.getopt(self.args, "u:elri")
except getopt.GetoptError as err:
self.write(f"crontab: invalid option -- '{err.opt}'\n")
self.write("crontab: usage error: unrecognized option\n")
self.help()
self.exit()
return
# Parse options
user = self.protocol.user.avatar.username
opt = ""
for o, a in opts:
if o in "-u":
user = a
else:
opt = o
if opt == "-e":
self.write(f"must be privileged to use {opt}\n")
self.exit()
return
elif opt in ["-l", "-r", "-i"]:
self.write(f"no crontab for {user}\n")
self.exit()
return
if len(self.args):
pass
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.command.input",
realm="crontab",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
def handle_CTRL_D(self) -> None:
self.exit()
commands["/usr/bin/crontab"] = Command_crontab
commands["crontab"] = Command_crontab
| 2,134 | 26.025316 | 75 | py |
cowrie | cowrie-master/src/cowrie/commands/chmod.py |
from __future__ import annotations
import getopt
import re
from cowrie.shell.command import HoneyPotCommand
commands = {}
CHMOD_HELP = """Usage: chmod [OPTION]... MODE[,MODE]... FILE...
or: chmod [OPTION]... OCTAL-MODE FILE...
or: chmod [OPTION]... --reference=RFILE FILE...
Change the mode of each FILE to MODE.
With --reference, change the mode of each FILE to that of RFILE.
-c, --changes like verbose but report only when a change is made
-f, --silent, --quiet suppress most error messages
-v, --verbose output a diagnostic for every file processed
--no-preserve-root do not treat '/' specially (the default)
--preserve-root fail to operate recursively on '/'
--reference=RFILE use RFILE's mode instead of MODE values
-R, --recursive change files and directories recursively
--help display this help and exit
--version output version information and exit
Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=][0-7]+'.
GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation at: <https://www.gnu.org/software/coreutils/chmod>
or available locally via: info '(coreutils) chmod invocation'
"""
CHMOD_VERSION = """chmod (GNU coreutils) 8.25
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by David MacKenzie and Jim Meyering.
"""
MODE_REGEX = "^[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=]?[0-7]+$"
TRY_CHMOD_HELP_MSG = "Try 'chmod --help' for more information.\n"
class Command_chmod(HoneyPotCommand):
def call(self) -> None:
# parse the command line arguments
opts, mode, files, getopt_err = self.parse_args()
if getopt_err:
return
# if --help or --version is present, we don't care about the rest
for o in opts:
if o == "--help":
self.write(CHMOD_HELP)
return
if o == "--version":
self.write(CHMOD_VERSION)
return
# check for presence of mode and files in arguments
if (not mode or mode.startswith("-")) and not files:
self.write("chmod: missing operand\n" + TRY_CHMOD_HELP_MSG)
return
if mode and not files:
self.write(f"chmod: missing operand after ‘{mode}’\n" + TRY_CHMOD_HELP_MSG)
return
# mode has to match the regex
if not re.fullmatch(MODE_REGEX, mode):
self.write(f"chmod: invalid mode: ‘{mode}’\n" + TRY_CHMOD_HELP_MSG)
return
# go through the list of files and check whether they exist
for file in files:
if file == "*":
# if the current directory is empty, return 'No such file or directory'
files = self.fs.get_path(self.protocol.cwd)[:]
if not files:
self.write("chmod: cannot access '*': No such file or directory\n")
else:
path = self.fs.resolve_path(file, self.protocol.cwd)
if not self.fs.exists(path):
self.write(
f"chmod: cannot access '{file}': No such file or directory\n"
)
def parse_args(self):
mode = None
# a mode specification starting with '-' would cause the getopt parser to throw an error
# therefore, remove the first such argument self.args before parsing with getopt
args_new = []
for arg in self.args:
if not mode and arg.startswith("-") and re.fullmatch(MODE_REGEX, arg):
mode = arg
else:
args_new.append(arg)
# parse the command line options with getopt
try:
opts, args = getopt.gnu_getopt(
args_new,
"cfvR",
[
"changes",
"silent",
"quiet",
"verbose",
"no-preserve-root",
"preserve-root",
"reference=",
"recursive",
"help",
"version",
],
)
except getopt.GetoptError as err:
failed_opt = err.msg.split(" ")[1]
if failed_opt.startswith("--"):
self.errorWrite(
f"chmod: unrecognized option '--{err.opt}'\n" + TRY_CHMOD_HELP_MSG
)
else:
self.errorWrite(
f"chmod: invalid option -- '{err.opt}'\n" + TRY_CHMOD_HELP_MSG
)
return [], None, [], True
# if mode was not found before, use the first arg as mode
if not mode and len(args) > 0:
mode = args.pop(0)
# the rest of args should be files
files = args
return opts, mode, files, False
commands["/bin/chmod"] = Command_chmod
commands["chmod"] = Command_chmod
| 5,277 | 35.150685 | 96 | py |
cowrie | cowrie-master/src/cowrie/commands/service.py | # All rights reserved.
"""
This module contains the service commnad
"""
from __future__ import annotations
import getopt
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_service(HoneyPotCommand):
"""
By Giannis Papaioannou <giannispapcod7@gmail.com>
"""
def status_all(self) -> None:
"""
more services can be added here.
"""
output = (
"[ + ] acpid",
"[ - ] alsa-utils",
"[ + ] anacron",
"[ + ] apparmor",
"[ + ] apport",
"[ + ] avahi-daemon",
"[ + ] bluetooth",
"[ - ] bootmisc.sh",
"[ - ] brltty",
"[ - ] checkfs.sh",
"[ - ] checkroot-bootclean.sh",
"[ - ] checkroot.sh",
"[ + ] console-setup",
"[ + ] cron",
"[ + ] cups",
"[ + ] cups-browsed",
"[ + ] dbus",
"[ - ] dns-clean",
"[ + ] grub-common",
"[ - ] hostname.sh",
"[ - ] hwclock.sh",
"[ + ] irqbalance",
"[ - ] kerneloops",
"[ - ] killprocs",
"[ + ] kmod",
"[ + ] lightdm",
"[ - ] mountall-bootclean.sh",
"[ - ] mountall.sh",
"[ - ] mountdevsubfs.sh",
"[ - ] mountkernfs.sh",
"[ - ] mountnfs-bootclean.sh",
"[ - ] mountnfs.sh",
"[ + ] network-manager",
"[ + ] networking",
"[ + ] ondemand",
"[ + ] open-vm-tools",
"[ - ] plymouth",
"[ - ] plymouth-log",
"[ - ] pppd-dns",
"[ + ] procps",
"[ - ] rc.local",
"[ + ] resolvconf",
"[ - ] rsync",
"[ + ] rsyslog",
"[ - ] saned",
"[ - ] sendsigs",
"[ + ] speech-dispatcher",
"[ + ] thermald",
"[ + ] udev",
"[ + ] ufw",
"[ - ] umountfs",
"[ - ] umountnfs.sh",
"[ - ] umountroot",
"[ - ] unattended-upgrades",
"[ + ] urandom",
"[ - ] uuidd",
"[ + ] whoopsie",
"[ - ] x11-common",
)
for line in output:
self.write(line + "\n")
def help(self) -> None:
output = "Usage: service < option > | --status-all | [ service_name [ command | --full-restart ] ]"
self.write(output + "\n")
def call(self) -> None:
try:
opts, args = getopt.gnu_getopt(
self.args, "h", ["help", "status-all", "full-restart"]
)
except getopt.GetoptError:
self.help()
return
if not opts and not args:
self.help()
return
for o, _a in opts:
if o in ("--help") or o in ("-h"):
self.help()
return
elif o in ("--status-all"):
self.status_all()
"""
Ubuntu shows no response when stopping, starting
leviathan@ubuntu:~$ sudo service ufw stop
leviathan@ubuntu:~$ sudo service ufw start
leviathan@ubuntu:~$
"""
commands["/usr/sbin/service"] = Command_service
commands["service"] = Command_service
| 3,449 | 27.278689 | 107 | py |
cowrie | cowrie-master/src/cowrie/commands/tftp.py | from __future__ import annotations
import tftpy
from tftpy.TftpPacketTypes import TftpPacketDAT, TftpPacketOACK
from twisted.python import log
from cowrie.core.artifact import Artifact
from cowrie.core.config import CowrieConfig
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.customparser import CustomParser
commands = {}
class Progress:
def __init__(self, protocol):
self.progress = 0
self.out = protocol
def progresshook(self, pkt):
if isinstance(pkt, TftpPacketDAT):
self.progress += len(pkt.data)
self.out.write(f"Transferred {self.progress} bytes\n")
elif isinstance(pkt, TftpPacketOACK):
self.out.write(f"Received OACK, options are: {pkt.options}\n")
class Command_tftp(HoneyPotCommand):
port = 69
hostname = None
file_to_get: str
limit_size = CowrieConfig.getint("honeypot", "download_limit_size", fallback=0)
def makeTftpRetrieval(self) -> None:
progresshook = Progress(self).progresshook
self.artifactFile = Artifact(self.file_to_get)
tclient = None
url = ""
try:
tclient = tftpy.TftpClient(self.hostname, int(self.port))
# tftpy can't handle unicode string as filename
# so we have to convert unicode type to str type
tclient.download(str(self.file_to_get), self.artifactFile, progresshook)
url = "tftp://{}/{}".format(self.hostname, self.file_to_get.strip("/"))
self.file_to_get = self.fs.resolve_path(self.file_to_get, self.protocol.cwd)
if hasattr(tclient.context, "metrics"):
self.fs.mkfile(
self.file_to_get, 0, 0, tclient.context.metrics.bytes, 33188
)
else:
self.fs.mkfile(self.file_to_get, 0, 0, 0, 33188)
except tftpy.TftpException:
if tclient and tclient.context and not tclient.context.fileobj.closed:
tclient.context.fileobj.close()
self.artifactFile.close()
if url:
# log to cowrie.log
log.msg(
format="Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s",
url=url,
outfile=self.artifactFile.shasumFilename,
shasum=self.artifactFile.shasum,
)
self.protocol.logDispatch(
eventid="cowrie.session.file_download",
format="Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s",
url=url,
outfile=self.artifactFile.shasumFilename,
shasum=self.artifactFile.shasum,
destfile=self.file_to_get,
)
# Update the honeyfs to point to downloaded file
self.fs.update_realfile(
self.fs.getfile(self.file_to_get), self.artifactFile.shasumFilename
)
self.fs.chown(
self.file_to_get, self.protocol.user.uid, self.protocol.user.gid
)
def start(self) -> None:
parser = CustomParser(self)
parser.prog = "tftp"
parser.add_argument("hostname", nargs="?", default=None)
parser.add_argument("-c", nargs=2)
parser.add_argument("-l")
parser.add_argument("-g")
parser.add_argument("-p")
parser.add_argument("-r")
args = parser.parse_args(self.args)
if args.c:
if len(args.c) > 1:
self.file_to_get = args.c[1]
if args.hostname is None:
self.exit()
return
self.hostname = args.hostname
elif args.r:
self.file_to_get = args.r
self.hostname = args.g
else:
self.write(
"usage: tftp [-h] [-c C C] [-l L] [-g G] [-p P] [-r R] [hostname]\n"
)
self.exit()
return
if self.hostname is None:
self.exit()
return
if self.hostname.find(":") != -1:
host, port = self.hostname.split(":")
self.hostname = host
self.port = int(port)
self.makeTftpRetrieval()
self.exit()
commands["/usr/bin/tftp"] = Command_tftp
commands["tftp"] = Command_tftp
| 4,332 | 31.096296 | 89 | py |
cowrie | cowrie-master/src/cowrie/commands/unzip.py |
from __future__ import annotations
import os
import zipfile
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.fs import A_REALFILE
commands = {}
class Command_unzip(HoneyPotCommand):
def mkfullpath(self, path: str) -> None:
components, d = path.split("/"), []
while len(components):
d.append(components.pop(0))
dir = "/" + "/".join(d)
if not self.fs.exists(dir):
self.fs.mkdir(dir, 0, 0, 4096, 33188)
def call(self) -> None:
if len(self.args) == 0 or self.args[0].startswith("-"):
output = (
"UnZip 6.00 of 20 April 2009, by Debian. Original by Info-ZIP.\n"
"\n"
"Usage: unzip [-Z] [-opts[modifiers]] file[.zip] [list] [-x xlist] [-d exdir]\n"
" Default action is to extract files in list, except those in xlist, to exdir;\n"
' file[.zip] may be a wildcard. -Z => ZipInfo mode ("unzip -Z" for usage).\n'
"\n"
" -p extract files to pipe, no messages -l list files (short format)\n"
" -f freshen existing files, create none -t test compressed archive data\n"
" -u update files, create if necessary -z display archive comment only\n"
" -v list verbosely/show version info -T timestamp archive to latest\n"
" -x exclude files that follow (in xlist) -d extract files into exdir\n"
"modifiers:\n"
" -n never overwrite existing files -q quiet mode (-qq => quieter)\n"
" -o overwrite files WITHOUT prompting -a auto-convert any text files\n"
" -j junk paths (do not make directories) -aa treat ALL files as text\n"
" -U use escapes for all non-ASCII Unicode -UU ignore any Unicode fields\n"
" -C match filenames case-insensitively -L make (some) names lowercase\n"
" -X restore UID/GID info -V retain VMS version numbers\n"
' -K keep setuid/setgid/tacky permissions -M pipe through "more" pager\n'
'See "unzip -hh" or unzip.txt for more help. Examples:\n'
" unzip data1 -x joe => extract all files except joe from zipfile data1.zip\n"
" unzip -p foo | more => send contents of foo.zip via pipe into program more\n"
" unzip -fo foo ReadMe => quietly replace existing ReadMe if archive file newer\n"
)
self.write(output)
return
filename = self.args[0]
path = self.fs.resolve_path(filename, self.protocol.cwd)
if not path:
self.write(
f"unzip: cannot find or open {filename}, {filename}.zip or {filename}.ZIP.\n"
)
return
if not self.protocol.fs.exists(path):
if not self.protocol.fs.exists(path + ".zip"):
self.write(
f"unzip: cannot find or open {filename}, {filename}.zip or {filename}.ZIP.\n"
)
return
else:
path = path + ".zip"
f = self.fs.getfile(path)
if not f[A_REALFILE]:
output = (
" End-of-central-directory signature not found. Either this file is not\n"
" a zipfile, or it constitutes one disk of a multi-part archive. In the\n"
" latter case the central directory and zipfile comment will be found on\n"
" the last disk(s) of this archive.\n"
)
self.write(output)
self.write(
f"unzip: cannot find or open {filename}, {filename}.zip or {filename}.ZIP.\n"
)
return
try:
t = zipfile.ZipFile(f[A_REALFILE]).infolist()
except Exception:
output = (
" End-of-central-directory signature not found. Either this file is not\n"
" a zipfile, or it constitutes one disk of a multi-part archive. In the\n"
" latter case the central directory and zipfile comment will be found on\n"
" the last disk(s) of this archive.\n"
)
self.write(output)
self.write(
f"unzip: cannot find or open {filename}, {filename}.zip or {filename}.ZIP.\n"
)
return
self.write(f"Archive: {filename}\n")
for f in t:
dest = self.fs.resolve_path(f.filename.strip("/"), self.protocol.cwd)
self.write(f" inflating: {f.filename}\n")
if not len(dest):
continue
if f.is_dir():
self.fs.mkdir(dest, 0, 0, 4096, 33188)
elif not f.is_dir():
self.mkfullpath(os.path.dirname(dest))
self.fs.mkfile(dest, 0, 0, f.file_size, 33188)
else:
log.msg(f" skipping: {f.filename}\n")
commands["/bin/unzip"] = Command_unzip
commands["unzip"] = Command_unzip
| 5,357 | 44.02521 | 99 | py |
cowrie | cowrie-master/src/cowrie/commands/wget.py |
from __future__ import annotations
import getopt
import ipaddress
import os
import time
from typing import Any, Optional
from twisted.internet import error
from twisted.python import compat, log
from twisted.web.iweb import UNKNOWN_LENGTH
import treq
from cowrie.core.artifact import Artifact
from cowrie.core.config import CowrieConfig
from cowrie.shell.command import HoneyPotCommand
commands = {}
def tdiff(seconds: int) -> str:
t = seconds
days = int(t / (24 * 60 * 60))
t -= days * 24 * 60 * 60
hours = int(t / (60 * 60))
t -= hours * 60 * 60
minutes = int(t / 60)
t -= minutes * 60
s = "%ds" % (int(t),)
if minutes >= 1:
s = f"{minutes}m {s}"
if hours >= 1:
s = f"{hours}h {s}"
if days >= 1:
s = f"{days}d {s}"
return s
def sizeof_fmt(num: float) -> str:
for x in ["bytes", "K", "M", "G", "T"]:
if num < 1024.0:
return f"{num}{x}"
num /= 1024.0
raise Exception
def splitthousands(s: str, sep: str = ",") -> str:
if len(s) <= 3:
return s
return splitthousands(s[:-3], sep) + sep + s[-3:]
class Command_wget(HoneyPotCommand):
"""
wget command
"""
limit_size: int = CowrieConfig.getint("honeypot", "download_limit_size", fallback=0)
quiet: bool = False
outfile: Optional[str] = None # outfile is the file saved inside the honeypot
artifact: Artifact # artifact is the file saved for forensics in the real file system
currentlength: int = 0 # partial size during download
totallength: int = 0 # total length
proglen: int = 0
url: bytes
host: str
started: float
def start(self) -> None:
url: str
try:
optlist, args = getopt.getopt(self.args, "cqO:P:", ["header="])
except getopt.GetoptError:
self.errorWrite("Unrecognized option\n")
self.exit()
return
if len(args):
url = args[0].strip()
else:
self.errorWrite("wget: missing URL\n")
self.errorWrite("Usage: wget [OPTION]... [URL]...\n\n")
self.errorWrite("Try `wget --help' for more options.\n")
self.exit()
return
self.outfile = None
self.quiet = False
for opt in optlist:
if opt[0] == "-O":
self.outfile = opt[1]
if opt[0] == "-q":
self.quiet = True
# for some reason getopt doesn't recognize "-O -"
# use try..except for the case if passed command is malformed
try:
if not self.outfile:
if "-O" in args:
self.outfile = args[args.index("-O") + 1]
except Exception:
pass
if "://" not in url:
url = f"http://{url}"
urldata = compat.urllib_parse.urlparse(url)
if urldata.hostname:
self.host = urldata.hostname
else:
pass
# TODO: need to do full name resolution in case someon passes DNS name pointing to local address
try:
if ipaddress.ip_address(self.host).is_private:
self.errorWrite(f"curl: (6) Could not resolve host: {self.host}\n")
self.exit()
return None
except ValueError:
pass
self.url = url.encode("utf8")
if self.outfile is None:
self.outfile = urldata.path.split("/")[-1]
if not len(self.outfile.strip()) or not urldata.path.count("/"):
self.outfile = "index.html"
if self.outfile != "-":
self.outfile = self.fs.resolve_path(self.outfile, self.protocol.cwd)
path = os.path.dirname(self.outfile) # type: ignore
if not path or not self.fs.exists(path) or not self.fs.isdir(path):
self.errorWrite(
"wget: {}: Cannot open: No such file or directory\n".format(
self.outfile
)
)
self.exit()
return
self.artifact = Artifact("curl-download")
if not self.quiet:
tm = time.strftime("%Y-%m-%d %H:%M:%S")
self.errorWrite(f"--{tm}-- {url}\n")
self.errorWrite(f"Connecting to {self.host}:{urldata.port}... connected.\n")
self.errorWrite("HTTP request sent, awaiting response... ")
self.deferred = self.wgetDownload(url)
if self.deferred:
self.deferred.addCallback(self.success)
self.deferred.addErrback(self.error)
def wgetDownload(self, url: str) -> Any:
"""
Download `url`
"""
headers = {"User-Agent": ["curl/7.38.0"]}
# TODO: use designated outbound interface
# out_addr = None
# if CowrieConfig.has_option("honeypot", "out_addr"):
# out_addr = (CowrieConfig.get("honeypot", "out_addr"), 0)
deferred = treq.get(url=url, allow_redirects=True, headers=headers, timeout=10)
return deferred
def handle_CTRL_C(self) -> None:
self.write("^C\n")
self.exit()
def success(self, response):
"""
successful treq get
"""
# TODO possible this is UNKNOWN_LENGTH
if response.length != UNKNOWN_LENGTH:
self.totallength = response.length
else:
self.totallength = 0
if self.limit_size > 0 and self.totallength > self.limit_size:
log.msg(
f"Not saving URL ({self.url.decode()}) (size: {self.totallength}) exceeds file size limit ({self.limit_size})"
)
self.exit()
return
self.started = time.time()
if not self.quiet:
self.errorWrite("200 OK\n")
if response.headers.hasHeader(b"content-type"):
self.contenttype = response.headers.getRawHeaders(b"content-type")[
0
].decode()
else:
self.contenttype = "text/whatever"
if not self.quiet:
if response.length != UNKNOWN_LENGTH:
self.errorWrite(
f"Length: {self.totallength} ({sizeof_fmt(self.totallength)}) [{self.contenttype}]\n"
)
else:
self.errorWrite(f"Length: unspecified [{self.contenttype}]\n")
if self.outfile is None:
self.errorWrite("Saving to: `STDOUT'\n\n")
else:
self.errorWrite(f"Saving to: `{self.outfile}'\n\n")
deferred = treq.collect(response, self.collect)
deferred.addCallback(self.collectioncomplete)
return deferred
def collect(self, data: bytes) -> None:
"""
partial collect
"""
eta: float
self.currentlength += len(data)
if self.limit_size > 0 and self.currentlength > self.limit_size:
log.msg(
f"Not saving URL ({self.url.decode()}) (size: {self.currentlength}) exceeds file size limit ({self.limit_size})"
)
self.exit()
return
self.artifact.write(data)
self.speed = self.currentlength / (time.time() - self.started)
if self.totallength != 0:
percent = int(self.currentlength / self.totallength * 100)
spercent = f"{percent}%"
eta = (self.totallength - self.currentlength) / self.speed
else:
spercent = f"{self.currentlength / 1000}K"
percent = 0
eta = 0.0
s = "\r%s [%s] %s %dK/s eta %s" % (
spercent.rjust(3),
("%s>" % (int(39.0 / 100.0 * percent) * "=")).ljust(39),
splitthousands(str(int(self.currentlength))).ljust(12),
self.speed / 1000,
tdiff(int(eta)),
)
if not self.quiet:
self.errorWrite(s.ljust(self.proglen))
self.proglen = len(s)
self.lastupdate = time.time()
if not self.outfile:
self.writeBytes(data)
def collectioncomplete(self, data: None) -> None:
"""
this gets called once collection is complete
"""
self.artifact.close()
self.totallength = self.currentlength
if not self.quiet:
self.errorWrite(
"\r100%%[%s] %s %dK/s"
% (
"%s>" % (38 * "="),
splitthousands(str(int(self.totallength))).ljust(12),
self.speed / 1000,
)
)
self.errorWrite("\n\n")
self.errorWrite(
"%s (%d KB/s) - `%s' saved [%d/%d]\n\n"
% (
time.strftime("%Y-%m-%d %H:%M:%S"),
self.speed / 1000,
self.outfile,
self.currentlength,
self.totallength,
)
)
# Update the honeyfs to point to artifact file if output is to file
if self.outfile:
self.fs.mkfile(self.outfile, 0, 0, self.currentlength, 33188)
self.fs.chown(self.outfile, self.protocol.user.uid, self.protocol.user.gid)
self.fs.update_realfile(
self.fs.getfile(self.outfile), self.artifact.shasumFilename
)
self.protocol.logDispatch(
eventid="cowrie.session.file_download",
format="Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s",
url=self.url.decode(),
outfile=self.artifact.shasumFilename,
shasum=self.artifact.shasum,
)
log.msg(
eventid="cowrie.session.file_download",
format="Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s",
url=self.url.decode(),
outfile=self.artifact.shasumFilename,
shasum=self.artifact.shasum,
)
self.exit()
def error(self, response):
"""
handle errors
"""
if response.check(error.DNSLookupError) is not None:
self.write(
f"Resolving no.such ({self.host})... failed: nodename nor servname provided, or not known.\n"
)
self.write(f"wget: unable to resolve host address ‘{self.host}’\n")
self.exit()
return
log.err(response)
log.msg(response.printTraceback())
if hasattr(response, "getErrorMessage"): # Exceptions
errormsg = response.getErrorMessage()
log.msg(errormsg)
self.write("\n")
self.protocol.logDispatch(
eventid="cowrie.session.file_download.failed",
format="Attempt to download file(s) from URL (%(url)s) failed",
url=self.url.decode(),
)
self.exit()
commands["/usr/bin/wget"] = Command_wget
commands["wget"] = Command_wget
commands["/usr/bin/dget"] = Command_wget
commands["dget"] = Command_wget
| 11,157 | 30.971347 | 128 | py |
cowrie | cowrie-master/src/cowrie/commands/tee.py | """
tee command
"""
from __future__ import annotations
import getopt
import os
from typing import Optional
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.fs import FileNotFound
commands = {}
class Command_tee(HoneyPotCommand):
"""
tee command
"""
append = False
teeFiles: list[str] = []
writtenBytes = 0
ignoreInterupts = False
def start(self) -> None:
try:
optlist, args = getopt.gnu_getopt(
self.args, "aip", ["help", "append", "version"]
)
except getopt.GetoptError as err:
self.errorWrite(
f"tee: invalid option -- '{err.opt}'\nTry 'tee --help' for more information.\n"
)
self.exit()
return
for o, _a in optlist:
if o in ("--help"):
self.help()
self.exit()
return
elif o in ("-a", "--append"):
self.append = True
elif o in ("-a", "--ignore-interrupts"):
self.ignoreInterupts = True
for arg in args:
pname = self.fs.resolve_path(arg, self.protocol.cwd)
if self.fs.isdir(pname):
self.errorWrite(f"tee: {arg}: Is a directory\n")
continue
try:
pname = self.fs.resolve_path(arg, self.protocol.cwd)
folder_path = os.path.dirname(pname)
if not self.fs.exists(folder_path) or not self.fs.isdir(folder_path):
raise FileNotFound
self.teeFiles.append(pname)
self.fs.mkfile(pname, 0, 0, 0, 0o644)
except FileNotFound:
self.errorWrite(f"tee: {arg}: No such file or directory\n")
if self.input_data:
self.output(self.input_data)
self.exit()
def write_to_file(self, data: bytes) -> None:
self.writtenBytes += len(data)
for outf in self.teeFiles:
self.fs.update_size(outf, self.writtenBytes)
def output(self, inb: Optional[bytes]) -> None:
"""
This is the tee output, if no file supplied
"""
if inb:
inp = inb.decode("utf-8")
else:
return
lines = inp.split("\n")
if lines[-1] == "":
lines.pop()
for line in lines:
self.write(line + "\n")
self.write_to_file(line.encode("utf-8") + b"\n")
def lineReceived(self, line: str) -> None:
"""
This function logs standard input from the user send to tee
"""
log.msg(
eventid="cowrie.session.input",
realm="tee",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
self.output(line.encode("utf-8"))
def handle_CTRL_C(self) -> None:
if not self.ignoreInterupts:
log.msg("Received CTRL-C, exiting..")
self.write("^C\n")
self.exit()
def handle_CTRL_D(self) -> None:
"""
ctrl-d is end-of-file, time to terminate
"""
self.exit()
def help(self) -> None:
self.write(
"""Usage: tee [OPTION]... [FILE]...
Copy standard input to each FILE, and also to standard output.
-a, --append append to the given FILEs, do not overwrite
-i, --ignore-interrupts ignore interrupt signals
-p diagnose errors writing to non pipes
--output-error[=MODE] set behavior on write error. See MODE below
--help display this help and exit
--version output version information and exit
MODE determines behavior with write errors on the outputs:
'warn' diagnose errors writing to any output
'warn-nopipe' diagnose errors writing to any output not a pipe
'exit' exit on error writing to any output
'exit-nopipe' exit on error writing to any output not a pipe
The default MODE for the -p option is 'warn-nopipe'.
The default operation when --output-error is not specified, is to
exit immediately on error writing to a pipe, and diagnose errors
writing to non pipe outputs.
GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation <https://www.gnu.org/software/coreutils/tee>
or available locally via: info '(coreutils) tee invocation'
"""
)
commands["/bin/tee"] = Command_tee
commands["tee"] = Command_tee
| 4,597 | 28.474359 | 95 | py |
cowrie | cowrie-master/src/cowrie/commands/last.py |
from __future__ import annotations
import time
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_last(HoneyPotCommand):
def call(self) -> None:
line = list(self.args)
while len(line):
arg = line.pop(0)
if not arg.startswith("-"):
continue
elif arg == "-n" and len(line) and line[0].isdigit():
line.pop(0)
self.write(
"%-8s %-12s %-16s %s still logged in\n"
% (
self.protocol.user.username,
"pts/0",
self.protocol.clientIP,
time.strftime(
"%a %b %d %H:%M", time.localtime(self.protocol.logintime)
),
)
)
self.write("\n")
self.write(
"wtmp begins {}\n".format(
time.strftime(
"%a %b %d %H:%M:%S %Y",
time.localtime(
self.protocol.logintime // (3600 * 24) * (3600 * 24) + 63
),
)
)
)
commands["/usr/bin/last"] = Command_last
commands["last"] = Command_last
| 1,299 | 24.490196 | 81 | py |
cowrie | cowrie-master/src/cowrie/commands/du.py |
from __future__ import annotations
import os
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.fs import A_NAME
commands = {}
class Command_du(HoneyPotCommand):
def message_help(self) -> str:
return """Usage: du [OPTION]... [FILE]...
or: du [OPTION]... --files0-from=F
Summarize disk usage of the set of FILEs, recursively for directories.
Mandatory arguments to long options are mandatory for short options too.
-0, --null end each output line with NUL, not newline
-a, --all write counts for all files, not just directories
--apparent-size print apparent sizes, rather than disk usage; although
the apparent size is usually smaller, it may be
larger due to holes in ('sparse') files, internal
fragmentation, indirect blocks, and the like
-B, --block-size=SIZE scale sizes by SIZE before printing them; e.g.,
'-BM' prints sizes in units of 1,048,576 bytes;
see SIZE format below
-b, --bytes equivalent to '--apparent-size --block-size=1'
-c, --total produce a grand total
-D, --dereference-args dereference only symlinks that are listed on the
command line
-d, --max-depth=N print the total for a directory (or file, with --all)
only if it is N or fewer levels below the command
line argument; --max-depth=0 is the same as
--summarize
--files0-from=F summarize disk usage of the
NUL-terminated file names specified in file F;
if F is -, then read names from standard input
-H equivalent to --dereference-args (-D)
-h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)
--inodes list inode usage information instead of block usage
-k like --block-size=1K
-L, --dereference dereference all symbolic links
-l, --count-links count sizes many times if hard linked
-m like --block-size=1M
-P, --no-dereference don't follow any symbolic links (this is the default)
-S, --separate-dirs for directories do not include size of subdirectories
--si like -h, but use powers of 1000 not 1024
-s, --summarize display only a total for each argument
-t, --threshold=SIZE exclude entries smaller than SIZE if positive,
or entries greater than SIZE if negative
--time show time of the last modification of any file in the
directory, or any of its subdirectories
--time=WORD show time as WORD instead of modification time:
atime, access, use, ctime or status
--time-style=STYLE show times using STYLE, which can be:
full-iso, long-iso, iso, or +FORMAT;
FORMAT is interpreted like in 'date'
-X, --exclude-from=FILE exclude files that match any pattern in FILE
--exclude=PATTERN exclude files that match PATTERN
-x, --one-file-system skip directories on different file systems
--help display this help and exit
--version output version information and exit
Display values are in units of the first available SIZE from --block-size,
and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables.
Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set).
The SIZE argument is an integer and optional unit (example: 10K is 10*1024).
Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers of 1000).
GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
Report du translation bugs to <http://translationproject.org/team/>
Full documentation at: <http://www.gnu.org/software/coreutils/du>
or available locally via: info '(coreutils) du invocation'\n"""
def call(self) -> None:
self.showHidden = False
self.showDirectories = False
path = self.protocol.cwd
args = self.args
if args:
if "-sh" == args[0]:
self.write("28K .\n")
elif "--help" == args[0]:
self.write(self.message_help())
else:
self.du_show(path)
else:
self.du_show(path, all=True)
def du_show(self, path: str, all: bool = False) -> None:
try:
if self.protocol.fs.isdir(path) and not self.showDirectories:
files = self.protocol.fs.get_path(path)[:]
if self.showHidden:
dot = self.protocol.fs.getfile(path)[:]
dot[A_NAME] = "."
files.append(dot)
# FIXME: should grab dotdot off the parent instead
dotdot = self.protocol.fs.getfile(path)[:]
dotdot[A_NAME] = ".."
files.append(dotdot)
else:
files = [x for x in files if not x[A_NAME].startswith(".")]
files.sort()
else:
files = (self.protocol.fs.getfile(path)[:],)
except Exception:
self.write(f"ls: cannot access {path}: No such file or directory\n")
return
filenames = [x[A_NAME] for x in files]
if not filenames:
return
for filename in filenames:
if all:
isdir = self.protocol.fs.isdir(os.path.join(path, filename))
if isdir:
filename = f"4 ./{filename}\n"
self.write(filename)
else:
filename = f"4 {filename}\n"
self.write(filename)
if all:
self.write("36 .\n")
commands["du"] = Command_du
| 6,062 | 44.931818 | 80 | py |
cowrie | cowrie-master/src/cowrie/commands/dd.py |
"""
dd commands
"""
from __future__ import annotations
import re
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
from cowrie.shell.fs import FileNotFound
commands = {}
class Command_dd(HoneyPotCommand):
"""
dd command
"""
ddargs: dict[str, str] = {}
def start(self) -> None:
if not self.args or self.args[0] == ">":
return
for arg in self.args:
if arg.find("=") == -1:
self.write(f"unknown operand: {arg}")
HoneyPotCommand.exit(self)
operand, value = arg.split("=")
if operand not in ("if", "bs", "of", "count"):
self.write(f"unknown operand: {operand}")
self.exit(success=False)
self.ddargs[operand] = value
if self.input_data:
self.writeBytes(self.input_data)
else:
bSuccess = True
c = -1
block = 512
if "if" in self.ddargs:
iname = self.ddargs["if"]
pname = self.fs.resolve_path(iname, self.protocol.cwd)
if self.fs.isdir(pname):
self.errorWrite(f"dd: {iname}: Is a directory\n")
bSuccess = False
if bSuccess:
if "bs" in self.ddargs:
block = parse_size(self.ddargs["bs"])
if block <= 0:
self.errorWrite(f"dd: invalid number '{block}'\n")
bSuccess = False
if bSuccess:
if "count" in self.ddargs:
c = int(self.ddargs["count"])
if c < 0:
self.errorWrite(f"dd: invalid number '{c}'\n")
bSuccess = False
if bSuccess:
try:
contents = self.fs.file_contents(pname)
if c == -1:
self.writeBytes(contents)
else:
tsize = block * c
data = contents
if len(data) > tsize:
self.writeBytes(data[:tsize])
else:
self.writeBytes(data)
except FileNotFound:
self.errorWrite(f"dd: {iname}: No such file or directory\n")
bSuccess = False
self.exit(success=bSuccess)
def exit(self, success: bool = True) -> None:
if success is True:
self.write("0+0 records in\n")
self.write("0+0 records out\n")
self.write("0 bytes transferred in 0.695821 secs (0 bytes/sec)\n")
HoneyPotCommand.exit(self)
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.session.input",
realm="dd",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
def handle_CTRL_D(self) -> None:
self.exit()
def parse_size(param: str) -> int:
"""
Parse dd arguments that indicate block sizes
Return 0 in case of illegal input
"""
pattern = r"^(\d+)(c|w|b|kB|K|MB|M|xM|GB|G|T|TB|P|PB|E|EB|Z|ZB|Y|YB)?$"
z = re.search(pattern, param)
if not z:
return 0
digits = int(z.group(1))
letters = z.group(2)
if not letters:
multiplier = 1
elif letters == "c":
multiplier = 1
elif letters == "w":
multiplier = 2
elif letters == "b":
multiplier = 512
elif letters == "kB":
multiplier = 1000
elif letters == "K":
multiplier = 1024
elif letters == "MB":
multiplier = 1000 * 1000
elif letters == "M" or letters == "xM":
multiplier = 1024 * 1024
elif letters == "GB":
multiplier = 1000 * 1000 * 1000
elif letters == "G":
multiplier = 1024 * 1024 * 1024
else:
multiplier = 1
return digits * multiplier
commands["/bin/dd"] = Command_dd
commands["dd"] = Command_dd
| 4,279 | 28.517241 | 84 | py |
cowrie | cowrie-master/src/cowrie/commands/uname.py |
"""
uname command
"""
from __future__ import annotations
from cowrie.core.config import CowrieConfig
from cowrie.shell.command import HoneyPotCommand
commands = {}
def hardware_platform() -> str:
return CowrieConfig.get("shell", "hardware_platform", fallback="x86_64")
def kernel_name() -> str:
return CowrieConfig.get("shell", "kernel_name", fallback="Linux")
def kernel_version() -> str:
return CowrieConfig.get("shell", "kernel_version", fallback="3.2.0-4-amd64")
def kernel_build_string() -> str:
return CowrieConfig.get(
"shell", "kernel_build_string", fallback="#1 SMP Debian 3.2.68-1+deb7u1"
)
def operating_system() -> str:
return CowrieConfig.get("shell", "operating_system", fallback="GNU/Linux")
def uname_help() -> str:
return """Usage: uname [OPTION]...
Print certain system information. With no OPTION, same as -s.
-a, --all print all information, in the following order,
except omit -p and -i if unknown:
-s, --kernel-name print the kernel name
-n, --nodename print the network node hostname
-r, --kernel-release print the kernel release
-v, --kernel-version print the kernel version
-m, --machine print the machine hardware name
-p, --processor print the processor type (non-portable)
-i, --hardware-platform print the hardware platform (non-portable)
-o, --operating-system print the operating system
--help display this help and exit
--version output version information and exit
GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
Full documentation at: <http://www.gnu.org/software/coreutils/uname>
or available locally via: info '(coreutils) uname invocation'\n
"""
def uname_get_some_help() -> str:
return "Try 'uname --help' for more information."
def uname_fail_long(arg: str) -> str:
return f"uname: unrecognized option '{arg}'\n{uname_get_some_help()}\n"
def uname_fail_short(arg: str) -> str:
return f"uname: invalid option -- '{arg}'\n{uname_get_some_help()}\n"
def uname_fail_extra(arg: str) -> str:
# Note: These are apostrophes, not single quotation marks.
return f"uname: extra operand ‘{arg}’\n{uname_get_some_help()}\n"
class Command_uname(HoneyPotCommand):
def full_uname(self) -> str:
return "{} {} {} {} {} {}\n".format(
kernel_name(),
self.protocol.hostname,
kernel_version(),
kernel_build_string(),
hardware_platform(),
operating_system(),
)
def call(self) -> None:
opts = {
"name": False,
"release": False,
"version": False,
"os": False,
"node": False,
"machine": False,
}
flags = [
(["a", "all"], "__ALL__"),
(["s", "kernel-name"], "name"),
(["r", "kernel-release"], "release"),
(["v", "kernel-version"], "version"),
(["o", "operating-system"], "os"),
(["n", "nodename"], "node"),
(["m", "machine", "p", "processor", "i", "hardware-platform"], "machine"),
]
if not self.args:
# IF no params output default
self.write(f"{kernel_name()}\n")
return
# getopt-style parsing
for a in self.args:
a = a.strip()
arg_block = []
was_long = False
if a == "--help":
# Help overrides invalid args following --help
# There's no -h, invalid args before --help still fail.
self.write(uname_help())
return
elif a.startswith("--"):
# arg name w/o --
was_long = True
arg_block.append(a[2:])
elif a.startswith("-"):
# letter by letter
a = a[1:]
if len(a) == 0:
self.write(uname_fail_extra("-"))
return
for split_arg in a:
arg_block.append(split_arg)
else:
self.write(uname_fail_extra(a))
return
for arg in arg_block:
arg_parsed = False
# Find a possible flag for each arg.
for possible_args, target_opt in flags:
if arg not in possible_args:
continue
arg_parsed = True # Got a hit!
# Set all opts for -a/--all, single opt otherwise:
if target_opt == "__ALL__":
for key in opts.keys():
opts[key] = True
else:
opts[target_opt] = True
break # Next arg please
if not arg_parsed:
self.write(
uname_fail_long(a) if was_long else uname_fail_short(arg)
)
return
# All the options set, let's get the output
output = []
if opts["name"]:
output.append(kernel_name())
if opts["node"]:
output.append(self.protocol.hostname)
if opts["release"]:
output.append(kernel_version())
if opts["version"]:
output.append(kernel_build_string())
if opts["machine"]:
output.append(hardware_platform())
if opts["os"]:
output.append(operating_system())
if len(output) < 1:
output.append(kernel_name())
self.write(" ".join(output) + "\n")
commands["/bin/uname"] = Command_uname
commands["uname"] = Command_uname
| 5,891 | 29.848168 | 86 | py |
cowrie | cowrie-master/src/cowrie/commands/nohup.py |
from __future__ import annotations
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_nohup(HoneyPotCommand):
def call(self) -> None:
if not len(self.args):
self.write("nohup: missing operand\n")
self.write("Try `nohup --help' for more information.\n")
return
path = self.fs.resolve_path("nohup.out", self.protocol.cwd)
if self.fs.exists(path):
return
self.fs.mkfile(path, 0, 0, 0, 33188)
self.write("nohup: ignoring input and appending output to 'nohup.out'\n")
commands["/usr/bin/nohup"] = Command_nohup
commands["nohup"] = Command_nohup
| 769 | 27.518519 | 81 | py |
cowrie | cowrie-master/src/cowrie/commands/uptime.py |
from __future__ import annotations
import time
from cowrie.core import utils
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_uptime(HoneyPotCommand):
def call(self) -> None:
self.write(
"{} up {}, 1 user, load average: 0.00, 0.00, 0.00\n".format(time.strftime("%H:%M:%S"), utils.uptime(self.protocol.uptime()))
)
commands["/usr/bin/uptime"] = Command_uptime
commands["uptime"] = Command_uptime
| 567 | 23.695652 | 139 | py |
cowrie | cowrie-master/src/cowrie/commands/ethtool.py |
from __future__ import annotations
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_ethtool(HoneyPotCommand):
def call(self) -> None:
func = self.do_ethtool_help
for x in self.args:
if x.startswith("lo"):
func = self.do_ethtool_lo
if x.startswith("eth0"):
func = self.do_ethtool_eth0
if x.startswith("eth1"):
func = self.do_ethtool_eth1
func()
def do_ethtool_help(self) -> None:
"""
No real help output.
"""
self.write(
"""ethtool: bad command line argument(s)
For more information run ethtool -h\n"""
)
def do_ethtool_lo(self) -> None:
self.write(
"""Settings for lo:
Link detected: yes\n"""
)
def do_ethtool_eth0(self) -> None:
self.write(
"""Settings for eth0:
Supported ports: [ TP MII ]
Supported link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
1000baseT/Half 1000baseT/Full
Supported pause frame use: No
Supports auto-negotiation: Yes
Advertised link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
1000baseT/Half 1000baseT/Full
Advertised pause frame use: Symmetric Receive-only
Advertised auto-negotiation: Yes
Link partner advertised link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
1000baseT/Full
Link partner advertised pause frame use: Symmetric Receive-only
Link partner advertised auto-negotiation: Yes
Speed: 1000Mb/s
Duplex: Full
Port: MII
PHYAD: 0
Transceiver: internal
Auto-negotiation: on
Supports Wake-on: pumbg
Wake-on: g
Current message level: 0x00000033 (51)
drv probe ifdown ifup
Link detected: yes\n"""
)
def do_ethtool_eth1(self) -> None:
self.write(
"""Settings for eth1:
Cannot get device settings: No such device
Cannot get wake-on-lan settings: No such device
Cannot get message level: No such device
Cannot get link status: No such device
No data available\n"""
)
commands["/sbin/ethtool"] = Command_ethtool
commands["ethtool"] = Command_ethtool
| 2,441 | 28.071429 | 64 | py |
cowrie | cowrie-master/src/cowrie/commands/locate.py | from __future__ import annotations
import getopt
from cowrie.shell.command import HoneyPotCommand
commands = {}
LOCATE_HELP = """Usage: locate [OPTION]... [PATTERN]...
Search for entries in a mlocate database.
-A, --all only print entries that match all patterns
-b, --basename match only the base name of path names
-c, --count only print number of found entries
-d, --database DBPATH use DBPATH instead of default database (which is
/var/lib/mlocate/mlocate.db)
-e, --existing only print entries for currently existing files
-L, --follow follow trailing symbolic links when checking file
existence (default)
-h, --help print this help
-i, --ignore-case ignore case distinctions when matching patterns
-p, --ignore-spaces ignore punctuation and spaces when matching patterns
-t, --transliterate ignore accents using iconv transliteration when
matching patterns
-l, --limit, -n LIMIT limit output (or counting) to LIMIT entries
-m, --mmap ignored, for backward compatibility
-P, --nofollow, -H don't follow trailing symbolic links when checking file
existence
-0, --null separate entries with NUL on output
-S, --statistics don't search for entries, print statistics about each
used database
-q, --quiet report no error messages about reading databases
-r, --regexp REGEXP search for basic regexp REGEXP instead of patterns
--regex patterns are extended regexps
-s, --stdio ignored, for backward compatibility
-V, --version print version information
-w, --wholename match whole path name (default)
Report bugs to https://pagure.io/mlocate. \n
"""
LOCATE_VERSION = """mlocate 0.26
Copyright (C) 2007 Red Hat, Inc. All rights reserved.
This software is distributed under the GPL v.2.
This program is provided with NO WARRANTY, to the extent permitted by law. \n
"""
LOCATE_HELP_MSG = """no search pattern specified \n"""
class Command_locate(HoneyPotCommand):
def call(self):
if len(self.args):
try:
opts, args = getopt.gnu_getopt(
self.args, "hvr:", ["help", "version", "regexp="]
)
except getopt.GetoptError as err:
self.errorWrite(
f"locate: invalid option -- '{err.opt}'\nTry 'locate --help' for more information.\n"
)
return
for vars in opts:
if vars[0] == "-h" or vars[0] == "--help":
self.write(LOCATE_HELP)
return
elif vars[0] == "-v" or vars[0] == "--version":
self.write(LOCATE_VERSION)
return
if len(args) > 0:
paths_list = []
curdir = "/"
locate_list = self.find_path(args, paths_list, curdir)
for length in locate_list:
self.write(length + "\n")
return
else:
self.write(LOCATE_HELP_MSG)
return
def find_path(self, args, paths_list, curdir):
arg = args[0]
home_dir = self.fs.listdir(curdir)
for hf in home_dir:
abs_path = self.fs.resolve_path(hf, curdir)
if self.fs.isdir(hf):
self.find_path(args, paths_list, abs_path)
elif self.fs.isfile(abs_path):
resolve_path = self.fs.resolve_path(hf, curdir)
if arg in resolve_path and paths_list.count(resolve_path) == 0:
paths_list.append(resolve_path)
return paths_list
commands["locate"] = Command_locate
commands["/bin/locate"] = Command_locate
| 3,912 | 38.13 | 105 | py |
cowrie | cowrie-master/src/cowrie/commands/base64.py | from __future__ import annotations
import base64
import getopt
import sys
from twisted.python import log
from cowrie.shell.command import HoneyPotCommand
commands = {}
class Command_base64(HoneyPotCommand):
"""
author: Ivan Korolev (@fe7ch)
"""
mode: str = "e"
ignore: bool
def start(self) -> None:
self.mode = "e"
self.ignore = False
try:
optlist, args = getopt.getopt(
self.args,
"diw:",
["version", "help", "decode", "ignore-garbage", "wrap="],
)
except getopt.GetoptError:
self.errorWrite("Unrecognized option\n")
self.exit()
return
for opt in optlist:
if opt[0] == "--help":
self.write(
"""Usage: base64 [OPTION]... [FILE]
Base64 encode or decode FILE, or standard input, to standard output.
Mandatory arguments to long options are mandatory for short options too.
-d, --decode decode data
-i, --ignore-garbage when decoding, ignore non-alphabet characters
-w, --wrap=COLS wrap encoded lines after COLS character (default 76).
Use 0 to disable line wrapping
--help display this help and exit
--version output version information and exit
With no FILE, or when FILE is -, read standard input.
The data are encoded as described for the base64 alphabet in RFC 3548.
When decoding, the input may contain newlines in addition to the bytes of
the formal base64 alphabet. Use --ignore-garbage to attempt to recover
from any other non-alphabet bytes in the encoded stream.
Report base64 bugs to bug-coreutils@gnu.org
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info coreutils 'base64 invocation'
"""
)
self.exit()
return
elif opt[0] == "--version":
self.write(
"""base64 (GNU coreutils) 8.21
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Simon Josefsson.
"""
)
self.exit()
return
elif opt[0] == "-d" or opt[0] == "--decode":
self.mode = "d"
elif opt[0] == "-i" or opt[0] == "--ignore-garbage":
self.ignore = True
elif opt[0] == "-w" or opt[0] == "wrap":
pass
if self.input_data:
self.dojob(self.input_data)
else:
if len(args) > 1:
self.errorWrite(
"""base64: extra operand '%s'
Try 'base64 --help' for more information.
"""
% args[0]
)
self.exit()
return
pname = self.fs.resolve_path(args[0], self.protocol.cwd)
if not self.fs.isdir(pname):
try:
self.dojob(self.fs.file_contents(pname))
except Exception as e:
log.err(str(e))
self.errorWrite(f"base64: {args[0]}: No such file or directory\n")
else:
self.errorWrite("base64: read error: Is a directory\n")
self.exit()
def dojob(self, s: bytes) -> None:
if self.ignore:
s = b"".join(
[
i.to_bytes(1, sys.byteorder)
for i in s
if i
in b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
]
)
if self.mode == "e":
self.writeBytes(base64.b64encode(s))
self.writeBytes(b"\n")
else:
try:
self.writeBytes(base64.b64decode(s))
except Exception:
self.errorWrite("base64: invalid input\n")
def lineReceived(self, line: str) -> None:
log.msg(
eventid="cowrie.session.input",
realm="base64",
input=line,
format="INPUT (%(realm)s): %(input)s",
)
self.dojob(line.encode("ascii"))
def handle_CTRL_D(self) -> None:
self.exit()
commands["/usr/bin/base64"] = Command_base64
commands["base64"] = Command_base64
| 4,554 | 29.57047 | 91 | py |
cowrie | cowrie-master/src/cowrie/commands/adduser.py |
from __future__ import annotations
import random
from typing import Optional
from twisted.internet import reactor
from cowrie.shell.command import HoneyPotCommand
commands = {}
O_O, O_Q, O_P = 1, 2, 3
class Command_adduser(HoneyPotCommand):
item: int
output: list[tuple[int, str]] = [
(O_O, "Adding user `%(username)s' ...\n"),
(O_O, "Adding new group `%(username)s' (1001) ...\n"),
(
O_O,
"Adding new user `%(username)s' (1001) with group `%(username)s' ...\n",
),
(O_O, "Creating home directory `/home/%(username)s' ...\n"),
(O_O, "Copying files from `/etc/skel' ...\n"),
(O_P, "Password: "),
(O_P, "Password again: "),
(O_O, "\nChanging the user information for %(username)s\n"),
(O_O, "Enter the new value, or press ENTER for the default\n"),
(O_Q, " Username []: "),
(O_Q, " Full Name []: "),
(O_Q, " Room Number []: "),
(O_Q, " Work Phone []: "),
(O_Q, " Home Phone []: "),
(O_Q, " Mobile Phone []: "),
(O_Q, " Country []: "),
(O_Q, " City []: "),
(O_Q, " Language []: "),
(O_Q, " Favorite movie []: "),
(O_Q, " Other []: "),
(O_Q, "Is the information correct? [Y/n] "),
(O_O, "ERROR: Some of the information you entered is invalid\n"),
(O_O, "Deleting user `%(username)s' ...\n"),
(O_O, "Deleting group `%(username)s' (1001) ...\n"),
(O_O, "Deleting home directory `/home/%(username)s' ...\n"),
(O_Q, "Try again? [Y/n] "),
]
username: Optional[str] = None
def start(self) -> None:
self.item = 0
for arg in self.args:
if arg.startswith("-") or arg.isdigit():
continue
self.username = arg
break
if self.username is None:
self.write("adduser: Only one or two names allowed.\n")
self.exit()
return
self.do_output()
def do_output(self) -> None:
if self.item == len(self.output):
self.item = 7
self.schedule_next()
return
line = self.output[self.item]
self.write(line[1] % {"username": self.username})
if line[0] == O_P:
self.protocol.password_input = True
return
if line[0] == O_Q:
return
else:
self.item += 1
self.schedule_next()
def schedule_next(self) -> None:
self.scheduled = reactor.callLater(0.5 + random.random() * 1, self.do_output) # type: ignore[attr-defined]
def lineReceived(self, line: str) -> None:
if self.item + 1 == len(self.output) and line.strip() in ("n", "no"):
self.exit()
return
elif self.item == 20 and line.strip() not in ("y", "yes"):
self.item = 7
self.write("Ok, starting over\n")
elif not len(line) and self.output[self.item][0] == O_Q:
self.write("Must enter a value!\n")
else:
self.item += 1
self.schedule_next()
self.protocol.password_input = False
commands["/usr/sbin/adduser"] = Command_adduser
commands["/usr/sbin/useradd"] = Command_adduser
commands["adduser"] = Command_adduser
commands["useradd"] = Command_adduser
| 3,515 | 32.169811 | 115 | py |
cowrie | cowrie-master/src/cowrie/insults/insults.py |
from __future__ import annotations
import hashlib
import os
import time
from typing import Any
from twisted.conch.insults import insults
from twisted.python import log
from cowrie.core import ttylog
from cowrie.core.config import CowrieConfig
from cowrie.shell import protocol
class LoggingServerProtocol(insults.ServerProtocol):
"""
Wrapper for ServerProtocol that implements TTY logging
"""
ttylogPath: str = CowrieConfig.get("honeypot", "ttylog_path")
downloadPath: str = CowrieConfig.get("honeypot", "download_path")
ttylogEnabled: bool = CowrieConfig.getboolean("honeypot", "ttylog", fallback=True)
bytesReceivedLimit: int = CowrieConfig.getint(
"honeypot", "download_limit_size", fallback=0
)
def __init__(self, protocolFactory=None, *a, **kw):
self.type: str
self.ttylogFile: str
self.ttylogSize: int = 0
self.bytesReceived: int = 0
self.redirFiles: set[list[str]] = set()
self.redirlogOpen: bool = False # it will be set at core/protocol.py
self.stdinlogOpen: bool = False
self.ttylogOpen: bool = False
self.terminalProtocol: Any
self.transport: Any
self.startTime: float
self.stdinlogFile: str
insults.ServerProtocol.__init__(self, protocolFactory, *a, **kw)
if protocolFactory is protocol.HoneyPotExecProtocol:
self.type = "e" # Execcmd
else:
self.type = "i" # Interactive
def getSessionId(self):
transportId = self.transport.session.conn.transport.transportId
channelId = self.transport.session.id
return (transportId, channelId)
def connectionMade(self) -> None:
transportId, channelId = self.getSessionId()
self.startTime = time.time()
if self.ttylogEnabled:
self.ttylogFile = "{}/{}-{}-{}{}.log".format(
self.ttylogPath,
time.strftime("%Y%m%d-%H%M%S"),
transportId,
channelId,
self.type,
)
ttylog.ttylog_open(self.ttylogFile, self.startTime)
self.ttylogOpen = True
self.ttylogSize = 0
self.stdinlogFile = "{}/{}-{}-{}-stdin.log".format(
self.downloadPath,
time.strftime("%Y%m%d-%H%M%S"),
transportId,
channelId,
)
if self.type == "e":
self.stdinlogOpen = True
# log the command into ttylog
if self.ttylogEnabled:
(sess, cmd) = self.protocolArgs
ttylog.ttylog_write(
self.ttylogFile, len(cmd), ttylog.TYPE_INTERACT, time.time(), cmd
)
else:
self.stdinlogOpen = False
insults.ServerProtocol.connectionMade(self)
if self.type == "e":
self.terminalProtocol.execcmd.encode("utf8")
def write(self, data: bytes) -> None:
if self.ttylogEnabled and self.ttylogOpen:
ttylog.ttylog_write(
self.ttylogFile, len(data), ttylog.TYPE_OUTPUT, time.time(), data
)
self.ttylogSize += len(data)
insults.ServerProtocol.write(self, data)
def dataReceived(self, data: bytes) -> None:
"""
Input received from user
"""
self.bytesReceived += len(data)
if self.bytesReceivedLimit and self.bytesReceived > self.bytesReceivedLimit:
log.msg(format="Data upload limit reached")
self.eofReceived()
return
if self.stdinlogOpen:
with open(self.stdinlogFile, "ab") as f:
f.write(data)
elif self.ttylogEnabled and self.ttylogOpen:
ttylog.ttylog_write(
self.ttylogFile, len(data), ttylog.TYPE_INPUT, time.time(), data
)
# prevent crash if something like this was passed:
# echo cmd ; exit; \n\n
if self.terminalProtocol:
insults.ServerProtocol.dataReceived(self, data)
def eofReceived(self) -> None:
"""
Receive channel close and pass on to terminal
"""
if self.terminalProtocol:
self.terminalProtocol.eofReceived()
def loseConnection(self) -> None:
"""
Override super to remove the terminal reset on logout
"""
self.transport.loseConnection()
def connectionLost(self, reason):
"""
FIXME: this method is called 4 times on logout....
it's called once from Avatar.closed() if disconnected
"""
if self.stdinlogOpen:
try:
with open(self.stdinlogFile, "rb") as f:
shasum = hashlib.sha256(f.read()).hexdigest()
shasumfile = os.path.join(self.downloadPath, shasum)
if os.path.exists(shasumfile):
os.remove(self.stdinlogFile)
duplicate = True
else:
os.rename(self.stdinlogFile, shasumfile)
duplicate = False
log.msg(
eventid="cowrie.session.file_download",
format="Saved stdin contents with SHA-256 %(shasum)s to %(outfile)s",
duplicate=duplicate,
outfile=shasumfile,
shasum=shasum,
destfile="",
)
except OSError:
pass
finally:
self.stdinlogOpen = False
if self.redirFiles:
for rp in self.redirFiles:
rf = rp[0]
if rp[1]:
url = rp[1]
else:
url = rf[rf.find("redir_") + len("redir_") :]
try:
if not os.path.exists(rf):
continue
if os.path.getsize(rf) == 0:
os.remove(rf)
continue
with open(rf, "rb") as f:
shasum = hashlib.sha256(f.read()).hexdigest()
shasumfile = os.path.join(self.downloadPath, shasum)
if os.path.exists(shasumfile):
os.remove(rf)
duplicate = True
else:
os.rename(rf, shasumfile)
duplicate = False
log.msg(
eventid="cowrie.session.file_download",
format="Saved redir contents with SHA-256 %(shasum)s to %(outfile)s",
duplicate=duplicate,
outfile=shasumfile,
shasum=shasum,
destfile=url,
)
except OSError:
pass
self.redirFiles.clear()
if self.ttylogEnabled and self.ttylogOpen:
ttylog.ttylog_close(self.ttylogFile, time.time())
self.ttylogOpen = False
shasum = ttylog.ttylog_inputhash(self.ttylogFile)
shasumfile = os.path.join(self.ttylogPath, shasum)
if os.path.exists(shasumfile):
duplicate = True
os.remove(self.ttylogFile)
else:
duplicate = False
os.rename(self.ttylogFile, shasumfile)
umask = os.umask(0)
os.umask(umask)
os.chmod(shasumfile, 0o666 & ~umask)
log.msg(
eventid="cowrie.log.closed",
format="Closing TTY Log: %(ttylog)s after %(duration)d seconds",
ttylog=shasumfile,
size=self.ttylogSize,
shasum=shasum,
duplicate=duplicate,
duration=time.time() - self.startTime,
)
insults.ServerProtocol.connectionLost(self, reason)
class LoggingTelnetServerProtocol(LoggingServerProtocol):
"""
Wrap LoggingServerProtocol with single method to fetch session id for Telnet
"""
def getSessionId(self):
transportId = self.transport.session.transportId
sn = self.transport.session.transport.transport.sessionno
return (transportId, sn)
| 8,462 | 33.125 | 93 | py |
cowrie | cowrie-master/src/cowrie/shell/pwd.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
from binascii import crc32
from random import randint, seed
from typing import Any, Union
from twisted.python import log
from cowrie.core.config import CowrieConfig
class Passwd:
"""
This class contains code to handle the users and their properties in
/etc/passwd. Note that contrary to the name, it does not handle any
passwords.
"""
passwd_file = "{}/etc/passwd".format(CowrieConfig.get("honeypot", "contents_path"))
passwd: list[dict[str, Any]] = []
def __init__(self) -> None:
self.load()
def load(self) -> None:
"""
Load /etc/passwd
"""
self.passwd = []
with open(self.passwd_file, encoding="ascii") as f:
while True:
rawline = f.readline()
if not rawline:
break
line = rawline.strip()
if not line:
continue
if line.startswith("#"):
continue
if len(line.split(":")) != 7:
log.msg("Error parsing line `" + line + "` in <honeyfs>/etc/passwd")
continue
(
pw_name,
pw_passwd,
pw_uid,
pw_gid,
pw_gecos,
pw_dir,
pw_shell,
) = line.split(":")
e: dict[str, Union[str, int]] = {}
e["pw_name"] = pw_name
e["pw_passwd"] = pw_passwd
e["pw_gecos"] = pw_gecos
e["pw_dir"] = pw_dir
e["pw_shell"] = pw_shell
try:
e["pw_uid"] = int(pw_uid)
except ValueError:
e["pw_uid"] = 1001
try:
e["pw_gid"] = int(pw_gid)
except ValueError:
e["pw_gid"] = 1001
self.passwd.append(e)
def save(self):
"""
Save the user db
Note: this is subject to races between cowrie instances, but hey ...
"""
# with open(self.passwd_file, 'w') as f:
# for (login, uid, passwd) in self.userdb:
# f.write('%s:%d:%s\n' % (login, uid, passwd))
raise NotImplementedError
def getpwnam(self, name: str) -> dict[str, Any]:
"""
Get passwd entry for username
"""
for e in self.passwd:
if e["pw_name"] == name:
return e
raise KeyError("getpwnam(): name not found in passwd file: " + name)
def getpwuid(self, uid: int) -> dict[str, Any]:
"""
Get passwd entry for uid
"""
for e in self.passwd:
if uid == e["pw_uid"]:
return e
raise KeyError("getpwuid(): uid not found in passwd file: " + str(uid))
def setpwentry(self, name: str) -> dict[str, Any]:
"""
If the user is not in /etc/passwd, creates a new user entry for the session
"""
# ensure consistent uid and gid
seed_id = crc32(name.encode("utf-8"))
seed(seed_id)
e: dict[str, Any] = {}
e["pw_name"] = name
e["pw_passwd"] = "x"
e["pw_gecos"] = 0
e["pw_dir"] = "/home/" + name
e["pw_shell"] = "/bin/bash"
e["pw_uid"] = randint(1500, 10000)
e["pw_gid"] = e["pw_uid"]
self.passwd.append(e)
return e
class Group:
"""
This class contains code to handle the groups and their properties in
/etc/group.
"""
group_file = "{}/etc/group".format(CowrieConfig.get("honeypot", "contents_path"))
group: list[dict[str, Any]]
def __init__(self):
self.load()
def load(self) -> None:
"""
Load /etc/group
"""
self.group = []
with open(self.group_file, encoding="ascii") as f:
while True:
rawline = f.readline()
if not rawline:
break
line = rawline.strip()
if not line:
continue
if line.startswith("#"):
continue
(gr_name, _, gr_gid, gr_mem) = line.split(":")
e: dict[str, Union[str, int]] = {}
e["gr_name"] = gr_name
try:
e["gr_gid"] = int(gr_gid)
except ValueError:
e["gr_gid"] = 1001
e["gr_mem"] = gr_mem
self.group.append(e)
def save(self) -> None:
"""
Save the group db
Note: this is subject to races between cowrie instances, but hey ...
"""
# with open(self.group_file, 'w') as f:
# for (login, uid, passwd) in self.userdb:
# f.write('%s:%d:%s\n' % (login, uid, passwd))
raise NotImplementedError
def getgrnam(self, name: str) -> dict[str, Any]:
"""
Get group entry for groupname
"""
for e in self.group:
if name == e["gr_name"]:
return e
raise KeyError("getgrnam(): name not found in group file: " + name)
def getgrgid(self, uid: int) -> dict[str, Any]:
"""
Get group entry for gid
"""
for e in self.group:
if uid == e["gr_gid"]:
return e
raise KeyError("getgruid(): uid not found in group file: " + str(uid))
| 7,069 | 31.136364 | 88 | py |
cowrie | cowrie-master/src/cowrie/shell/avatar.py |
from __future__ import annotations
from zope.interface import implementer
from twisted.conch import avatar
from twisted.conch.error import ConchError
from twisted.conch.interfaces import IConchUser, ISession, ISFTPServer
from twisted.conch.ssh import filetransfer as conchfiletransfer
from twisted.conch.ssh.connection import OPEN_UNKNOWN_CHANNEL_TYPE
from twisted.python import components, log
from cowrie.core.config import CowrieConfig
from cowrie.shell import filetransfer, pwd
from cowrie.shell import session as shellsession
from cowrie.shell import server
from cowrie.ssh import forwarding
from cowrie.ssh import session as sshsession
@implementer(IConchUser)
class CowrieUser(avatar.ConchUser):
def __init__(self, username: bytes, server: server.CowrieServer) -> None:
avatar.ConchUser.__init__(self)
self.username: str = username.decode("utf-8")
self.server = server
self.channelLookup[b"session"] = sshsession.HoneyPotSSHSession
self.temporary: bool
try:
pwentry = pwd.Passwd().getpwnam(self.username)
self.temporary = False
except KeyError:
pwentry = pwd.Passwd().setpwentry(self.username)
self.temporary = True
self.uid = pwentry["pw_uid"]
self.gid = pwentry["pw_gid"]
self.home = pwentry["pw_dir"]
# SFTP support enabled only when option is explicitly set
if CowrieConfig.getboolean("ssh", "sftp_enabled", fallback=False):
self.subsystemLookup[b"sftp"] = conchfiletransfer.FileTransferServer
# SSH forwarding disabled only when option is explicitly set
if CowrieConfig.getboolean("ssh", "forwarding", fallback=True):
self.channelLookup[
b"direct-tcpip"
] = forwarding.cowrieOpenConnectForwardingClient
def logout(self) -> None:
log.msg(f"avatar {self.username} logging out")
def lookupChannel(self, channelType, windowSize, maxPacket, data):
"""
Override this to get more info on the unknown channel
"""
klass = self.channelLookup.get(channelType, None)
if not klass:
raise ConchError(
OPEN_UNKNOWN_CHANNEL_TYPE, f"unknown channel: {channelType}"
)
else:
return klass(
remoteWindow=windowSize,
remoteMaxPacket=maxPacket,
data=data,
avatar=self,
)
components.registerAdapter(
filetransfer.SFTPServerForCowrieUser, CowrieUser, ISFTPServer
)
components.registerAdapter(shellsession.SSHSessionForCowrieUser, CowrieUser, ISession)
| 2,773 | 33.675 | 86 | py |
cowrie | cowrie-master/src/cowrie/shell/fs.py |
# Todo, use os.stat_result, which contains the stat 10-tuple instead of the custom object.
from __future__ import annotations
import errno
import fnmatch
import hashlib
import os
from pathlib import Path
import pickle
import re
import sys
import stat
import time
from typing import Any, Optional
from twisted.python import log
from cowrie.core.config import CowrieConfig
(
A_NAME,
A_TYPE,
A_UID,
A_GID,
A_SIZE,
A_MODE,
A_CTIME,
A_CONTENTS,
A_TARGET,
A_REALFILE,
) = list(range(0, 10))
T_LINK, T_DIR, T_FILE, T_BLK, T_CHR, T_SOCK, T_FIFO = list(range(0, 7))
SPECIAL_PATHS: list[str] = ["/sys", "/proc", "/dev/pts"]
class _statobj:
"""
Transform a tuple into a stat object
"""
def __init__(
self,
st_mode: int,
st_ino: int,
st_dev: int,
st_nlink: int,
st_uid: int,
st_gid: int,
st_size: int,
st_atime: float,
st_mtime: float,
st_ctime: float,
) -> None:
self.st_mode: int = st_mode
self.st_ino: int = st_ino
self.st_dev: int = st_dev
self.st_nlink: int = st_nlink
self.st_uid: int = st_uid
self.st_gid: int = st_gid
self.st_size: int = st_size
self.st_atime: float = st_atime
self.st_mtime: float = st_mtime
self.st_ctime: float = st_ctime
class TooManyLevels(Exception):
"""
62 ELOOP Too many levels of symbolic links. A path name lookup involved more than 8 symbolic links.
raise OSError(errno.ELOOP, os.strerror(errno.ENOENT))
"""
class FileNotFound(Exception):
"""
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT))
"""
class PermissionDenied(Exception):
"""
Our implementation is rather naive for now
* TODO: Top-level /proc should return 'no such file' not 'permission
denied'. However this seems to vary based on kernel version.
$ sudo touch /sys/.nippon
touch: cannot touch '/sys/.nippon': Permission denied
$ sudo touch /proc/test
touch: cannot touch '/proc/test': No such file or directory
$ sudo touch /dev/pts/test
touch: cannot touch '/dev/pts/test': Permission denied
$ sudo touch /proc/sys/fs/binfmt_misc/.nippon
touch: cannot touch '/proc/sys/fs/binfmt_misc/.nippon': Permission denied
$ sudo touch /sys/fs/fuse/connections/.nippon
touch: cannot touch '/sys/fs/fuse/connections/.nippon': Permission denied
"""
class HoneyPotFilesystem:
def __init__(self, arch: str, home: str) -> None:
self.fs: list[Any]
try:
with open(CowrieConfig.get("shell", "filesystem"), "rb") as f:
self.fs = pickle.load(f)
except UnicodeDecodeError:
with open(CowrieConfig.get("shell", "filesystem"), "rb") as f:
self.fs = pickle.load(f, encoding="utf8")
except Exception as e:
log.err(e, "ERROR: Failed to load filesystem")
sys.exit(2)
# Keep track of arch so we can return appropriate binary
self.arch: str = arch
self.home: str = home
# Keep track of open file descriptors
self.tempfiles: dict[int, str] = {}
self.filenames: dict[int, str] = {}
# Keep count of new files, so we can have an artificial limit
self.newcount: int = 0
# Get the honeyfs path from the config file and explore it for file
# contents:
self.init_honeyfs(CowrieConfig.get("honeypot", "contents_path"))
def init_honeyfs(self, honeyfs_path: str) -> None:
"""
Explore the honeyfs at 'honeyfs_path' and set all A_REALFILE attributes on
the virtual filesystem.
"""
for path, _directories, filenames in os.walk(honeyfs_path):
for filename in filenames:
realfile_path: str = os.path.join(path, filename)
virtual_path: str = "/" + os.path.relpath(realfile_path, honeyfs_path)
f: Optional[list[Any]] = self.getfile(
virtual_path, follow_symlinks=False
)
if f and f[A_TYPE] == T_FILE:
self.update_realfile(f, realfile_path)
def resolve_path(self, pathspec: str, cwd: str) -> str:
"""
This function does not need to be in this class, it has no dependencies
"""
cwdpieces: list[str] = []
# If a path within home directory is specified, convert it to an absolute path
if pathspec.startswith("~/"):
path = self.home + pathspec[1:]
else:
path = pathspec
pieces = path.rstrip("/").split("/")
if path[0] == "/":
cwdpieces = []
else:
cwdpieces = [x for x in cwd.split("/") if len(x) and x is not None]
while 1:
if not pieces:
break
piece = pieces.pop(0)
if piece == "..":
if cwdpieces:
cwdpieces.pop()
continue
if piece in (".", ""):
continue
cwdpieces.append(piece)
return "/{}".format("/".join(cwdpieces))
def resolve_path_wc(self, path: str, cwd: str) -> list[str]:
"""
Resolve_path with wildcard support (globbing)
"""
pieces: list[str] = path.rstrip("/").split("/")
cwdpieces: list[str]
if len(pieces[0]):
cwdpieces = [x for x in cwd.split("/") if len(x) and x is not None]
path = path[1:]
else:
cwdpieces, pieces = [], pieces[1:]
found: list[str] = []
def foo(p, cwd):
if not p:
found.append("/{}".format("/".join(cwd)))
elif p[0] == ".":
foo(p[1:], cwd)
elif p[0] == "..":
foo(p[1:], cwd[:-1])
else:
names = [x[A_NAME] for x in self.get_path("/".join(cwd))]
matches = [x for x in names if fnmatch.fnmatchcase(x, p[0])]
for match in matches:
foo(p[1:], [*cwd, match])
foo(pieces, cwdpieces)
return found
def get_path(self, path: str, follow_symlinks: bool = True) -> Any:
"""
This returns the Cowrie file system objects for a directory
"""
cwd: list[Any] = self.fs
for part in path.split("/"):
if not part:
continue
ok = False
for c in cwd[A_CONTENTS]:
if c[A_NAME] == part:
if c[A_TYPE] == T_LINK:
f = self.getfile(c[A_TARGET], follow_symlinks=follow_symlinks)
if f is None:
ok = False
break
else:
cwd = f
else:
cwd = c
ok = True
break
if not ok:
raise FileNotFound
return cwd[A_CONTENTS]
def exists(self, path: str) -> bool:
"""
Return True if path refers to an existing path.
Returns False for broken symbolic links.
"""
f: Optional[list[Any]] = self.getfile(path, follow_symlinks=True)
if f is not None:
return True
return False
def lexists(self, path: str) -> bool:
"""
Return True if path refers to an existing path.
Returns True for broken symbolic links.
"""
f: Optional[list[Any]] = self.getfile(path, follow_symlinks=False)
if f is not None:
return True
return False
def update_realfile(self, f: Any, realfile: str) -> None:
if (
not f[A_REALFILE]
and os.path.exists(realfile)
and not os.path.islink(realfile)
and os.path.isfile(realfile)
and f[A_SIZE] < 25000000
):
f[A_REALFILE] = realfile
def getfile(self, path: str, follow_symlinks: bool = True) -> Optional[list[Any]]:
"""
This returns the Cowrie file system object for a path
"""
if path == "/":
return self.fs
pieces: list[str] = path.strip("/").split("/")
cwd: str = ""
p: Optional[list[Any]] = self.fs
for piece in pieces:
if not isinstance(p, list):
return None
if piece not in [x[A_NAME] for x in p[A_CONTENTS]]:
return None
for x in p[A_CONTENTS]:
if x[A_NAME] == piece:
if piece == pieces[-1] and not follow_symlinks:
p = x
elif x[A_TYPE] == T_LINK:
if x[A_TARGET][0] == "/":
# Absolute link
fileobj = self.getfile(
x[A_TARGET], follow_symlinks=follow_symlinks
)
else:
# Relative link
fileobj = self.getfile(
"/".join((cwd, x[A_TARGET])),
follow_symlinks=follow_symlinks,
)
if not fileobj:
# Broken link
return None
p = fileobj
else:
p = x
# cwd = '/'.join((cwd, piece))
return p
def file_contents(self, target: str) -> bytes:
"""
Retrieve the content of a file in the honeyfs
It follows links.
It tries A_REALFILE first and then tries honeyfs directory
Then return the executable header for executables
"""
path: str = self.resolve_path(target, os.path.dirname(target))
if not path or not self.exists(path):
raise FileNotFound
f: Any = self.getfile(path)
if f[A_TYPE] == T_DIR:
raise IsADirectoryError
if f[A_TYPE] == T_FILE and f[A_REALFILE]:
return Path(f[A_REALFILE]).read_bytes()
if f[A_TYPE] == T_FILE and f[A_SIZE] == 0:
# Zero-byte file lacking A_REALFILE backing: probably empty.
# (The exceptions to this are some system files in /proc and /sys,
# but it's likely better to return nothing than suspiciously fail.)
return b""
if f[A_TYPE] == T_FILE and f[A_MODE] & stat.S_IXUSR:
return open(
CowrieConfig.get("honeypot", "share_path") + "/arch/" + self.arch,
"rb",
).read()
return b""
def mkfile(
self,
path: str,
uid: int,
gid: int,
size: int,
mode: int,
ctime: Optional[float] = None,
) -> bool:
if self.newcount > 10000:
return False
if ctime is None:
ctime = time.time()
_path: str = os.path.dirname(path)
if any([_path.startswith(_p) for _p in SPECIAL_PATHS]):
raise PermissionDenied
_dir = self.get_path(_path)
outfile: str = os.path.basename(path)
if outfile in [x[A_NAME] for x in _dir]:
_dir.remove([x for x in _dir if x[A_NAME] == outfile][0])
_dir.append([outfile, T_FILE, uid, gid, size, mode, ctime, [], None, None])
self.newcount += 1
return True
def mkdir(
self,
path: str,
uid: int,
gid: int,
size: int,
mode: int,
ctime: Optional[float] = None,
) -> None:
if self.newcount > 10000:
raise OSError(errno.EDQUOT, os.strerror(errno.EDQUOT), path)
if ctime is None:
ctime = time.time()
if not path.strip("/"):
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), path)
try:
directory = self.get_path(os.path.dirname(path.strip("/")))
except IndexError:
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), path) from None
directory.append(
[os.path.basename(path), T_DIR, uid, gid, size, mode, ctime, [], None, None]
)
self.newcount += 1
def isfile(self, path: str) -> bool:
"""
Return True if path is an existing regular file. This follows symbolic
links, so both islink() and isfile() can be true for the same path.
"""
try:
f: Optional[list[Any]] = self.getfile(path)
except Exception:
return False
if f is None:
return False
if f[A_TYPE] == T_FILE:
return True
return False
def islink(self, path: str) -> bool:
"""
Return True if path refers to a directory entry that is a symbolic
link. Always False if symbolic links are not supported by the python
runtime.
"""
try:
f: Optional[list[Any]] = self.getfile(path)
except Exception:
return False
if f is None:
return False
if f[A_TYPE] == T_LINK:
return True
return False
def isdir(self, path: str) -> bool:
"""
Return True if path is an existing directory.
This follows symbolic links, so both islink() and isdir() can be true for the same path.
"""
if path == "/":
return True
try:
directory = self.getfile(path)
except Exception:
directory = None
if directory is None:
return False
if directory[A_TYPE] == T_DIR:
return True
return False
# Below additions for SFTP support, try to keep functions here similar to os.*
def open(self, filename: str, openFlags: int, mode: int) -> Optional[int]:
"""
#log.msg("fs.open %s" % filename)
#if (openFlags & os.O_APPEND == os.O_APPEND):
# log.msg("fs.open append")
#if (openFlags & os.O_CREAT == os.O_CREAT):
# log.msg("fs.open creat")
#if (openFlags & os.O_TRUNC == os.O_TRUNC):
# log.msg("fs.open trunc")
#if (openFlags & os.O_EXCL == os.O_EXCL):
# log.msg("fs.open excl")
# treat O_RDWR same as O_WRONLY
"""
if openFlags & os.O_WRONLY == os.O_WRONLY or openFlags & os.O_RDWR == os.O_RDWR:
# strip executable bit
hostmode: int = mode & ~(111)
hostfile: str = "{}/{}_sftp_{}".format(
CowrieConfig.get("honeypot", "download_path"),
time.strftime("%Y%m%d-%H%M%S"),
re.sub("[^A-Za-z0-9]", "_", filename),
)
self.mkfile(filename, 0, 0, 0, stat.S_IFREG | mode)
fd = os.open(hostfile, openFlags, hostmode)
self.update_realfile(self.getfile(filename), hostfile)
self.tempfiles[fd] = hostfile
self.filenames[fd] = filename
return fd
# TODO: throw exception
if openFlags & os.O_RDONLY == os.O_RDONLY:
return None
# TODO: throw exception
return None
def read(self, fd: int, n: int) -> bytes:
# this should not be called, we intercept at readChunk
raise NotImplementedError
def write(self, fd: int, string: bytes) -> int:
return os.write(fd, string)
def close(self, fd: int) -> None:
if not fd:
return
if self.tempfiles[fd] is not None:
with open(self.tempfiles[fd], "rb") as f:
shasum: str = hashlib.sha256(f.read()).hexdigest()
shasumfile: str = (
CowrieConfig.get("honeypot", "download_path") + "/" + shasum
)
if os.path.exists(shasumfile):
os.remove(self.tempfiles[fd])
else:
os.rename(self.tempfiles[fd], shasumfile)
self.update_realfile(self.getfile(self.filenames[fd]), shasumfile)
log.msg(
format='SFTP Uploaded file "%(filename)s" to %(outfile)s',
eventid="cowrie.session.file_upload",
filename=os.path.basename(self.filenames[fd]),
outfile=shasumfile,
shasum=shasum,
)
del self.tempfiles[fd]
del self.filenames[fd]
os.close(fd)
def lseek(self, fd: int, offset: int, whence: int) -> int:
if not fd:
return True
return os.lseek(fd, offset, whence)
def mkdir2(self, path: str) -> None:
"""
FIXME mkdir() name conflicts with existing mkdir
"""
directory: Optional[list[Any]] = self.getfile(path)
if directory:
raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), path)
self.mkdir(path, 0, 0, 4096, 16877)
def rmdir(self, path: str) -> bool:
p: str = path.rstrip("/")
name: str = os.path.basename(p)
parent: str = os.path.dirname(p)
directory: Any = self.getfile(p, follow_symlinks=False)
if not directory:
raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), p)
if directory[A_TYPE] != T_DIR:
raise OSError(errno.ENOTDIR, os.strerror(errno.ENOTDIR), p)
if len(self.get_path(p)) > 0:
raise OSError(errno.ENOTEMPTY, os.strerror(errno.ENOTEMPTY), p)
pdir = self.get_path(parent, follow_symlinks=True)
for i in pdir[:]:
if i[A_NAME] == name:
pdir.remove(i)
return True
return False
def utime(self, path: str, _atime: float, mtime: float) -> None:
p: Optional[list[Any]] = self.getfile(path)
if not p:
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT))
p[A_CTIME] = mtime
def chmod(self, path: str, perm: int) -> None:
p: Optional[list[Any]] = self.getfile(path)
if not p:
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT))
p[A_MODE] = stat.S_IFMT(p[A_MODE]) | perm
def chown(self, path: str, uid: int, gid: int) -> None:
p: Optional[list[Any]] = self.getfile(path)
if not p:
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT))
if uid != -1:
p[A_UID] = uid
if gid != -1:
p[A_GID] = gid
def remove(self, path: str) -> None:
p: Optional[list[Any]] = self.getfile(path, follow_symlinks=False)
if not p:
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT))
self.get_path(os.path.dirname(path)).remove(p)
def readlink(self, path: str) -> str:
p: Optional[list[Any]] = self.getfile(path, follow_symlinks=False)
if not p:
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT))
if not p[A_MODE] & stat.S_IFLNK:
raise OSError
return p[A_TARGET] # type: ignore
def symlink(self, targetPath: str, linkPath: str) -> None:
raise NotImplementedError
def rename(self, oldpath: str, newpath: str) -> None:
old: Optional[list[Any]] = self.getfile(oldpath)
if not old:
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT))
new = self.getfile(newpath)
if new:
raise OSError(errno.EEXIST, os.strerror(errno.EEXIST))
self.get_path(os.path.dirname(oldpath)).remove(old)
old[A_NAME] = os.path.basename(newpath)
self.get_path(os.path.dirname(newpath)).append(old)
def listdir(self, path: str) -> list[str]:
names: list[str] = [x[A_NAME] for x in self.get_path(path)]
return names
def lstat(self, path: str) -> _statobj:
return self.stat(path, follow_symlinks=False)
def stat(self, path: str, follow_symlinks: bool = True) -> _statobj:
p: Optional[list[Any]]
if path == "/":
# TODO: shouldn't this be a list?
p = []
p[A_TYPE] = T_DIR
p[A_UID] = 0
p[A_GID] = 0
p[A_SIZE] = 4096
p[A_MODE] = 16877
p[A_CTIME] = time.time()
else:
p = self.getfile(path, follow_symlinks=follow_symlinks)
if not p:
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT))
return _statobj(
p[A_MODE],
0,
0,
1,
p[A_UID],
p[A_GID],
p[A_SIZE],
p[A_CTIME],
p[A_CTIME],
p[A_CTIME],
)
def realpath(self, path: str) -> str:
return path
def update_size(self, filename: str, size: int) -> None:
f: Optional[list[Any]] = self.getfile(filename)
if not f:
return
if f[A_TYPE] != T_FILE:
return
f[A_SIZE] = size
| 21,062 | 32.014107 | 104 | py |
cowrie | cowrie-master/src/cowrie/shell/server.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
from __future__ import annotations
import json
import random
from configparser import NoOptionError
from twisted.cred.portal import IRealm
from twisted.python import log
from cowrie.core.config import CowrieConfig
from cowrie.shell import fs
class CowrieServer:
"""
In traditional Kippo each connection gets its own simulated machine.
This is not always ideal, sometimes two connections come from the same
source IP address. we want to give them the same environment as well.
So files uploaded through SFTP are visible in the SSH session.
This class represents a 'virtual server' that can be shared between
multiple Cowrie connections
"""
fs = None
process = None
hostname: str = CowrieConfig.get("honeypot", "hostname")
def __init__(self, realm: IRealm) -> None:
try:
arches = [
arch.strip() for arch in CowrieConfig.get("shell", "arch").split(",")
]
self.arch = random.choice(arches)
except NoOptionError:
self.arch = "linux-x64-lsb"
log.msg(f"Initialized emulated server as architecture: {self.arch}")
def getCommandOutput(self, file):
"""
Reads process output from JSON file.
"""
with open(file, encoding="utf-8") as f:
cmdoutput = json.load(f)
return cmdoutput
def initFileSystem(self, home):
"""
Do this so we can trigger it later. Not all sessions need file system
"""
self.fs = fs.HoneyPotFilesystem(self.arch, home)
try:
self.process = self.getCommandOutput(
CowrieConfig.get("shell", "processes")
)["command"]["ps"]
except NoOptionError:
self.process = None
| 3,256 | 36.011364 | 85 | py |
cowrie | cowrie-master/src/cowrie/shell/filetransfer.py |
"""
This module contains ...
"""
from __future__ import annotations
import os
from zope.interface import implementer
import twisted
import twisted.conch.ls
from twisted.conch.interfaces import ISFTPFile, ISFTPServer
from twisted.conch.ssh import filetransfer
from twisted.conch.ssh.filetransfer import (
FXF_APPEND,
FXF_CREAT,
FXF_EXCL,
FXF_READ,
FXF_TRUNC,
FXF_WRITE,
)
from twisted.python import log
from twisted.python.compat import nativeString
from cowrie.shell import pwd
from cowrie.core.config import CowrieConfig
@implementer(ISFTPFile)
class CowrieSFTPFile:
"""
SFTPTFile
"""
contents: bytes
bytesReceived: int = 0
bytesReceivedLimit: int = CowrieConfig.getint(
"honeypot", "download_limit_size", fallback=0
)
def __init__(self, sftpserver, filename, flags, attrs):
self.sftpserver = sftpserver
self.filename = filename
openFlags = 0
if flags & FXF_READ == FXF_READ and flags & FXF_WRITE == 0:
openFlags = os.O_RDONLY
if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == 0:
openFlags = os.O_WRONLY
if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == FXF_READ:
openFlags = os.O_RDWR
if flags & FXF_APPEND == FXF_APPEND:
openFlags |= os.O_APPEND
if flags & FXF_CREAT == FXF_CREAT:
openFlags |= os.O_CREAT
if flags & FXF_TRUNC == FXF_TRUNC:
openFlags |= os.O_TRUNC
if flags & FXF_EXCL == FXF_EXCL:
openFlags |= os.O_EXCL
if "permissions" in attrs:
filemode = attrs["permissions"]
del attrs["permissions"]
else:
filemode = 0o777
fd = sftpserver.fs.open(filename, openFlags, filemode)
if attrs:
self.sftpserver.setAttrs(filename, attrs)
self.fd = fd
# Cache a copy of file in memory to read from in readChunk
if flags & FXF_READ == FXF_READ:
self.contents = self.sftpserver.fs.file_contents(self.filename)
def close(self):
if self.bytesReceived > 0:
self.sftpserver.fs.update_size(self.filename, self.bytesReceived)
return self.sftpserver.fs.close(self.fd)
def readChunk(self, offset: int, length: int) -> bytes:
return self.contents[offset : offset + length]
def writeChunk(self, offset: int, data: bytes) -> None:
self.bytesReceived += len(data)
if self.bytesReceivedLimit and self.bytesReceived > self.bytesReceivedLimit:
raise filetransfer.SFTPError(filetransfer.FX_FAILURE, "Quota exceeded")
self.sftpserver.fs.lseek(self.fd, offset, os.SEEK_SET)
self.sftpserver.fs.write(self.fd, data)
def getAttrs(self):
s = self.sftpserver.fs.stat(self.filename)
return self.sftpserver.getAttrs(s)
def setAttrs(self, attrs):
raise NotImplementedError
class CowrieSFTPDirectory:
def __init__(self, server, directory):
self.server = server
self.files = server.fs.listdir(directory)
self.files = [".", "..", *self.files]
self.dir = directory
def __iter__(self):
return self
def __next__(self):
try:
f = self.files.pop(0)
except IndexError:
raise StopIteration from None
if f == "..":
directory = self.dir.strip().split("/")
pdir = "/" + "/".join(directory[:-1])
s1 = self.server.fs.lstat(pdir)
s = self.server.fs.lstat(pdir)
s1.st_uid = pwd.Passwd().getpwuid(s.st_uid)["pw_name"]
s1.st_gid = pwd.Group().getgrgid(s.st_gid)["gr_name"]
longname = twisted.conch.ls.lsLine(f, s1)
attrs = self.server._getAttrs(s)
return (f, longname, attrs)
elif f == ".":
s1 = self.server.fs.lstat(self.dir)
s = self.server.fs.lstat(self.dir)
s1.st_uid = pwd.Passwd().getpwuid(s.st_uid)["pw_name"]
s1.st_gid = pwd.Group().getgrgid(s.st_gid)["gr_name"]
longname = twisted.conch.ls.lsLine(f, s1)
attrs = self.server._getAttrs(s)
return (f, longname, attrs)
else:
s = self.server.fs.lstat(os.path.join(self.dir, f))
s2 = self.server.fs.lstat(os.path.join(self.dir, f))
s2.st_uid = pwd.Passwd().getpwuid(s.st_uid)["pw_name"]
s2.st_gid = pwd.Group().getgrgid(s.st_gid)["gr_name"]
longname = twisted.conch.ls.lsLine(f, s2)
attrs = self.server._getAttrs(s)
return (f, longname, attrs)
def close(self):
self.files = []
@implementer(ISFTPServer)
class SFTPServerForCowrieUser:
def __init__(self, avatar):
self.avatar = avatar
self.avatar.server.initFileSystem(self.avatar.home)
self.fs = self.avatar.server.fs
def _absPath(self, path):
home = self.avatar.home
return os.path.abspath(os.path.join(nativeString(home), nativeString(path)))
def _setAttrs(self, path, attrs):
if "uid" in attrs and "gid" in attrs:
self.fs.chown(path, attrs["uid"], attrs["gid"])
if "permissions" in attrs:
self.fs.chmod(path, attrs["permissions"])
if "atime" in attrs and "mtime" in attrs:
self.fs.utime(path, attrs["atime"], attrs["mtime"])
def _getAttrs(self, s):
return {
"size": s.st_size,
"uid": s.st_uid,
"gid": s.st_gid,
"permissions": s.st_mode,
"atime": int(s.st_atime),
"mtime": int(s.st_mtime),
}
def gotVersion(self, otherVersion, extData):
return {}
def openFile(self, filename, flags, attrs):
log.msg(f"SFTP openFile: {filename}")
return CowrieSFTPFile(self, self._absPath(filename), flags, attrs)
def removeFile(self, filename):
log.msg(f"SFTP removeFile: {filename}")
return self.fs.remove(self._absPath(filename))
def renameFile(self, oldpath, newpath):
log.msg(f"SFTP renameFile: {oldpath} {newpath}")
return self.fs.rename(self._absPath(oldpath), self._absPath(newpath))
def makeDirectory(self, path, attrs):
log.msg(f"SFTP makeDirectory: {path}")
path = self._absPath(path)
self.fs.mkdir2(path)
self._setAttrs(path, attrs)
def removeDirectory(self, path):
log.msg(f"SFTP removeDirectory: {path}")
return self.fs.rmdir(self._absPath(path))
def openDirectory(self, path):
log.msg(f"SFTP OpenDirectory: {path}")
return CowrieSFTPDirectory(self, self._absPath(path))
def getAttrs(self, path, followLinks):
log.msg(f"SFTP getAttrs: {path}")
path = self._absPath(path)
if followLinks:
s = self.fs.stat(path)
else:
s = self.fs.lstat(path)
return self._getAttrs(s)
def setAttrs(self, path, attrs):
log.msg(f"SFTP setAttrs: {path}")
path = self._absPath(path)
return self._setAttrs(path, attrs)
def readLink(self, path):
log.msg(f"SFTP readLink: {path}")
path = self._absPath(path)
return self.fs.readlink(path)
def makeLink(self, linkPath, targetPath):
log.msg(f"SFTP makeLink: {linkPath} {targetPath}")
linkPath = self._absPath(linkPath)
targetPath = self._absPath(targetPath)
return self.fs.symlink(targetPath, linkPath)
def realPath(self, path):
return self.fs.realpath(self._absPath(path))
def extendedRequest(self, extName, extData):
raise NotImplementedError
| 7,786 | 31.995763 | 84 | py |
cowrie | cowrie-master/src/cowrie/shell/honeypot.py |
from __future__ import annotations
import copy
import os
import re
import shlex
from typing import Any, Optional
from twisted.internet import error
from twisted.python import failure, log
from twisted.python.compat import iterbytes
from cowrie.core.config import CowrieConfig
from cowrie.shell import fs
class HoneyPotShell:
def __init__(
self, protocol: Any, interactive: bool = True, redirect: bool = False
) -> None:
self.protocol = protocol
self.interactive: bool = interactive
self.redirect: bool = redirect # to support output redirection
self.cmdpending: list[list[str]] = []
self.environ: dict[str, str] = copy.copy(protocol.environ)
if hasattr(protocol.user, "windowSize"):
self.environ["COLUMNS"] = str(protocol.user.windowSize[1])
self.environ["LINES"] = str(protocol.user.windowSize[0])
self.lexer: Optional[shlex.shlex] = None
self.showPrompt()
def lineReceived(self, line: str) -> None:
log.msg(eventid="cowrie.command.input", input=line, format="CMD: %(input)s")
self.lexer = shlex.shlex(instream=line, punctuation_chars=True, posix=True)
# Add these special characters that are not in the default lexer
self.lexer.wordchars += "@%{}=$:+^,()`"
tokens: list[str] = []
while True:
try:
tok: str = self.lexer.get_token()
# log.msg("tok: %s" % (repr(tok)))
if tok == self.lexer.eof:
if tokens:
self.cmdpending.append(tokens)
break
# For now, treat && and || same as ;, just execute without checking return code
if tok == "&&" or tok == "||":
if tokens:
self.cmdpending.append(tokens)
tokens = []
continue
else:
self.protocol.terminal.write(
f"-bash: syntax error near unexpected token `{tok}'\n".encode()
)
break
elif tok == ";":
if tokens:
self.cmdpending.append(tokens)
tokens = []
continue
else:
self.protocol.terminal.write(
f"-bash: syntax error near unexpected token `{tok}'\n".encode()
)
break
elif tok == "$?":
tok = "0"
elif tok[0] == "(":
cmd = self.do_command_substitution(tok)
tokens = cmd.split()
continue
elif "$(" in tok or "`" in tok:
tok = self.do_command_substitution(tok)
elif tok.startswith("${"):
envRex = re.compile(r"^\${([_a-zA-Z0-9]+)}$")
envSearch = envRex.search(tok)
if envSearch is not None:
envMatch = envSearch.group(1)
if envMatch in list(self.environ.keys()):
tok = self.environ[envMatch]
else:
continue
elif tok.startswith("$"):
envRex = re.compile(r"^\$([_a-zA-Z0-9]+)$")
envSearch = envRex.search(tok)
if envSearch is not None:
envMatch = envSearch.group(1)
if envMatch in list(self.environ.keys()):
tok = self.environ[envMatch]
else:
continue
tokens.append(tok)
except Exception as e:
self.protocol.terminal.write(
b"-bash: syntax error: unexpected end of file\n"
)
# Could run runCommand here, but i'll just clear the list instead
log.msg(f"exception: {e}")
self.cmdpending = []
self.showPrompt()
return
if self.cmdpending:
self.runCommand()
else:
self.showPrompt()
def do_command_substitution(self, start_tok: str) -> str:
if start_tok[0] == "(":
# start parsing the (...) expression
cmd_expr = start_tok
pos = 1
elif "$(" in start_tok:
# split the first token to prefix and $(... part
dollar_pos = start_tok.index("$(")
result = start_tok[:dollar_pos]
cmd_expr = start_tok[dollar_pos:]
pos = 2
elif "`" in start_tok:
# split the first token to prefix and `... part
backtick_pos = start_tok.index("`")
result = start_tok[:backtick_pos]
cmd_expr = start_tok[backtick_pos:]
pos = 1
opening_count = 1
closing_count = 0
# parse the remaining tokens and execute subshells
while opening_count > closing_count:
if cmd_expr[pos] in (")", "`"):
# found an end of $(...) or `...`
closing_count += 1
if opening_count == closing_count:
if cmd_expr[0] == "(":
# return the command in () without executing it
result = cmd_expr[1:pos]
else:
# execute the command in $() or `` or () and return the output
result += self.run_subshell_command(cmd_expr[: pos + 1])
# check whether there are more command substitutions remaining
if pos < len(cmd_expr) - 1:
remainder = cmd_expr[pos + 1 :]
if "$(" in remainder or "`" in remainder:
result = self.do_command_substitution(result + remainder)
else:
result += remainder
else:
pos += 1
elif cmd_expr[pos : pos + 2] == "$(":
# found a new $(...) expression
opening_count += 1
pos += 2
else:
if opening_count > closing_count and pos == len(cmd_expr) - 1:
if self.lexer:
tok = self.lexer.get_token()
cmd_expr = cmd_expr + " " + tok
elif opening_count == closing_count:
result += cmd_expr[pos]
pos += 1
return result
def run_subshell_command(self, cmd_expr: str) -> str:
# extract the command from $(...) or `...` or (...) expression
if cmd_expr.startswith("$("):
cmd = cmd_expr[2:-1]
else:
cmd = cmd_expr[1:-1]
# instantiate new shell with redirect output
self.protocol.cmdstack.append(
HoneyPotShell(self.protocol, interactive=False, redirect=True)
)
# call lineReceived method that indicates that we have some commands to parse
self.protocol.cmdstack[-1].lineReceived(cmd)
# remove the shell
res = self.protocol.cmdstack.pop()
try:
output: str = res.protocol.pp.redirected_data.decode()[:-1]
return output
except AttributeError:
return ""
def runCommand(self):
pp = None
def runOrPrompt() -> None:
if self.cmdpending:
self.runCommand()
else:
self.showPrompt()
def parse_arguments(arguments: list[str]) -> list[str]:
parsed_arguments = []
for arg in arguments:
parsed_arguments.append(arg)
return parsed_arguments
def parse_file_arguments(arguments: str) -> list[str]:
"""
Look up arguments in the file system
"""
parsed_arguments = []
for arg in arguments:
matches = self.protocol.fs.resolve_path_wc(arg, self.protocol.cwd)
if matches:
parsed_arguments.extend(matches)
else:
parsed_arguments.append(arg)
return parsed_arguments
if not self.cmdpending:
if self.protocol.pp.next_command is None: # command dont have pipe(s)
if self.interactive:
self.showPrompt()
else:
# when commands passed to a shell via PIPE, we spawn a HoneyPotShell in none interactive mode
# if there are another shells on stack (cmdstack), let's just exit our new shell
# else close connection
if len(self.protocol.cmdstack) == 1:
ret = failure.Failure(error.ProcessDone(status=""))
self.protocol.terminal.transport.processEnded(ret)
else:
return
else:
pass # command with pipes
return
cmdAndArgs = self.cmdpending.pop(0)
cmd2 = copy.copy(cmdAndArgs)
# Probably no reason to be this comprehensive for just PATH...
environ = copy.copy(self.environ)
cmd_array = []
cmd: dict[str, Any] = {}
while cmdAndArgs:
piece = cmdAndArgs.pop(0)
if piece.count("="):
key, val = piece.split("=", 1)
environ[key] = val
continue
cmd["command"] = piece
cmd["rargs"] = []
break
if "command" not in cmd or not cmd["command"]:
runOrPrompt()
return
pipe_indices = [i for i, x in enumerate(cmdAndArgs) if x == "|"]
multipleCmdArgs: list[list[str]] = []
pipe_indices.append(len(cmdAndArgs))
start = 0
# Gather all arguments with pipes
for _index, pipe_indice in enumerate(pipe_indices):
multipleCmdArgs.append(cmdAndArgs[start:pipe_indice])
start = pipe_indice + 1
cmd["rargs"] = parse_arguments(multipleCmdArgs.pop(0))
# parse_file_arguments parses too much. should not parse every argument
# cmd['rargs'] = parse_file_arguments(multipleCmdArgs.pop(0))
cmd_array.append(cmd)
cmd = {}
for value in multipleCmdArgs:
cmd["command"] = value.pop(0)
cmd["rargs"] = parse_arguments(value)
cmd_array.append(cmd)
cmd = {}
lastpp = None
for index, cmd in reversed(list(enumerate(cmd_array))):
cmdclass = self.protocol.getCommand(
cmd["command"], environ["PATH"].split(":")
)
if cmdclass:
log.msg(
input=cmd["command"] + " " + " ".join(cmd["rargs"]),
format="Command found: %(input)s",
)
if index == len(cmd_array) - 1:
lastpp = StdOutStdErrEmulationProtocol(
self.protocol, cmdclass, cmd["rargs"], None, None, self.redirect
)
pp = lastpp
else:
pp = StdOutStdErrEmulationProtocol(
self.protocol,
cmdclass,
cmd["rargs"],
None,
lastpp,
self.redirect,
)
lastpp = pp
else:
log.msg(
eventid="cowrie.command.failed",
input=" ".join(cmd2),
format="Command not found: %(input)s",
)
self.protocol.terminal.write(
"-bash: {}: command not found\n".format(cmd["command"]).encode(
"utf8"
)
)
if not self.interactive:
stat = failure.Failure(error.ProcessDone(status=""))
self.protocol.terminal.transport.processEnded(stat)
runOrPrompt()
pp = None # Got a error. Don't run any piped commands
break
if pp:
self.protocol.call_command(pp, cmdclass, *cmd_array[0]["rargs"])
def resume(self) -> None:
if self.interactive:
self.protocol.setInsertMode()
self.runCommand()
def showPrompt(self) -> None:
if not self.interactive:
return
prompt = ""
if CowrieConfig.has_option("honeypot", "prompt"):
prompt = CowrieConfig.get("honeypot", "prompt")
prompt += " "
else:
cwd = self.protocol.cwd
homelen = len(self.protocol.user.avatar.home)
if cwd == self.protocol.user.avatar.home:
cwd = "~"
elif (
len(cwd) > (homelen + 1)
and cwd[: (homelen + 1)] == self.protocol.user.avatar.home + "/"
):
cwd = "~" + cwd[homelen:]
# Example: [root@svr03 ~]# (More of a "CentOS" feel)
# Example: root@svr03:~# (More of a "Debian" feel)
prompt = f"{self.protocol.user.username}@{self.protocol.hostname}:{cwd}"
if not self.protocol.user.uid:
prompt += "# " # "Root" user
else:
prompt += "$ " # "Non-Root" user
self.protocol.terminal.write(prompt.encode("ascii"))
self.protocol.ps = (prompt.encode("ascii"), b"> ")
def eofReceived(self) -> None:
"""
this should probably not go through ctrl-d, but use processprotocol to close stdin
"""
log.msg("received eof, sending ctrl-d to command")
if self.protocol.cmdstack:
self.protocol.cmdstack[-1].handle_CTRL_D()
def handle_CTRL_C(self) -> None:
self.protocol.lineBuffer = []
self.protocol.lineBufferIndex = 0
self.protocol.terminal.write(b"\n")
self.showPrompt()
def handle_CTRL_D(self) -> None:
log.msg("Received CTRL-D, exiting..")
stat = failure.Failure(error.ProcessDone(status=""))
self.protocol.terminal.transport.processEnded(stat)
def handle_TAB(self) -> None:
"""
lineBuffer is an array of bytes
"""
if not self.protocol.lineBuffer:
return
line: bytes = b"".join(self.protocol.lineBuffer)
if line[-1:] == b" ":
clue = ""
else:
clue = line.split()[-1].decode("utf8")
# clue now contains the string to complete or is empty.
# line contains the buffer as bytes
try:
basedir = os.path.dirname(clue)
except Exception:
pass
if basedir and basedir[-1] != "/":
basedir += "/"
files = []
tmppath = basedir
if not basedir:
tmppath = self.protocol.cwd
try:
r = self.protocol.fs.resolve_path(tmppath, self.protocol.cwd)
except Exception:
return
for x in self.protocol.fs.get_path(r):
if clue == "":
files.append(x)
continue
if not x[fs.A_NAME].startswith(os.path.basename(clue)):
continue
files.append(x)
if not files:
return
# Clear early so we can call showPrompt if needed
for _i in range(self.protocol.lineBufferIndex):
self.protocol.terminal.cursorBackward()
self.protocol.terminal.deleteCharacter()
newbuf = ""
if len(files) == 1:
newbuf = " ".join(
line.decode("utf8").split()[:-1] + [f"{basedir}{files[0][fs.A_NAME]}"]
)
if files[0][fs.A_TYPE] == fs.T_DIR:
newbuf += "/"
else:
newbuf += " "
newbyt = newbuf.encode("utf8")
else:
if os.path.basename(clue):
prefix = os.path.commonprefix([x[fs.A_NAME] for x in files])
else:
prefix = ""
first = line.decode("utf8").split(" ")[:-1]
newbuf = " ".join([*first, f"{basedir}{prefix}"])
newbyt = newbuf.encode("utf8")
if newbyt == b"".join(self.protocol.lineBuffer):
self.protocol.terminal.write(b"\n")
maxlen = max(len(x[fs.A_NAME]) for x in files) + 1
perline = int(self.protocol.user.windowSize[1] / (maxlen + 1))
count = 0
for file in files:
if count == perline:
count = 0
self.protocol.terminal.write(b"\n")
self.protocol.terminal.write(
file[fs.A_NAME].ljust(maxlen).encode("utf8")
)
count += 1
self.protocol.terminal.write(b"\n")
self.showPrompt()
self.protocol.lineBuffer = [y for x, y in enumerate(iterbytes(newbyt))]
self.protocol.lineBufferIndex = len(self.protocol.lineBuffer)
self.protocol.terminal.write(newbyt)
class StdOutStdErrEmulationProtocol:
"""
Pipe support written by Dave Germiquet
Support for commands chaining added by Ivan Korolev (@fe7ch)
"""
__author__ = "davegermiquet"
def __init__(
self, protocol, cmd, cmdargs, input_data, next_command, redirect=False
):
self.cmd = cmd
self.cmdargs = cmdargs
self.input_data: bytes = input_data
self.next_command = next_command
self.data: bytes = b""
self.redirected_data: bytes = b""
self.err_data: bytes = b""
self.protocol = protocol
self.redirect = redirect # dont send to terminal if enabled
def connectionMade(self) -> None:
self.input_data = b""
def outReceived(self, data: bytes) -> None:
"""
Invoked when a command in the chain called 'write' method
If we have a next command, pass the data via input_data field
Else print data to the terminal
"""
self.data = data
if not self.next_command:
if not self.redirect:
if self.protocol is not None and self.protocol.terminal is not None:
self.protocol.terminal.write(data)
else:
log.msg("Connection was probably lost. Could not write to terminal")
else:
self.redirected_data += self.data
else:
if self.next_command.input_data is None:
self.next_command.input_data = self.data
else:
self.next_command.input_data += self.data
def insert_command(self, command):
"""
Insert the next command into the list.
"""
command.next_command = self.next_command
self.next_command = command
def errReceived(self, data: bytes) -> None:
if self.protocol and self.protocol.terminal:
self.protocol.terminal.write(data)
self.err_data = self.err_data + data
def inConnectionLost(self):
pass
def outConnectionLost(self):
"""
Called from HoneyPotBaseProtocol.call_command() to run a next command in the chain
"""
if self.next_command:
# self.next_command.input_data = self.data
npcmd = self.next_command.cmd
npcmdargs = self.next_command.cmdargs
self.protocol.call_command(self.next_command, npcmd, *npcmdargs)
def errConnectionLost(self):
pass
def processExited(self, reason):
log.msg(f"processExited for {self.cmd}, status {reason.value.exitCode}")
def processEnded(self, reason):
log.msg(f"processEnded for {self.cmd}, status {reason.value.exitCode}")
| 20,291 | 35.562162 | 113 | py |
cowrie | cowrie-master/src/cowrie/shell/customparser.py | from __future__ import annotations
import argparse
class OptionNotFound(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class ExitException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class CustomParser(argparse.ArgumentParser):
def __init__(
self,
protocol,
prog=None,
usage=None,
description=None,
epilog=None,
parents=None,
formatter_class=argparse.HelpFormatter,
prefix_chars="-",
fromfile_prefix_chars=None,
argument_default=None,
conflict_handler="error",
add_help=True,
):
self.protocol = protocol
if parents is None:
parents = []
super().__init__(
prog=prog,
usage=usage,
description=description,
epilog=epilog,
parents=parents,
formatter_class=formatter_class,
prefix_chars=prefix_chars,
fromfile_prefix_chars=fromfile_prefix_chars,
argument_default=argument_default,
conflict_handler=conflict_handler,
add_help=add_help,
)
def exit(self, status=0, message=None):
raise ExitException("Exiting...")
def _print_message(self, message, file=None):
super()._print_message(message, self.protocol)
def error(self, message):
self.print_usage(self.protocol)
raise OptionNotFound("Sorry no option found")
| 1,605 | 24.492063 | 56 | py |
cowrie | cowrie-master/src/cowrie/shell/command.py |
"""
This module contains code to run a command
"""
from __future__ import annotations
import os
import re
import shlex
import stat
import time
from typing import Optional
from collections.abc import Callable
from twisted.internet import error
from twisted.python import failure, log
from cowrie.core.config import CowrieConfig
from cowrie.shell import fs
class HoneyPotCommand:
"""
This is the super class for all commands in cowrie/commands
"""
safeoutfile: str = ""
def __init__(self, protocol, *args):
self.protocol = protocol
self.args = list(args)
self.environ = self.protocol.cmdstack[0].environ
self.fs = self.protocol.fs
self.data: bytes = b"" # output data
self.input_data: Optional[
bytes
] = None # used to store STDIN data passed via PIPE
self.writefn: Callable[[bytes], None] = self.protocol.pp.outReceived
self.errorWritefn: Callable[[bytes], None] = self.protocol.pp.errReceived
# MS-DOS style redirect handling, inside the command
# TODO: handle >>, 2>, etc
if ">" in self.args or ">>" in self.args:
if self.args[-1] in [">", ">>"]:
self.errorWrite("-bash: parse error near '\\n' \n")
return
self.writtenBytes = 0
self.writefn = self.write_to_file
if ">>" in self.args:
index = self.args.index(">>")
b_append = True
else:
index = self.args.index(">")
b_append = False
self.outfile = self.fs.resolve_path(
str(self.args[(index + 1)]), self.protocol.cwd
)
del self.args[index:]
p = self.fs.getfile(self.outfile)
if (
not p
or not p[fs.A_REALFILE]
or p[fs.A_REALFILE].startswith("honeyfs")
or not b_append
):
tmp_fname = "{}-{}-{}-redir_{}".format(
time.strftime("%Y%m%d-%H%M%S"),
self.protocol.getProtoTransport().transportId,
self.protocol.terminal.transport.session.id,
re.sub("[^A-Za-z0-9]", "_", self.outfile),
)
self.safeoutfile = os.path.join(
CowrieConfig.get("honeypot", "download_path"), tmp_fname
)
perm = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
try:
self.fs.mkfile(self.outfile, 0, 0, 0, stat.S_IFREG | perm)
except fs.FileNotFound:
# The outfile locates at a non-existing directory.
self.errorWrite(
f"-bash: {self.outfile}: No such file or directory\n"
)
self.writefn = self.write_to_failed
self.outfile = None
self.safeoutfile = ""
except fs.PermissionDenied:
# The outfile locates in a file-system that doesn't allow file creation
self.errorWrite(f"-bash: {self.outfile}: Permission denied\n")
self.writefn = self.write_to_failed
self.outfile = None
self.safeoutfile = ""
else:
with open(self.safeoutfile, "ab"):
self.fs.update_realfile(
self.fs.getfile(self.outfile), self.safeoutfile
)
else:
self.safeoutfile = p[fs.A_REALFILE]
def write(self, data: str) -> None:
"""
Write a string to the user on stdout
"""
self.writefn(data.encode("utf8"))
def writeBytes(self, data: bytes) -> None:
"""
Like write() but input is bytes
"""
self.writefn(data)
def errorWrite(self, data: str) -> None:
"""
Write errors to the user on stderr
"""
self.errorWritefn(data.encode("utf8"))
def check_arguments(self, application, args):
files = []
for arg in args:
path = self.fs.resolve_path(arg, self.protocol.cwd)
if self.fs.isdir(path):
self.errorWrite(
f"{application}: error reading `{arg}': Is a directory\n"
)
continue
files.append(path)
return files
def set_input_data(self, data: bytes) -> None:
self.input_data = data
def write_to_file(self, data: bytes) -> None:
with open(self.safeoutfile, "ab") as f:
f.write(data)
self.writtenBytes += len(data)
self.fs.update_size(self.outfile, self.writtenBytes)
def write_to_failed(self, data: bytes) -> None:
pass
def start(self) -> None:
if self.writefn != self.write_to_failed:
self.call()
self.exit()
def call(self) -> None:
self.write(f"Hello World! [{self.args!r}]\n")
def exit(self) -> None:
"""
Sometimes client is disconnected and command exits after. So cmdstack is gone
"""
if (
self.protocol
and self.protocol.terminal
and hasattr(self, "safeoutfile")
and self.safeoutfile
):
if hasattr(self, "outfile") and self.outfile:
self.protocol.terminal.redirFiles.add((self.safeoutfile, self.outfile))
else:
self.protocol.terminal.redirFiles.add((self.safeoutfile, ""))
if len(self.protocol.cmdstack):
self.protocol.cmdstack.pop()
if len(self.protocol.cmdstack):
self.protocol.cmdstack[-1].resume()
else:
ret = failure.Failure(error.ProcessDone(status=""))
# The session could be disconnected already, when his happens .transport is gone
try:
self.protocol.terminal.transport.processEnded(ret)
except AttributeError:
pass
def handle_CTRL_C(self) -> None:
log.msg("Received CTRL-C, exiting..")
self.write("^C\n")
self.exit()
def lineReceived(self, line: str) -> None:
log.msg(f"QUEUED INPUT: {line}")
# FIXME: naive command parsing, see lineReceived below
# line = "".join(line)
self.protocol.cmdstack[0].cmdpending.append(shlex.split(line, posix=True))
def resume(self) -> None:
pass
def handle_TAB(self) -> None:
pass
def handle_CTRL_D(self) -> None:
pass
def __repr__(self) -> str:
return str(self.__class__.__name__)
| 6,848 | 32.905941 | 92 | py |
cowrie | cowrie-master/src/cowrie/shell/session.py |
from __future__ import annotations
from zope.interface import implementer
from twisted.conch.interfaces import ISession
from twisted.conch.ssh import session
from twisted.python import log
from cowrie.insults import insults
from cowrie.shell import protocol
@implementer(ISession)
class SSHSessionForCowrieUser:
def __init__(self, avatar, reactor=None):
"""
Construct an C{SSHSessionForCowrieUser}.
@param avatar: The L{CowrieUser} for whom this is an SSH session.
@param reactor: An L{IReactorProcess} used to handle shell and exec
requests. Uses the default reactor if None.
"""
self.protocol = None
self.avatar = avatar
self.server = avatar.server
self.uid = avatar.uid
self.gid = avatar.gid
self.username = avatar.username
self.environ = {
"LOGNAME": self.username,
"SHELL": "/bin/bash",
"USER": self.username,
"HOME": self.avatar.home,
"TMOUT": "1800",
"UID": str(self.uid),
}
if self.uid == 0:
self.environ[
"PATH"
] = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else:
self.environ[
"PATH"
] = "/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
self.server.initFileSystem(self.avatar.home)
if self.avatar.temporary:
self.server.fs.mkdir(self.avatar.home, self.uid, self.gid, 4096, 755)
def openShell(self, processprotocol):
self.protocol = insults.LoggingServerProtocol(
protocol.HoneyPotInteractiveProtocol, self
)
self.protocol.makeConnection(processprotocol)
processprotocol.makeConnection(session.wrapProtocol(self.protocol))
def getPty(self, terminal, windowSize, attrs):
self.environ["TERM"] = terminal.decode("utf-8")
log.msg(
eventid="cowrie.client.size",
width=windowSize[1],
height=windowSize[0],
format="Terminal Size: %(width)s %(height)s",
)
self.windowSize = windowSize
def execCommand(self, processprotocol, cmd):
self.protocol = insults.LoggingServerProtocol(
protocol.HoneyPotExecProtocol, self, cmd
)
self.protocol.makeConnection(processprotocol)
processprotocol.makeConnection(session.wrapProtocol(self.protocol))
def closed(self) -> None:
"""
this is reliably called on both logout and disconnect
we notify the protocol here we lost the connection
"""
if self.protocol:
self.protocol.connectionLost("disconnected")
self.protocol = None
def eofReceived(self) -> None:
if self.protocol:
self.protocol.eofReceived()
def windowChanged(self, windowSize):
self.windowSize = windowSize
| 3,053 | 31.83871 | 81 | py |
cowrie | cowrie-master/src/cowrie/shell/protocol.py | # -*- test-case-name: cowrie.test.protocol -*-
from __future__ import annotations
import os
import socket
import sys
import time
import traceback
from twisted.conch import recvline
from twisted.conch.insults import insults
from twisted.internet import error
from twisted.protocols.policies import TimeoutMixin
from twisted.python import failure, log
import cowrie.commands
from cowrie.core.config import CowrieConfig
from cowrie.shell import command, honeypot
class HoneyPotBaseProtocol(insults.TerminalProtocol, TimeoutMixin):
"""
Base protocol for interactive and non-interactive use
"""
commands = {}
for c in cowrie.commands.__all__:
try:
module = __import__(
f"cowrie.commands.{c}", globals(), locals(), ["commands"]
)
commands.update(module.commands)
except ImportError as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
log.err(
"Failed to import command {}: {}: {}".format(
c,
e,
"".join(
traceback.format_exception(exc_type, exc_value, exc_traceback)
),
)
)
def __init__(self, avatar):
self.user = avatar
self.environ = avatar.environ
self.hostname: str = self.user.server.hostname
self.fs = self.user.server.fs
self.pp = None
self.logintime: float
self.realClientIP: str
self.realClientPort: int
self.kippoIP: str
self.clientIP: str
self.sessionno: int
self.factory = None
if self.fs.exists(self.user.avatar.home):
self.cwd = self.user.avatar.home
else:
self.cwd = "/"
self.data = None
self.password_input = False
self.cmdstack = []
def getProtoTransport(self):
"""
Due to protocol nesting differences, we need provide how we grab
the proper transport to access underlying SSH information. Meant to be
overridden for other protocols.
"""
return self.terminal.transport.session.conn.transport
def logDispatch(self, **args):
"""
Send log directly to factory, avoiding normal log dispatch
"""
args["sessionno"] = self.sessionno
self.factory.logDispatch(**args)
def connectionMade(self) -> None:
pt = self.getProtoTransport()
self.factory = pt.factory
self.sessionno = pt.transport.sessionno
self.realClientIP = pt.transport.getPeer().host
self.realClientPort = pt.transport.getPeer().port
self.logintime = time.time()
log.msg(eventid="cowrie.session.params", arch=self.user.server.arch)
timeout = CowrieConfig.getint("honeypot", "interactive_timeout", fallback=180)
self.setTimeout(timeout)
# Source IP of client in user visible reports (can be fake or real)
self.clientIP = CowrieConfig.get(
"honeypot", "fake_addr", fallback=self.realClientIP
)
# Source IP of server in user visible reports (can be fake or real)
if CowrieConfig.has_option("honeypot", "internet_facing_ip"):
self.kippoIP = CowrieConfig.get("honeypot", "internet_facing_ip")
else:
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("8.8.8.8", 80))
self.kippoIP = s.getsockname()[0]
except Exception:
self.kippoIP = "192.168.0.1"
def timeoutConnection(self) -> None:
"""
this logs out when connection times out
"""
ret = failure.Failure(error.ProcessTerminated(exitCode=1))
self.terminal.transport.processEnded(ret)
def connectionLost(self, reason):
"""
Called when the connection is shut down.
Clear any circular references here, and any external references to
this Protocol. The connection has been closed.
"""
self.setTimeout(None)
insults.TerminalProtocol.connectionLost(self, reason)
self.terminal = None # (this should be done by super above)
self.cmdstack = []
self.fs = None
self.pp = None
self.user = None
self.environ = None
def txtcmd(self, txt: str) -> object:
class Command_txtcmd(command.HoneyPotCommand):
def call(self):
log.msg(f'Reading txtcmd from "{txt}"')
with open(txt, encoding="utf-8") as f:
self.write(f.read())
return Command_txtcmd
def isCommand(self, cmd):
"""
Check if cmd (the argument of a command) is a command, too.
"""
return True if cmd in self.commands else False
def getCommand(self, cmd, paths):
if not cmd.strip():
return None
path = None
if cmd in self.commands:
return self.commands[cmd]
if cmd[0] in (".", "/"):
path = self.fs.resolve_path(cmd, self.cwd)
if not self.fs.exists(path):
return None
else:
for i in [f"{self.fs.resolve_path(x, self.cwd)}/{cmd}" for x in paths]:
if self.fs.exists(i):
path = i
break
txt = os.path.normpath(
"{}/txtcmds/{}".format(CowrieConfig.get("honeypot", "share_path"), path)
)
if os.path.exists(txt) and os.path.isfile(txt):
return self.txtcmd(txt)
if path in self.commands:
return self.commands[path]
log.msg(f"Can't find command {cmd}")
return None
def lineReceived(self, line: bytes) -> None:
"""
IMPORTANT
Before this, all data is 'bytes'. Here it converts to 'string' and
commands work with string rather than bytes.
"""
string = line.decode("utf8")
if self.cmdstack:
self.cmdstack[-1].lineReceived(string)
else:
log.msg(f"discarding input {string}")
def call_command(self, pp, cmd, *args):
self.pp = pp
obj = cmd(self, *args)
obj.set_input_data(pp.input_data)
self.cmdstack.append(obj)
obj.start()
if self.pp:
self.pp.outConnectionLost()
def uptime(self):
"""
Uptime
"""
pt = self.getProtoTransport()
r = time.time() - pt.factory.starttime
return r
def eofReceived(self) -> None:
# Shell received EOF, nicely exit
"""
TODO: this should probably not go through transport, but use processprotocol to close stdin
"""
ret = failure.Failure(error.ProcessTerminated(exitCode=0))
self.terminal.transport.processEnded(ret)
class HoneyPotExecProtocol(HoneyPotBaseProtocol):
# input_data is static buffer for stdin received from remote client
input_data = b""
def __init__(self, avatar, execcmd):
"""
IMPORTANT
Before this, execcmd is 'bytes'. Here it converts to 'string' and
commands work with string rather than bytes.
"""
try:
self.execcmd = execcmd.decode("utf8")
except UnicodeDecodeError:
log.err(f"Unusual execcmd: {execcmd!r}")
HoneyPotBaseProtocol.__init__(self, avatar)
def connectionMade(self) -> None:
HoneyPotBaseProtocol.connectionMade(self)
self.setTimeout(60)
self.cmdstack = [honeypot.HoneyPotShell(self, interactive=False)]
# TODO: quick and dirty fix to deal with \n separated commands
# HoneypotShell() needs a rewrite to better work with pending input
self.cmdstack[0].lineReceived("; ".join(self.execcmd.split("\n")))
def keystrokeReceived(self, keyID, modifier):
self.input_data += keyID
class HoneyPotInteractiveProtocol(HoneyPotBaseProtocol, recvline.HistoricRecvLine):
def __init__(self, avatar):
recvline.HistoricRecvLine.__init__(self)
HoneyPotBaseProtocol.__init__(self, avatar)
def connectionMade(self) -> None:
self.displayMOTD()
HoneyPotBaseProtocol.connectionMade(self)
recvline.HistoricRecvLine.connectionMade(self)
self.cmdstack = [honeypot.HoneyPotShell(self)]
self.keyHandlers.update(
{
b"\x01": self.handle_HOME, # CTRL-A
b"\x02": self.handle_LEFT, # CTRL-B
b"\x03": self.handle_CTRL_C, # CTRL-C
b"\x04": self.handle_CTRL_D, # CTRL-D
b"\x05": self.handle_END, # CTRL-E
b"\x06": self.handle_RIGHT, # CTRL-F
b"\x08": self.handle_BACKSPACE, # CTRL-H
b"\x09": self.handle_TAB,
b"\x0b": self.handle_CTRL_K, # CTRL-K
b"\x0c": self.handle_CTRL_L, # CTRL-L
b"\x0e": self.handle_DOWN, # CTRL-N
b"\x10": self.handle_UP, # CTRL-P
b"\x15": self.handle_CTRL_U, # CTRL-U
b"\x16": self.handle_CTRL_V, # CTRL-V
b"\x1b": self.handle_ESC, # ESC
}
)
def displayMOTD(self) -> None:
try:
self.terminal.write(self.fs.file_contents("/etc/motd"))
except Exception:
pass
def timeoutConnection(self) -> None:
"""
this logs out when connection times out
"""
self.terminal.write(b"timed out waiting for input: auto-logout\n")
HoneyPotBaseProtocol.timeoutConnection(self)
def connectionLost(self, reason):
HoneyPotBaseProtocol.connectionLost(self, reason)
recvline.HistoricRecvLine.connectionLost(self, reason)
self.keyHandlers = {}
def initializeScreen(self) -> None:
"""
Overriding super to prevent terminal.reset()
"""
self.setInsertMode()
def call_command(self, pp, cmd, *args):
self.pp = pp
self.setTypeoverMode()
HoneyPotBaseProtocol.call_command(self, pp, cmd, *args)
def characterReceived(self, ch, moreCharactersComing):
"""
Easier way to implement password input?
"""
if self.mode == "insert":
self.lineBuffer.insert(self.lineBufferIndex, ch)
else:
self.lineBuffer[self.lineBufferIndex : self.lineBufferIndex + 1] = [ch]
self.lineBufferIndex += 1
if not self.password_input:
self.terminal.write(ch)
def handle_RETURN(self):
if len(self.cmdstack) == 1:
if self.lineBuffer:
self.historyLines.append(b"".join(self.lineBuffer))
self.historyPosition = len(self.historyLines)
return recvline.RecvLine.handle_RETURN(self)
def handle_CTRL_C(self) -> None:
if self.cmdstack:
self.cmdstack[-1].handle_CTRL_C()
def handle_CTRL_D(self) -> None:
if self.cmdstack:
self.cmdstack[-1].handle_CTRL_D()
def handle_TAB(self) -> None:
if self.cmdstack:
self.cmdstack[-1].handle_TAB()
def handle_CTRL_K(self) -> None:
self.terminal.eraseToLineEnd()
self.lineBuffer = self.lineBuffer[0 : self.lineBufferIndex]
def handle_CTRL_L(self) -> None:
"""
Handle a 'form feed' byte - generally used to request a screen
refresh/redraw.
"""
self.terminal.eraseDisplay()
self.terminal.cursorHome()
self.drawInputLine()
def handle_CTRL_U(self) -> None:
for _ in range(self.lineBufferIndex):
self.terminal.cursorBackward()
self.terminal.deleteCharacter()
self.lineBuffer = self.lineBuffer[self.lineBufferIndex :]
self.lineBufferIndex = 0
def handle_CTRL_V(self) -> None:
pass
def handle_ESC(self) -> None:
pass
class HoneyPotInteractiveTelnetProtocol(HoneyPotInteractiveProtocol):
"""
Specialized HoneyPotInteractiveProtocol that provides Telnet specific
overrides.
"""
def __init__(self, avatar):
HoneyPotInteractiveProtocol.__init__(self, avatar)
def getProtoTransport(self):
"""
Due to protocol nesting differences, we need to override how we grab
the proper transport to access underlying Telnet information.
"""
return self.terminal.transport.session.transport
| 12,602 | 31.820313 | 99 | py |
cowrie | cowrie-master/src/cowrie/ssh/userauth.py |
from __future__ import annotations
import struct
from typing import Any
from twisted.conch import error
from twisted.conch.interfaces import IConchUser
from twisted.conch.ssh import userauth
from twisted.conch.ssh.common import NS, getNS
from twisted.conch.ssh.transport import DISCONNECT_PROTOCOL_ERROR
from twisted.internet import defer
from twisted.python.failure import Failure
from cowrie.core import credentials
from cowrie.core.config import CowrieConfig
class HoneyPotSSHUserAuthServer(userauth.SSHUserAuthServer):
"""
This contains modifications to the authentication system to do:
* Login banners (like /etc/issue.net)
* Anonymous authentication
* Keyboard-interactive authentication (PAM)
* IP based authentication
"""
bannerSent: bool = False
user: str
_pamDeferred: defer.Deferred | None
def serviceStarted(self) -> None:
self.interfaceToMethod[credentials.IUsername] = b"none"
self.interfaceToMethod[credentials.IUsernamePasswordIP] = b"password"
keyboard: bool = CowrieConfig.getboolean(
"ssh", "auth_keyboard_interactive_enabled", fallback=False
)
if keyboard is True:
self.interfaceToMethod[
credentials.IPluggableAuthenticationModulesIP
] = b"keyboard-interactive"
self._pamDeferred: defer.Deferred | None = None
userauth.SSHUserAuthServer.serviceStarted(self)
def sendBanner(self):
"""
This is the pre-login banner. The post-login banner is the MOTD file
Display contents of <honeyfs>/etc/issue.net
"""
if self.bannerSent:
return
self.bannerSent = True
try:
issuefile = CowrieConfig.get("honeypot", "contents_path") + "/etc/issue.net"
with open(issuefile, "rb") as issue:
data = issue.read()
except OSError:
return
if not data or not data.strip():
return
self.transport.sendPacket(userauth.MSG_USERAUTH_BANNER, NS(data) + NS(b"en"))
def ssh_USERAUTH_REQUEST(self, packet: bytes) -> Any:
"""
This is overriden to send the login banner.
"""
self.sendBanner()
return userauth.SSHUserAuthServer.ssh_USERAUTH_REQUEST(self, packet)
# def auth_publickey(self, packet):
# """
# We subclass to intercept non-dsa/rsa keys,
# or Conch will crash on ecdsa..
# UPDATE: conch no longer crashes. comment this out
# """
# algName, blob, rest = getNS(packet[1:], 2)
# if algName not in (b'ssh-rsa', b'ssh-dsa'):
# log.msg("Attempted public key authentication\
# with {} algorithm".format(algName))
# return defer.fail(error.ConchError("Incorrect signature"))
# return userauth.SSHUserAuthServer.auth_publickey(self, packet)
def auth_none(self, _packet: bytes) -> Any:
"""
Allow every login
"""
c = credentials.Username(self.user)
srcIp: str = self.transport.transport.getPeer().host # type: ignore
return self.portal.login(c, srcIp, IConchUser)
def auth_password(self, packet: bytes) -> Any:
"""
Overridden to pass src_ip to credentials.UsernamePasswordIP
"""
password = getNS(packet[1:])[0]
srcIp = self.transport.transport.getPeer().host # type: ignore
c = credentials.UsernamePasswordIP(self.user, password, srcIp)
return self.portal.login(c, srcIp, IConchUser).addErrback(self._ebPassword)
def auth_keyboard_interactive(self, _packet: bytes) -> Any:
"""
Keyboard interactive authentication. No payload. We create a
PluggableAuthenticationModules credential and authenticate with our
portal.
Overridden to pass src_ip to
credentials.PluggableAuthenticationModulesIP
"""
if self._pamDeferred is not None:
self.transport.sendDisconnect( # type: ignore
DISCONNECT_PROTOCOL_ERROR,
"only one keyboard interactive attempt at a time",
)
return defer.fail(error.IgnoreAuthentication())
src_ip = self.transport.transport.getPeer().host # type: ignore
c = credentials.PluggableAuthenticationModulesIP(
self.user, self._pamConv, src_ip
)
return self.portal.login(c, src_ip, IConchUser).addErrback(self._ebPassword)
def _pamConv(self, items: list[tuple[Any, int]]) -> defer.Deferred:
"""
Convert a list of PAM authentication questions into a
MSG_USERAUTH_INFO_REQUEST. Returns a Deferred that will be called
back when the user has responses to the questions.
@param items: a list of 2-tuples (message, kind). We only care about
kinds 1 (password) and 2 (text).
@type items: C{list}
@rtype: L{defer.Deferred}
"""
resp = []
for message, kind in items:
if kind == 1: # Password
resp.append((message, 0))
elif kind == 2: # Text
resp.append((message, 1))
elif kind in (3, 4):
return defer.fail(error.ConchError("cannot handle PAM 3 or 4 messages"))
else:
return defer.fail(error.ConchError(f"bad PAM auth kind {kind}" ))
packet = NS(b"") + NS(b"") + NS(b"")
packet += struct.pack(">L", len(resp))
for prompt, echo in resp:
packet += NS(prompt)
packet += bytes((echo,))
self.transport.sendPacket(userauth.MSG_USERAUTH_INFO_REQUEST, packet) # type: ignore
self._pamDeferred = defer.Deferred()
return self._pamDeferred
def ssh_USERAUTH_INFO_RESPONSE(self, packet: bytes) -> None:
"""
The user has responded with answers to PAMs authentication questions.
Parse the packet into a PAM response and callback self._pamDeferred.
Payload::
uint32 numer of responses
string response 1
...
string response n
"""
d: defer.Deferred | None = self._pamDeferred
self._pamDeferred = None
resp: list
if not d:
raise Exception("can't find deferred in ssh_USERAUTH_INFO_RESPONSE")
try:
resp = []
numResps = struct.unpack(">L", packet[:4])[0]
packet = packet[4:]
while len(resp) < numResps:
response, packet = getNS(packet)
resp.append((response, 0))
if packet:
raise error.ConchError(f"{len(packet):d} bytes of extra data")
except Exception:
d.errback(Failure())
else:
d.callback(resp)
| 6,936 | 36.497297 | 93 | py |
cowrie | cowrie-master/src/cowrie/ssh/forwarding.py |
"""
This module contains code for handling SSH direct-tcpip connection requests
"""
from __future__ import annotations
from twisted.conch.ssh import forwarding
from twisted.python import log
from cowrie.core.config import CowrieConfig
def cowrieOpenConnectForwardingClient(remoteWindow, remoteMaxPacket, data, avatar):
"""
This function will redirect an SSH forward request to another address
or will log the request and do nothing
"""
remoteHP, origHP = forwarding.unpackOpen_direct_tcpip(data)
log.msg(
eventid="cowrie.direct-tcpip.request",
format="direct-tcp connection request to %(dst_ip)s:%(dst_port)s from %(src_ip)s:%(src_port)s",
dst_ip=remoteHP[0],
dst_port=remoteHP[1],
src_ip=origHP[0],
src_port=origHP[1],
)
# Forward redirect
redirectEnabled: bool = CowrieConfig.getboolean(
"ssh", "forward_redirect", fallback=False
)
if redirectEnabled:
redirects = {}
items = CowrieConfig.items("ssh")
for i in items:
if i[0].startswith("forward_redirect_"):
destPort = i[0].split("_")[-1]
redirectHP = i[1].split(":")
redirects[int(destPort)] = (redirectHP[0], int(redirectHP[1]))
if remoteHP[1] in redirects:
remoteHPNew = redirects[remoteHP[1]]
log.msg(
eventid="cowrie.direct-tcpip.redirect",
format="redirected direct-tcp connection request from %(src_ip)s:%(src_port)"
+ "d to %(dst_ip)s:%(dst_port)d to %(new_ip)s:%(new_port)d",
new_ip=remoteHPNew[0],
new_port=remoteHPNew[1],
dst_ip=remoteHP[0],
dst_port=remoteHP[1],
src_ip=origHP[0],
src_port=origHP[1],
)
return SSHConnectForwardingChannel(
remoteHPNew, remoteWindow=remoteWindow, remoteMaxPacket=remoteMaxPacket
)
# TCP tunnel
tunnelEnabled: bool = CowrieConfig.getboolean(
"ssh", "forward_tunnel", fallback=False
)
if tunnelEnabled:
tunnels = {}
items = CowrieConfig.items("ssh")
for i in items:
if i[0].startswith("forward_tunnel_"):
destPort = i[0].split("_")[-1]
tunnelHP = i[1].split(":")
tunnels[int(destPort)] = (tunnelHP[0], int(tunnelHP[1]))
if remoteHP[1] in tunnels:
remoteHPNew = tunnels[remoteHP[1]]
log.msg(
eventid="cowrie.direct-tcpip.tunnel",
format="tunneled direct-tcp connection request %(src_ip)s:%(src_port)"
+ "d->%(dst_ip)s:%(dst_port)d to %(new_ip)s:%(new_port)d",
new_ip=remoteHPNew[0],
new_port=remoteHPNew[1],
dst_ip=remoteHP[0],
dst_port=remoteHP[1],
src_ip=origHP[0],
src_port=origHP[1],
)
return TCPTunnelForwardingChannel(
remoteHPNew,
remoteHP,
remoteWindow=remoteWindow,
remoteMaxPacket=remoteMaxPacket,
)
return FakeForwardingChannel(
remoteHP, remoteWindow=remoteWindow, remoteMaxPacket=remoteMaxPacket
)
class SSHConnectForwardingChannel(forwarding.SSHConnectForwardingChannel):
"""
This class modifies the original to close the connection
"""
name = b"cowrie-forwarded-direct-tcpip"
def eofReceived(self) -> None:
self.loseConnection()
class FakeForwardingChannel(forwarding.SSHConnectForwardingChannel):
"""
This channel does not forward, but just logs requests.
"""
name = b"cowrie-discarded-direct-tcpip"
def channelOpen(self, specificData: bytes) -> None:
pass
def dataReceived(self, data: bytes) -> None:
log.msg(
eventid="cowrie.direct-tcpip.data",
format="discarded direct-tcp forward request %(id)s to %(dst_ip)s:%(dst_port)s with data %(data)s",
dst_ip=self.hostport[0],
dst_port=self.hostport[1],
data=repr(data),
id=self.id,
)
self._close("Connection refused")
class TCPTunnelForwardingChannel(forwarding.SSHConnectForwardingChannel):
"""
This class modifies the original to perform TCP tunneling via the CONNECT method
"""
name = b"cowrie-tunneled-direct-tcpip"
def __init__(self, hostport, dstport, *args, **kw):
"""
Modifies the original to store where the data was originally going to go
"""
forwarding.SSHConnectForwardingChannel.__init__(self, hostport, *args, **kw)
self.dstport = dstport
self.tunnel_established = False
def channelOpen(self, specificData: bytes) -> None:
"""
Modifies the original to send a TCP tunnel request via the CONNECT method
"""
forwarding.SSHConnectForwardingChannel.channelOpen(self, specificData)
dst = self.dstport[0] + ":" + str(self.dstport[1])
connect_hdr = b"CONNECT " + dst.encode("ascii") + b" HTTP/1.1\r\n\r\n"
forwarding.SSHConnectForwardingChannel.dataReceived(self, connect_hdr)
def dataReceived(self, data: bytes) -> None:
log.msg(
eventid="cowrie.tunnelproxy-tcpip.data",
format="sending via tunnel proxy %(data)s",
data=repr(data),
)
forwarding.SSHConnectForwardingChannel.dataReceived(self, data)
def write(self, data: bytes) -> None:
"""
Modifies the original to strip off the TCP tunnel response
"""
if not self.tunnel_established and data[:4].lower() == b"http":
# Check proxy response code
try:
res_code = int(data.split(b" ")[1], 10)
except ValueError:
log.err("Failed to parse TCP tunnel response code")
self._close("Connection refused")
if res_code != 200:
log.err(f"Unexpected response code: {res_code}")
self._close("Connection refused")
# Strip off rest of packet
eop = data.find(b"\r\n\r\n")
if eop > -1:
data = data[eop + 4 :]
# This only happens once when the channel is opened
self.tunnel_established = True
forwarding.SSHConnectForwardingChannel.write(self, data)
def eofReceived(self) -> None:
self.loseConnection()
| 6,655 | 34.404255 | 111 | py |
cowrie | cowrie-master/src/cowrie/ssh/keys.py |
"""
This module contains ...
"""
from __future__ import annotations
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from twisted.conch.ssh import keys
from twisted.python import log
from cowrie.core.config import CowrieConfig
def getRSAKeys():
publicKeyFile: str = CowrieConfig.get("ssh", "rsa_public_key")
privateKeyFile: str = CowrieConfig.get("ssh", "rsa_private_key")
if not (os.path.exists(publicKeyFile) and os.path.exists(privateKeyFile)):
log.msg("Generating new RSA keypair...")
rsaKey = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_backend()
)
publicKeyString = keys.Key(rsaKey).public().toString("openssh")
privateKeyString = keys.Key(rsaKey).toString("openssh")
with open(publicKeyFile, "w+b") as f:
f.write(publicKeyString)
with open(privateKeyFile, "w+b") as f:
f.write(privateKeyString)
else:
with open(publicKeyFile, "rb") as f:
publicKeyString = f.read()
with open(privateKeyFile, "rb") as f:
privateKeyString = f.read()
return publicKeyString, privateKeyString
def getDSAKeys():
publicKeyFile: str = CowrieConfig.get("ssh", "dsa_public_key")
privateKeyFile: str = CowrieConfig.get("ssh", "dsa_private_key")
if not (os.path.exists(publicKeyFile) and os.path.exists(privateKeyFile)):
log.msg("Generating new DSA keypair...")
dsaKey = dsa.generate_private_key(key_size=1024, backend=default_backend())
publicKeyString = keys.Key(dsaKey).public().toString("openssh")
privateKeyString = keys.Key(dsaKey).toString("openssh")
with open(publicKeyFile, "w+b") as f:
f.write(publicKeyString)
with open(privateKeyFile, "w+b") as f:
f.write(privateKeyString)
else:
with open(publicKeyFile, "rb") as f:
publicKeyString = f.read()
with open(privateKeyFile, "rb") as f:
privateKeyString = f.read()
return publicKeyString, privateKeyString
def getECDSAKeys():
publicKeyFile: str = CowrieConfig.get("ssh", "ecdsa_public_key")
privateKeyFile: str = CowrieConfig.get("ssh", "ecdsa_private_key")
if not (os.path.exists(publicKeyFile) and os.path.exists(privateKeyFile)):
log.msg("Generating new ECDSA keypair...")
ecdsaKey = ec.generate_private_key(ec.SECP256R1())
publicKeyString = keys.Key(ecdsaKey).public().toString("openssh")
privateKeyString = keys.Key(ecdsaKey).toString("openssh")
with open(publicKeyFile, "w+b") as f:
f.write(publicKeyString)
with open(privateKeyFile, "w+b") as f:
f.write(privateKeyString)
else:
with open(publicKeyFile, "rb") as f:
publicKeyString = f.read()
with open(privateKeyFile, "rb") as f:
privateKeyString = f.read()
return publicKeyString, privateKeyString
def geted25519Keys():
publicKeyFile: str = CowrieConfig.get("ssh", "ed25519_public_key")
privateKeyFile: str = CowrieConfig.get("ssh", "ed25519_private_key")
if not (os.path.exists(publicKeyFile) and os.path.exists(privateKeyFile)):
log.msg("Generating new ed25519 keypair...")
ed25519Key = Ed25519PrivateKey.generate()
publicKeyString = keys.Key(ed25519Key).public().toString("openssh")
privateKeyString = keys.Key(ed25519Key).toString("openssh")
with open(publicKeyFile, "w+b") as f:
f.write(publicKeyString)
with open(privateKeyFile, "w+b") as f:
f.write(privateKeyString)
else:
with open(publicKeyFile, "rb") as f:
publicKeyString = f.read()
with open(privateKeyFile, "rb") as f:
privateKeyString = f.read()
return publicKeyString, privateKeyString
| 4,224 | 38.12037 | 83 | py |
cowrie | cowrie-master/src/cowrie/ssh/connection.py | # All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# notice, this list of conditions and the following disclaimer.
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# products derived from this software without specific prior written
# permission.
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
"""
This module contains connection code to work around issues with the
Granados SSH client library.
"""
from __future__ import annotations
import struct
from twisted.conch.ssh import common, connection
from twisted.internet import defer
from twisted.python import log
class CowrieSSHConnection(connection.SSHConnection):
"""
Subclass this for a workaround for the Granados SSH library.
Channel request for openshell needs to return success immediatly
"""
def ssh_CHANNEL_REQUEST(self, packet):
localChannel = struct.unpack(">L", packet[:4])[0]
requestType, rest = common.getNS(packet[4:])
wantReply = ord(rest[0:1])
channel = self.channels[localChannel]
if requestType == b"shell":
wantReply = 0
self.transport.sendPacket(
connection.MSG_CHANNEL_SUCCESS,
struct.pack(">L", self.localToRemoteChannel[localChannel]),
)
d = defer.maybeDeferred(
log.callWithLogger, channel, channel.requestReceived, requestType, rest[1:]
)
if wantReply:
d.addCallback(self._cbChannelRequest, localChannel)
d.addErrback(self._ebChannelRequest, localChannel)
return d
| 2,731 | 38.594203 | 87 | py |
cowrie | cowrie-master/src/cowrie/ssh/channel.py |
"""
This module contains a subclass of SSHChannel with additional logging
and session size limiting
"""
from __future__ import annotations
import time
from twisted.conch.ssh import channel
from twisted.python import log
from cowrie.core import ttylog
from cowrie.core.config import CowrieConfig
class CowrieSSHChannel(channel.SSHChannel):
"""
This is an SSH channel with built-in logging
"""
ttylogFile: str = ""
bytesReceived: int = 0
bytesWritten: int = 0
name: bytes = b"cowrie-ssh-channel"
startTime: float = 0.0
ttylogPath: str = CowrieConfig.get("honeypot", "log_path")
downloadPath: str = CowrieConfig.get("honeypot", "download_path")
ttylogEnabled: bool = CowrieConfig.getboolean("honeypot", "ttylog", fallback=True)
bytesReceivedLimit: int = CowrieConfig.getint(
"honeypot", "download_limit_size", fallback=0
)
def __repr__(self) -> str:
"""
Return a pretty representation of this object.
@return Pretty representation of this object as a string
@rtype: L{str}
"""
return f"Cowrie SSH Channel {self.name.decode()}"
def __init__(self, *args, **kw):
"""
Initialize logging
"""
channel.SSHChannel.__init__(self, *args, **kw)
def channelOpen(self, specificData: bytes) -> None:
self.startTime = time.time()
self.ttylogFile = "{}/tty/{}-{}-{}.log".format(
self.ttylogPath,
time.strftime("%Y%m%d-%H%M%S"),
self.conn.transport.transportId,
self.id,
)
log.msg(
eventid="cowrie.log.open",
ttylog=self.ttylogFile,
format="Opening TTY Log: %(ttylog)s",
)
ttylog.ttylog_open(self.ttylogFile, time.time())
channel.SSHChannel.channelOpen(self, specificData)
def closed(self) -> None:
log.msg(
eventid="cowrie.log.closed",
format="Closing TTY Log: %(ttylog)s after %(duration)f seconds",
ttylog=self.ttylogFile,
size=self.bytesReceived + self.bytesWritten,
duration=time.time() - self.startTime,
)
ttylog.ttylog_close(self.ttylogFile, time.time())
channel.SSHChannel.closed(self)
def dataReceived(self, data: bytes) -> None:
"""
Called when we receive data from the user
@type data: L{bytes}
@param data: Data sent to the server from the client
"""
self.bytesReceived += len(data)
if self.bytesReceivedLimit and self.bytesReceived > self.bytesReceivedLimit:
log.msg(f"Data upload limit reached for channel {self.id}")
self.eofReceived()
return
if self.ttylogEnabled:
ttylog.ttylog_write(
self.ttylogFile, len(data), ttylog.TYPE_INPUT, time.time(), data
)
channel.SSHChannel.dataReceived(self, data)
def write(self, data: bytes) -> None:
"""
Called when we send data to the user
@type data: L{bytes}
@param data: Data sent to the client from the server
"""
if self.ttylogEnabled:
ttylog.ttylog_write(
self.ttylogFile, len(data), ttylog.TYPE_OUTPUT, time.time(), data
)
self.bytesWritten += len(data)
channel.SSHChannel.write(self, data)
| 3,510 | 29.798246 | 86 | py |
cowrie | cowrie-master/src/cowrie/ssh/factory.py |
"""
This module contains ...
"""
from __future__ import annotations
from configparser import NoOptionError
import time
from typing import Optional
from twisted.conch.openssh_compat import primes
from twisted.conch.ssh import factory, keys, transport
from twisted.cred import portal as tp
from twisted.python import log
from cowrie.core.config import CowrieConfig
from cowrie.ssh import connection
from cowrie.ssh import keys as cowriekeys
from cowrie.ssh import transport as shellTransport
from cowrie.ssh.userauth import HoneyPotSSHUserAuthServer
from cowrie.ssh_proxy import server_transport as proxyTransport
from cowrie.ssh_proxy.userauth import ProxySSHAuthServer
class CowrieSSHFactory(factory.SSHFactory):
"""
This factory creates HoneyPotSSHTransport instances
They listen directly to the TCP port
"""
starttime: Optional[float] = None
privateKeys: dict[bytes, bytes] = {}
publicKeys: dict[bytes, bytes] = {}
primes = None
portal: Optional[tp.Portal] = None # gets set by plugin
ourVersionString: bytes = CowrieConfig.get(
"ssh", "version", fallback="SSH-2.0-OpenSSH_6.0p1 Debian-4+deb7u2"
).encode("ascii")
def __init__(self, backend, pool_handler):
self.pool_handler = pool_handler
self.backend: str = backend
self.services = {
b"ssh-userauth": ProxySSHAuthServer
if self.backend == "proxy"
else HoneyPotSSHUserAuthServer,
b"ssh-connection": connection.CowrieSSHConnection,
}
super().__init__()
def logDispatch(self, **args):
"""
Special delivery to the loggers to avoid scope problems
"""
args["sessionno"] = "S{}".format(args["sessionno"])
for output in self.tac.output_plugins:
output.logDispatch(**args)
def startFactory(self):
# For use by the uptime command
self.starttime = time.time()
# Load/create keys
try:
public_key_auth = [
i.encode("utf-8")
for i in CowrieConfig.get("ssh", "public_key_auth").split(",")
]
except NoOptionError:
# no keys defined, use the three most common pub keys of OpenSSH
public_key_auth = [b"ssh-rsa", b"ecdsa-sha2-nistp256", b"ssh-ed25519"]
for key in public_key_auth:
if key == b"ssh-rsa":
rsaPubKeyString, rsaPrivKeyString = cowriekeys.getRSAKeys()
self.publicKeys[key] = keys.Key.fromString(data=rsaPubKeyString)
self.privateKeys[key] = keys.Key.fromString(data=rsaPrivKeyString)
elif key == b"ssh-dss":
dsaaPubKeyString, dsaPrivKeyString = cowriekeys.getDSAKeys()
self.publicKeys[key] = keys.Key.fromString(data=dsaaPubKeyString)
self.privateKeys[key] = keys.Key.fromString(data=dsaPrivKeyString)
elif key == b"ecdsa-sha2-nistp256":
ecdsaPuKeyString, ecdsaPrivKeyString = cowriekeys.getECDSAKeys()
self.publicKeys[key] = keys.Key.fromString(data=ecdsaPuKeyString)
self.privateKeys[key] = keys.Key.fromString(data=ecdsaPrivKeyString)
elif key == b"ssh-ed25519":
ed25519PubKeyString, ed25519PrivKeyString = cowriekeys.geted25519Keys()
self.publicKeys[key] = keys.Key.fromString(data=ed25519PubKeyString)
self.privateKeys[key] = keys.Key.fromString(data=ed25519PrivKeyString)
_modulis = "/etc/ssh/moduli", "/private/etc/moduli"
for _moduli in _modulis:
try:
self.primes = primes.parseModuliFile(_moduli)
break
except OSError:
pass
# this can come from backend in the future, check HonSSH's slim client
self.ourVersionString = CowrieConfig.get(
"ssh", "version", fallback="SSH-2.0-OpenSSH_6.0p1 Debian-4+deb7u2"
).encode("ascii")
factory.SSHFactory.startFactory(self)
log.msg("Ready to accept SSH connections")
def stopFactory(self):
factory.SSHFactory.stopFactory(self)
def buildProtocol(self, addr):
"""
Create an instance of the server side of the SSH protocol.
@type addr: L{twisted.internet.interfaces.IAddress} provider
@param addr: The address at which the server will listen.
@rtype: L{cowrie.ssh.transport.HoneyPotSSHTransport}
@return: The built transport.
"""
t: transport.SSHServerTransport
if self.backend == "proxy":
t = proxyTransport.FrontendSSHTransport()
else:
t = shellTransport.HoneyPotSSHTransport()
t.ourVersionString = self.ourVersionString
t.supportedPublicKeys = list(self.privateKeys.keys())
if not self.primes:
ske = t.supportedKeyExchanges[:]
if b"diffie-hellman-group-exchange-sha1" in ske:
ske.remove(b"diffie-hellman-group-exchange-sha1")
log.msg("No moduli, no diffie-hellman-group-exchange-sha1")
if b"diffie-hellman-group-exchange-sha256" in ske:
ske.remove(b"diffie-hellman-group-exchange-sha256")
log.msg("No moduli, no diffie-hellman-group-exchange-sha256")
t.supportedKeyExchanges = ske
try:
t.supportedCiphers = [
i.encode("utf-8") for i in CowrieConfig.get("ssh", "ciphers").split(",")
]
except NoOptionError:
# Reorder supported ciphers to resemble current openssh more
t.supportedCiphers = [
b"aes128-ctr",
b"aes192-ctr",
b"aes256-ctr",
b"aes256-cbc",
b"aes192-cbc",
b"aes128-cbc",
b"3des-cbc",
b"blowfish-cbc",
b"cast128-cbc",
]
try:
t.supportedMACs = [
i.encode("utf-8") for i in CowrieConfig.get("ssh", "macs").split(",")
]
except NoOptionError:
# SHA1 and MD5 are considered insecure now. Use better algos
# like SHA-256 and SHA-384
t.supportedMACs = [
b"hmac-sha2-512",
b"hmac-sha2-384",
b"hmac-sha2-256",
b"hmac-sha1",
b"hmac-md5",
]
try:
t.supportedCompressions = [
i.encode("utf-8")
for i in CowrieConfig.get("ssh", "compression").split(",")
]
except NoOptionError:
t.supportedCompressions = [b"zlib@openssh.com", b"zlib", b"none"]
t.factory = self
return t
| 6,876 | 36.172973 | 88 | py |
cowrie | cowrie-master/src/cowrie/ssh/session.py |
"""
This module contains ...
"""
from __future__ import annotations
from twisted.conch.ssh import session
from twisted.conch.ssh.common import getNS
from twisted.python import log
class HoneyPotSSHSession(session.SSHSession):
"""
This is an SSH channel that's used for SSH sessions
"""
def __init__(self, *args, **kw):
session.SSHSession.__init__(self, *args, **kw)
def request_env(self, data: bytes) -> int:
name, rest = getNS(data)
value, rest = getNS(rest)
if rest:
raise ValueError("Bad data given in env request")
log.msg(
eventid="cowrie.client.var",
format="request_env: %(name)s=%(value)s",
name=name.decode("utf-8"),
value=value.decode("utf-8"),
)
# FIXME: This only works for shell, not for exec command
if self.session:
self.session.environ[name.decode("utf-8")] = value.decode("utf-8")
return 0
def request_agent(self, data: bytes) -> int:
log.msg(f"request_agent: {data!r}")
return 0
def request_x11_req(self, data: bytes) -> int:
log.msg(f"request_x11: {data!r}")
return 0
def closed(self) -> None:
"""
This is reliably called on session close/disconnect and calls the avatar
"""
session.SSHSession.closed(self)
self.client = None
def eofReceived(self) -> None:
"""
Redirect EOF to emulated shell. If shell is gone, then disconnect
"""
if self.session:
self.session.eofReceived()
else:
self.loseConnection()
def sendEOF(self) -> None:
"""
Utility function to request to send EOF for this session
"""
self.conn.sendEOF(self)
def sendClose(self) -> None:
"""
Utility function to request to send close for this session
"""
self.conn.sendClose(self)
def channelClosed(self) -> None:
log.msg("Called channelClosed in SSHSession")
| 2,160 | 26.705128 | 80 | py |
cowrie | cowrie-master/src/cowrie/ssh/transport.py |
"""
The lowest level SSH protocol. This handles the key negotiation, the
encryption and the compression. The transport layer is described in
RFC 4253.
"""
from __future__ import annotations
import re
import struct
import time
import uuid
import zlib
from hashlib import md5
from typing import Any
from twisted.conch.ssh import transport
from twisted.conch.ssh.common import getNS
from twisted.protocols.policies import TimeoutMixin
from twisted.python import log, randbytes
from cowrie.core.config import CowrieConfig
class HoneyPotSSHTransport(transport.SSHServerTransport, TimeoutMixin):
startTime: float = 0.0
gotVersion: bool = False
buf: bytes
transportId: str
ipv4rex = re.compile(r"^::ffff:(\d+\.\d+\.\d+\.\d+)$")
auth_timeout: int = CowrieConfig.getint(
"honeypot", "authentication_timeout", fallback=120
)
interactive_timeout: int = CowrieConfig.getint(
"honeypot", "interactive_timeout", fallback=300
)
ourVersionString: bytes # set by factory
transport: Any
outgoingCompression: Any
_blockedByKeyExchange: Any
def __repr__(self) -> str:
"""
Return a pretty representation of this object.
@return Pretty representation of this object as a string
@rtype: L{str}
"""
return f"Cowrie SSH Transport to {self.transport.getPeer().host}"
def connectionMade(self) -> None:
"""
Called when the connection is made from the other side.
We send our version, but wait with sending KEXINIT
"""
self.buf = b""
self.transportId = uuid.uuid4().hex[:12]
src_ip: str = self.transport.getPeer().host
ipv4_search = self.ipv4rex.search(src_ip)
if ipv4_search is not None:
src_ip = ipv4_search.group(1)
log.msg(
eventid="cowrie.session.connect",
format="New connection: %(src_ip)s:%(src_port)s (%(dst_ip)s:%(dst_port)s) [session: %(session)s]",
src_ip=src_ip,
src_port=self.transport.getPeer().port,
dst_ip=self.transport.getHost().host,
dst_port=self.transport.getHost().port,
session=self.transportId,
sessionno=f"S{self.transport.sessionno}",
protocol="ssh",
)
self.transport.write(self.ourVersionString + b"\r\n")
self.currentEncryptions = transport.SSHCiphers(
b"none", b"none", b"none", b"none"
)
self.currentEncryptions.setKeys(b"", b"", b"", b"", b"", b"")
self.startTime: float = time.time()
self.setTimeout(self.auth_timeout)
def sendKexInit(self) -> None:
"""
Don't send key exchange prematurely
"""
if not self.gotVersion:
return
transport.SSHServerTransport.sendKexInit(self)
def _unsupportedVersionReceived(self, remoteVersion: bytes) -> None:
"""
Change message to be like OpenSSH
"""
self.transport.write(b"Protocol major versions differ.\n")
self.transport.loseConnection()
def dataReceived(self, data: bytes) -> None:
"""
First, check for the version string (SSH-2.0-*). After that has been
received, this method adds data to the buffer, and pulls out any
packets.
@type data: C{str}
"""
self.buf = self.buf + data
if not self.gotVersion:
if b"\n" not in self.buf:
return
self.otherVersionString: bytes = self.buf.split(b"\n")[0].strip()
log.msg(
eventid="cowrie.client.version",
version=self.otherVersionString.decode(
"utf-8", errors="backslashreplace"
),
format="Remote SSH version: %(version)s",
)
m = re.match(rb"SSH-(\d+.\d+)-(.*)", self.otherVersionString)
if m is None:
log.msg(
f"Bad protocol version identification: {self.otherVersionString!r}"
)
# OpenSSH sending the same message
self.transport.write(b"Invalid SSH identification string.\n")
self.transport.loseConnection()
return
self.gotVersion = True
remote_version = m.group(1)
if remote_version not in self.supportedVersions:
self._unsupportedVersionReceived(self.otherVersionString)
return
i = self.buf.index(b"\n")
self.buf = self.buf[i + 1 :]
self.sendKexInit()
packet = self.getPacket()
while packet:
messageNum = ord(packet[0:1])
self.dispatchMessage(messageNum, packet[1:])
packet = self.getPacket()
def dispatchMessage(self, messageNum: int, payload: bytes) -> None:
transport.SSHServerTransport.dispatchMessage(self, messageNum, payload)
def sendPacket(self, messageType: int, payload: bytes) -> None:
"""
Override because OpenSSH pads with 0 on KEXINIT
"""
if self._keyExchangeState != self._KEY_EXCHANGE_NONE:
if not self._allowedKeyExchangeMessageType(messageType):
self._blockedByKeyExchange.append((messageType, payload))
return
payload = bytes((messageType,)) + payload
if self.outgoingCompression:
payload = self.outgoingCompression.compress(
payload
) + self.outgoingCompression.flush(2)
bs = self.currentEncryptions.encBlockSize
# 4 for the packet length and 1 for the padding length
totalSize = 5 + len(payload)
lenPad = bs - (totalSize % bs)
if lenPad < 4:
lenPad = lenPad + bs
padding: bytes
if messageType == transport.MSG_KEXINIT:
padding = b"\0" * lenPad
else:
padding = randbytes.secureRandom(lenPad)
packet = struct.pack(b"!LB", totalSize + lenPad - 4, lenPad) + payload + padding
encPacket = self.currentEncryptions.encrypt(
packet
) + self.currentEncryptions.makeMAC(self.outgoingPacketSequence, packet)
self.transport.write(encPacket)
self.outgoingPacketSequence += 1
def ssh_KEXINIT(self, packet: bytes) -> Any:
k = getNS(packet[16:], 10)
strings, _ = k[:-1], k[-1]
(kexAlgs, keyAlgs, encCS, _, macCS, _, compCS, _, langCS, _) = (
s.split(b",") for s in strings
)
# hassh SSH client fingerprint
ckexAlgs = ",".join([alg.decode("utf-8") for alg in kexAlgs])
cencCS = ",".join([alg.decode("utf-8") for alg in encCS])
cmacCS = ",".join([alg.decode("utf-8") for alg in macCS])
ccompCS = ",".join([alg.decode("utf-8") for alg in compCS])
hasshAlgorithms = f"{ckexAlgs};{cencCS};{cmacCS};{ccompCS}"
hassh = md5(hasshAlgorithms.encode("utf-8")).hexdigest()
log.msg(
eventid="cowrie.client.kex",
format="SSH client hassh fingerprint: %(hassh)s",
hassh=hassh,
hasshAlgorithms=hasshAlgorithms,
kexAlgs=kexAlgs,
keyAlgs=keyAlgs,
encCS=encCS,
macCS=macCS,
compCS=compCS,
langCS=langCS,
)
return transport.SSHServerTransport.ssh_KEXINIT(self, packet)
def timeoutConnection(self) -> None:
"""
Make sure all sessions time out eventually.
Timeout is reset when authentication succeeds.
"""
log.msg("Timeout reached in HoneyPotSSHTransport")
self.transport.loseConnection()
def setService(self, service):
"""
Remove login grace timeout, set zlib compression after auth
"""
# Reset timeout. Not everyone opens shell so need timeout at transport level
if service.name == b"ssh-connection":
self.setTimeout(self.interactive_timeout)
# when auth is successful we enable compression
# this is called right after MSG_USERAUTH_SUCCESS
if service.name == b"ssh-connection":
if self.outgoingCompressionType == b"zlib@openssh.com":
self.outgoingCompression = zlib.compressobj(6)
if self.incomingCompressionType == b"zlib@openssh.com":
self.incomingCompression = zlib.decompressobj()
transport.SSHServerTransport.setService(self, service)
def connectionLost(self, reason):
"""
This seems to be the only reliable place of catching lost connection
"""
self.setTimeout(None)
transport.SSHServerTransport.connectionLost(self, reason)
self.transport.connectionLost(reason)
self.transport = None
duration = time.time() - self.startTime
log.msg(
eventid="cowrie.session.closed",
format="Connection lost after %(duration)d seconds",
duration=duration,
)
def sendDisconnect(self, reason, desc):
"""
http://kbyte.snowpenguin.org/portal/2013/04/30/kippo-protocol-mismatch-workaround/
Workaround for the "bad packet length" error message.
@param reason: the reason for the disconnect. Should be one of the
DISCONNECT_* values.
@type reason: C{int}
@param desc: a description of the reason for the disconnection.
@type desc: C{str}
"""
if b"bad packet length" not in desc:
transport.SSHServerTransport.sendDisconnect(self, reason, desc)
else:
# this message is used to detect Cowrie behaviour
# self.transport.write(b"Packet corrupt\n")
log.msg(
f"[SERVER] - Disconnecting with error, code {reason} reason: {desc}"
)
self.transport.loseConnection()
def receiveError(self, reasonCode, description):
"""
Called when we receive a disconnect error message from the other side.
@param reasonCode: the reason for the disconnect, one of the
DISCONNECT_ values.
@type reasonCode: L{int}
@param description: a human-readable description of the
disconnection.
@type description: L{str}
"""
log.msg(f"Got remote error, code {reasonCode} reason: {description}")
| 10,587 | 35.763889 | 110 | py |
cowrie | cowrie-master/src/backend_pool/telnet_exec.py | from __future__ import annotations
import re
from typing import Optional
from twisted.conch.telnet import StatefulTelnetProtocol, TelnetTransport
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet.protocol import ClientFactory
from twisted.python import log
class TelnetConnectionError(Exception):
pass
class TelnetClient(StatefulTelnetProtocol):
def __init__(self):
# output from server
self.response: bytes = b""
# callLater instance to wait until we have stop getting output for some time
self.done_callback = None
self.command: Optional[bytes] = None
def connectionMade(self):
"""
Set rawMode since we do not receive the login and password prompt in line mode.
We return to default line mode when we detect the prompt in the received data stream.
"""
self.setRawMode()
def rawDataReceived(self, data):
"""
The login and password prompt on some systems are not received in lineMode.
Therefore we do the authentication in raw mode and switch back to line mode
when we detect the shell prompt.
TODO: Need to handle authentication failure
"""
if self.factory.prompt.strip() == rb"#":
self.re_prompt = re.compile(rb"#")
else:
self.re_prompt = re.compile(self.factory.prompt.encode())
if re.search(rb"([Ll]ogin:\s+$)", data):
self.sendLine(self.factory.username.encode())
elif re.search(rb"([Pp]assword:\s+$)", data):
self.sendLine(self.factory.password.encode())
elif self.re_prompt.search(data):
self.setLineMode()
# auth is done, send command to server
self.send_command(self.transport.factory.command)
def lineReceived(self, line: bytes) -> None:
# ignore data sent by server before command is sent
# ignore command echo from server
if not self.command or line == self.command:
return
# trim control characters
if line.startswith(b"\x1b"):
line = line[4:]
self.response += line + b"\r\n"
# start countdown to command done (when reached, consider the output was completely received and close)
if not self.done_callback:
self.done_callback = reactor.callLater(0.5, self.close) # type: ignore
else:
self.done_callback.reset(0.5)
def send_command(self, command: str) -> None:
"""
Sends a command via Telnet using line mode
"""
self.command = command.encode()
self.sendLine(self.command) # ignore: attr-defined
def close(self):
"""
Sends exit to the Telnet server and closes connection.
Fires the deferred with the command's output.
"""
self.sendLine(b"exit")
self.transport.loseConnection()
# deferred to signal command's output was fully received
self.factory.done_deferred.callback(self.response)
# call the request client callback, if any
if self.factory.callback:
self.factory.callback(self.response)
class TelnetFactory(ClientFactory):
def __init__(self, username, password, prompt, command, done_deferred, callback):
self.username = username
self.password = password
self.prompt = prompt
self.command = command
# called on command done
self.done_deferred = done_deferred
self.callback = callback
def buildProtocol(self, addr):
transport = TelnetTransport(TelnetClient)
transport.factory = self
return transport
def clientConnectionFailed(self, connector, reason):
log.err(f"Telnet connection failed. Reason: {reason}")
class TelnetClientCommand:
def __init__(self, callback, prompt, command):
# callback to be called when execution is done
self.callback = callback
self.prompt = prompt
self.command = command
def connect(self, host, port, username, password):
# deferred to signal command and its output is done
done_deferred: defer.Deferred = defer.Deferred()
# start connection to the Telnet server
factory = TelnetFactory(
username, password, self.prompt, self.command, done_deferred, self.callback
)
reactor.connectTCP(host, port, factory)
return done_deferred
def execute_telnet(host, port, username, password, command, callback=None):
"""
Executes a command over Telnet. For that, it performs authentication beforehand,
and waits some time to get all of the output (slow machines might need the time
parameter adjusted.
Returns a deferred that is fired upon receiving the command's output.
"""
telnet = TelnetClientCommand(callback, ":~#", command)
return telnet.connect(host, port, username, password)
| 5,024 | 32.952703 | 111 | py |
cowrie | cowrie-master/src/backend_pool/nat.py | from __future__ import annotations
from threading import Lock
from twisted.internet import protocol
from twisted.internet import reactor
class ClientProtocol(protocol.Protocol):
def dataReceived(self, data: bytes) -> None:
self.server_protocol.transport.write(data) # type: ignore
def connectionLost(self, reason):
self.server_protocol.transport.loseConnection()
class ClientFactory(protocol.ClientFactory):
def __init__(self, server_protocol):
self.server_protocol = server_protocol
def buildProtocol(self, addr):
client_protocol = ClientProtocol()
client_protocol.server_protocol = self.server_protocol
self.server_protocol.client_protocol = client_protocol
return client_protocol
class ServerProtocol(protocol.Protocol):
def __init__(self, dst_ip, dst_port):
self.dst_ip = dst_ip
self.dst_port = dst_port
self.client_protocol = None
self.buffer = []
def connectionMade(self):
reactor.connectTCP(self.dst_ip, self.dst_port, ClientFactory(self))
def dataReceived(self, data):
self.buffer.append(data)
self.sendData()
def sendData(self):
if not self.client_protocol:
reactor.callLater(0.5, self.sendData)
return
for packet in self.buffer:
self.client_protocol.transport.write(packet)
self.buffer = []
def connectionLost(self, reason):
if self.client_protocol:
self.client_protocol.transport.loseConnection()
class ServerFactory(protocol.Factory):
def __init__(self, dst_ip: str, dst_port: int) -> None:
self.dst_ip: str = dst_ip
self.dst_port: int = dst_port
def buildProtocol(self, addr):
return ServerProtocol(self.dst_ip, self.dst_port)
class NATService:
"""
This service provides a NAT-like service when the backend pool is located in a remote machine.
Guests are bound to a local IP (e.g., 192.168.150.0/24), and so not accessible from a remote Cowrie.
This class provides TCP proxies that associate accessible IPs in the backend pool's machine to the internal
IPs used by guests, like a NAT.
"""
def __init__(self):
self.bindings = {}
self.lock = (
Lock()
) # we need to be thread-safe just in case, this is accessed from multiple clients
def request_binding(self, guest_id, dst_ip, ssh_port, telnet_port):
self.lock.acquire()
try:
# see if binding is already created
if guest_id in self.bindings:
# increase connected
self.bindings[guest_id][0] += 1
return (
self.bindings[guest_id][1]._realPortNumber,
self.bindings[guest_id][2]._realPortNumber,
)
else:
nat_ssh = reactor.listenTCP(
0, ServerFactory(dst_ip, ssh_port), interface="0.0.0.0"
)
nat_telnet = reactor.listenTCP(
0, ServerFactory(dst_ip, telnet_port), interface="0.0.0.0"
)
self.bindings[guest_id] = [1, nat_ssh, nat_telnet]
return nat_ssh._realPortNumber, nat_telnet._realPortNumber
finally:
self.lock.release()
def free_binding(self, guest_id):
self.lock.acquire()
try:
self.bindings[guest_id][0] -= 1
# stop listening if no one is connected
if self.bindings[guest_id][0] <= 0:
self.bindings[guest_id][1].stopListening()
self.bindings[guest_id][2].stopListening()
del self.bindings[guest_id]
finally:
self.lock.release()
def free_all(self):
self.lock.acquire()
try:
for guest_id in self.bindings:
self.bindings[guest_id][1].stopListening()
self.bindings[guest_id][2].stopListening()
finally:
self.lock.release()
| 4,059 | 31.48 | 111 | py |
cowrie | cowrie-master/src/backend_pool/ssh_exec.py | from __future__ import annotations
from twisted.conch.ssh import channel, common, connection, transport, userauth
from twisted.internet import defer, protocol
from twisted.internet import reactor
class PasswordAuth(userauth.SSHUserAuthClient):
def __init__(self, user, password, conn):
super().__init__(user, conn)
self.password = password
def getPassword(self, prompt=None):
return defer.succeed(self.password)
class CommandChannel(channel.SSHChannel):
name = b"session"
def __init__(self, command, done_deferred, callback, *args, **kwargs):
super().__init__(*args, **kwargs)
self.command = command
self.done_deferred = done_deferred
self.callback = callback
self.data = b""
def channelOpen(self, data):
self.conn.sendRequest(self, "exec", common.NS(self.command), wantReply=True)
def dataReceived(self, data: bytes) -> None:
self.data += data
def extReceived(self, dataType, data):
self.data += data
def closeReceived(self):
self.conn.transport.loseConnection()
self.done_deferred.callback(self.data)
# call the request client callback, if any
if self.callback:
self.callback(self.data)
class ClientConnection(connection.SSHConnection):
def __init__(self, cmd, done_deferred, callback):
super().__init__()
self.command = cmd
self.done_deferred = done_deferred
self.callback = callback
def serviceStarted(self):
self.openChannel(
CommandChannel(self.command, self.done_deferred, self.callback, conn=self)
)
class ClientCommandTransport(transport.SSHClientTransport):
def __init__(self, username, password, command, done_deferred, callback):
self.username = username
self.password = password
self.command = command
self.done_deferred = done_deferred
self.callback = callback
def verifyHostKey(self, pub_key, fingerprint):
return defer.succeed(True)
def connectionSecure(self):
self.requestService(
PasswordAuth(
self.username,
self.password,
ClientConnection(self.command, self.done_deferred, self.callback),
)
)
class ClientCommandFactory(protocol.ClientFactory):
def __init__(self, username, password, command, done_deferred, callback):
self.username = username
self.password = password
self.command = command
self.done_deferred = done_deferred
self.callback = callback
def buildProtocol(self, addr):
return ClientCommandTransport(
self.username,
self.password,
self.command,
self.done_deferred,
self.callback,
)
def execute_ssh(host, port, username, password, command, callback=None):
done_deferred = defer.Deferred()
factory = ClientCommandFactory(username, password, command, done_deferred, callback)
reactor.connectTCP(host, port, factory)
return done_deferred
| 3,114 | 28.666667 | 88 | py |