Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
tftp_options,
options.localip)
try:
if options.download:
if not options.output:
options.output = os.path.basename(options.download)
tclient.download(options.download,
options.output,
progresshook)
elif options.upload:
if not options.input:
options.input = os.path.basename(options.upload)
tclient.upload(options.upload,
options.input,
progresshook)
except tftpy.TftpException as err:
sys.stderr.write("%s\n" % str(err))
sys.exit(1)
except KeyboardInterrupt:
pass
else:
error("Switch", raddress, "config =", switch, "tried to get file",
file_to_transfer)
f.close()
return None
f.seek(0)
return f
log("swtftpd started")
server = tftpy.TftpServer('/srv/tftp', file_callback)
tftplog = logging.getLogger('tftpy.TftpClient')
tftplog.setLevel(logging.WARN)
try:
server.listen("192.168.40.10", 69)
except tftpy.TftpException as err:
sys.stderr.write("%s\n" % str(err))
sys.exit(1)
except KeyboardInterrupt:
sys.stderr.write("\n")
% (self.context.host, self.context.port, raddress, rport)
)
# Return same state, we're still waiting for valid traffic.
return self
logger.debug("Requested filename is %s", pkt.filename)
if pkt.filename.startswith(self.context.root):
full_path = pkt.filename
else:
full_path = os.path.join(self.context.root, pkt.filename.lstrip("/"))
try:
logger.info("Full path of file to be uploaded is {}".format(full_path))
self.full_path = full_path
except fs.errors.FSError:
logger.warning("requested file is not within the server root - bad")
self.sendError(TftpErrors.IllegalTftpOp)
raise TftpException("Bad file path")
self.context.file_to_transfer = pkt.filename
return sendoack
def handle(self, pkt, raddress, rport):
"""Handle an initial RRQ packet as a server."""
logger.debug("In TftpStateServerRecvRRQ.handle")
sendoack = self.serverInitial(pkt, raddress, rport)
path = self.full_path
logger.info("Opening file %s for reading" % path)
if self.context.vfs.norm_path(path):
self.context.fileobj = self.context.vfs.open(
path.replace(self.context.root + "/", ""), "rb"
)
else:
logger.info("File not found: %s", path.replace(self.context.root + "/", ""))
self.sendError(TftpErrors.FileNotFound)
raise TftpException("File not found: {}".format(path))
# Options negotiation.
if sendoack and "tsize" in self.context.options:
# getting the file size for the tsize option. As we handle
# file-like objects and not only real files, we use this seeking
# method instead of asking the OS
self.context.fileobj.seek(0, os.SEEK_END)
tsize = str(self.context.fileobj.tell())
self.context.fileobj.seek(0, 0)
self.context.options["tsize"] = tsize
if sendoack:
# Note, next_block is 0 here since that's the proper
# acknowledgement to an OACK.
# FIXME: perhaps we do need a TftpStateExpectOACK class...
self.sendOACK()
)
)
logger.debug(
"TFTP serving list of files : {}".format(", ".join(self.vfs.listdir(".")))
)
self.root = "/" # Setup root dir.
# check for permissions etc.
logger.debug(
"TFTP root {} is a directory".format(self.vfs.getcwd() + self.root)
)
if self.vfs.access(self.root, 0, os.R_OK):
logger.debug(
"TFTP root {} is readable".format(self.vfs.getcwd() + self.root)
)
else:
raise TftpException("The TFTP root must be readable")
if self.vfs.access(self.root, 0, os.W_OK):
logger.debug(
"TFTP root {} is writable".format(self.vfs.getcwd() + self.root)
)
else:
logger.warning(
"The TFTP root {} is not writable".format(self.vfs.getcwd() + self.root)
)
"but we're in state %s" % (self.key, self.state))
self.errors += 1
# Next packet type
elif isinstance(recvpkt, TftpPacketACK):
logger.debug("Received an ACK from the client.")
if recvpkt.blocknumber == 0 and self.state.state == 'oack':
logger.debug("Received ACK with 0 blocknumber, starting download")
self.start_download()
else:
if self.state.state == 'dat' or self.state.state == 'fin':
if self.blocknumber == recvpkt.blocknumber:
logger.debug("Received ACK for block %d"
% recvpkt.blocknumber)
if self.state.state == 'fin':
raise TftpException, "Successful transfer."
else:
self.send_dat()
elif recvpkt.blocknumber < self.blocknumber:
logger.warn("Received old ACK for block number %d"
% recvpkt.blocknumber)
else:
logger.warn("Received ACK for block number "
"%d, apparently from the future"
% recvpkt.blocknumber)
else:
logger.error("Received ACK with block number %d "
"while in state %s"
% (recvpkt.blocknumber,
self.state.state))
elif isinstance(recvpkt, TftpPacketERR):
def handle(self, pkt, raddress, rport):
"""Handle a packet we just received."""
logger.debug("Using TFTPStateServerStart.handle")
if isinstance(pkt, TftpPacketRRQ):
logger.debug("Handling an RRQ packet")
return TFTPStateServerRecvRRQ(self.context).handle(pkt, raddress, rport)
elif isinstance(pkt, TftpPacketWRQ):
logger.debug("Handling a WRQ packet")
return TFTPStateServerRecvWRQ(self.context).handle(pkt, raddress, rport)
else:
self.sendError(tftpy.TftpErrors.IllegalTftpOp)
raise TftpException("Invalid packet to begin upload/download: %s" % pkt)
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://%s/%s' % (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()
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)