Skip to content

Commit ecf94bd

Browse files
gg-gvaladonguedou
authored andcommitted
Sessions removed
1 parent e762b8a commit ecf94bd

File tree

4 files changed

+10
-251
lines changed

4 files changed

+10
-251
lines changed

doc/scapy.1

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,7 @@ arping, tcpdump, tshark, p0f, ...
1717
.PP
1818
\fBScapy\fP uses the Python interpreter as a command board. That means that
1919
you can use directly Python language (assign variables, use loops,
20-
define functions, etc.) If you give a file a parameter when you run
21-
\fBScapy\fP, your session (variables, functions, instances, ...) will be saved
22-
when you leave the interpreter and restored the next time you launch
23-
\fBScapy\fP.
20+
define functions, etc.)
2421
.PP
2522
The idea is simple. Those kinds of tools do two things : sending packets
2623
and receiving answers. That's what \fBScapy\fP does : you define a set of
@@ -48,9 +45,6 @@ header-less mode, also reduces verbosity.
4845
\fB\-d\fR
4946
increase log verbosity. Can be used many times.
5047
.TP
51-
\fB\-s\fR FILE
52-
use FILE to save/load session values (variables, functions, instances, ...)
53-
.TP
5448
\fB\-p\fR PRESTART_FILE
5549
use PRESTART_FILE instead of $HOME/.config/scapy/prestart.py as pre-startup file
5650
.TP

doc/scapy/usage.rst

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -991,24 +991,6 @@ We can reimport the produced binary string by selecting the appropriate first la
991991
\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e
992992
\x1f !"#$%&\'()*+,-./01234567' |>>>>
993993

994-
Sessions
995-
^^^^^^^^
996-
997-
At last Scapy is capable of saving all session variables using the ``save_session()`` function:
998-
999-
>>> dir()
1000-
['__builtins__', 'conf', 'new_pkt', 'pkt', 'pkt_export', 'pkt_hex', 'pkt_raw', 'pkts']
1001-
>>> save_session("session.scapy")
1002-
1003-
Next time you start Scapy you can load the previous saved session using the ``load_session()`` command::
1004-
1005-
>>> dir()
1006-
['__builtins__', 'conf']
1007-
>>> load_session("session.scapy")
1008-
>>> dir()
1009-
['__builtins__', 'conf', 'new_pkt', 'pkt', 'pkt_export', 'pkt_hex', 'pkt_raw', 'pkts']
1010-
1011-
1012994
Making tables
1013995
-------------
1014996

scapy/main.py

Lines changed: 8 additions & 160 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,13 @@
1212
import code
1313
import getopt
1414
import glob
15-
import gzip
1615
import importlib
1716
import io
1817
import logging
1918
import os
2019
import pathlib
21-
import pickle
2220
import shutil
2321
import sys
24-
import types
2522
import warnings
2623

2724
from itertools import zip_longest
@@ -260,7 +257,7 @@ def _validate_local(k):
260257
def _usage():
261258
# type: () -> None
262259
print(
263-
"Usage: scapy.py [-s sessionfile] [-c new_startup_file] "
260+
"Usage: scapy.py [-c new_startup_file] "
264261
"[-p new_prestart_file] [-C] [-P] [-H]\n"
265262
"Args:\n"
266263
"\t-H: header-less start\n"
@@ -494,178 +491,35 @@ def _scapy_exts():
494491
return res
495492

496493

497-
def save_session(fname="", session=None, pickleProto=-1):
498-
# type: (str, Optional[Dict[str, Any]], int) -> None
499-
"""Save current Scapy session to the file specified in the fname arg.
500-
501-
params:
502-
- fname: file to save the scapy session in
503-
- session: scapy session to use. If None, the console one will be used
504-
- pickleProto: pickle proto version (default: -1 = latest)"""
505-
from scapy import utils
506-
from scapy.config import conf, ConfClass
507-
if not fname:
508-
fname = conf.session
509-
if not fname:
510-
conf.session = fname = utils.get_temp_file(keep=True)
511-
log_interactive.info("Saving session into [%s]", fname)
512-
513-
if not session:
514-
if conf.interactive_shell in ["ipython", "ptipython"]:
515-
from IPython import get_ipython
516-
session = get_ipython().user_ns
517-
else:
518-
session = builtins.__dict__["scapy_session"]
519-
520-
if not session:
521-
log_interactive.error("No session found ?!")
522-
return
523-
524-
ignore = session.get("_scpybuiltins", [])
525-
hard_ignore = ["scapy_session", "In", "Out", "open"]
526-
to_be_saved = session.copy()
527-
528-
for k in list(to_be_saved):
529-
i = to_be_saved[k]
530-
if k[0] == "_":
531-
del to_be_saved[k]
532-
elif hasattr(i, "__module__") and i.__module__.startswith("IPython"):
533-
del to_be_saved[k]
534-
elif isinstance(i, ConfClass):
535-
del to_be_saved[k]
536-
elif k in ignore or k in hard_ignore:
537-
del to_be_saved[k]
538-
elif isinstance(i, (type, types.ModuleType, types.FunctionType)):
539-
if k[0] != "_":
540-
log_interactive.warning("[%s] (%s) can't be saved.", k, type(i))
541-
del to_be_saved[k]
542-
else:
543-
try:
544-
pickle.dumps(i)
545-
except Exception:
546-
log_interactive.warning("[%s] (%s) can't be saved.", k, type(i))
547-
548-
try:
549-
os.rename(fname, fname + ".bak")
550-
except OSError:
551-
pass
552-
553-
f = gzip.open(fname, "wb")
554-
pickle.dump(to_be_saved, f, pickleProto)
555-
f.close()
556-
557-
558-
def load_session(fname=None):
559-
# type: (Optional[Union[str, None]]) -> None
560-
"""Load current Scapy session from the file specified in the fname arg.
561-
This will erase any existing session.
562-
563-
params:
564-
- fname: file to load the scapy session from"""
565-
from scapy.config import conf
566-
if fname is None:
567-
fname = conf.session
568-
try:
569-
s = pickle.load(gzip.open(fname, "rb"))
570-
except IOError:
571-
try:
572-
s = pickle.load(open(fname, "rb"))
573-
except IOError:
574-
# Raise "No such file exception"
575-
raise
576-
577-
scapy_session = builtins.__dict__["scapy_session"]
578-
s.update({k: scapy_session[k] for k in scapy_session["_scpybuiltins"]})
579-
scapy_session.clear()
580-
scapy_session.update(s)
581-
update_ipython_session(scapy_session)
582-
583-
log_loading.info("Loaded session [%s]", fname)
584-
585-
586-
def update_session(fname=None):
587-
# type: (Optional[Union[str, None]]) -> None
588-
"""Update current Scapy session from the file specified in the fname arg.
589-
590-
params:
591-
- fname: file to load the scapy session from"""
592-
from scapy.config import conf
593-
if fname is None:
594-
fname = conf.session
595-
try:
596-
s = pickle.load(gzip.open(fname, "rb"))
597-
except IOError:
598-
s = pickle.load(open(fname, "rb"))
599-
scapy_session = builtins.__dict__["scapy_session"]
600-
scapy_session.update(s)
601-
update_ipython_session(scapy_session)
602-
603-
604494
@overload
605-
def init_session(session_name, # type: Optional[Union[str, None]]
606-
mydict, # type: Optional[Union[Dict[str, Any], None]]
495+
def init_session(mydict, # type: Optional[Union[Dict[str, Any], None]]
607496
ret, # type: Literal[True]
608497
):
609498
# type: (...) -> Dict[str, Any]
610499
pass
611500

612501

613502
@overload
614-
def init_session(session_name, # type: Optional[Union[str, None]]
615-
mydict=None, # type: Optional[Union[Dict[str, Any], None]]
503+
def init_session(mydict=None, # type: Optional[Union[Dict[str, Any], None]]
616504
ret=False, # type: Literal[False]
617505
):
618506
# type: (...) -> None
619507
pass
620508

621509

622-
def init_session(session_name, # type: Optional[Union[str, None]]
623-
mydict=None, # type: Optional[Union[Dict[str, Any], None]]
510+
def init_session(mydict=None, # type: Optional[Union[Dict[str, Any], None]]
624511
ret=False, # type: bool
625512
):
626513
# type: (...) -> Union[Dict[str, Any], None]
627514
from scapy.config import conf
628-
SESSION = {} # type: Optional[Dict[str, Any]]
629515

630516
# Load Scapy
631517
scapy_builtins = _scapy_builtins()
632518

633519
# Load exts
634520
scapy_builtins.update(_scapy_exts())
635521

636-
if session_name:
637-
try:
638-
os.stat(session_name)
639-
except OSError:
640-
log_loading.info("New session [%s]", session_name)
641-
else:
642-
try:
643-
try:
644-
SESSION = pickle.load(gzip.open(session_name, "rb"))
645-
except IOError:
646-
SESSION = pickle.load(open(session_name, "rb"))
647-
log_loading.info("Using existing session [%s]", session_name)
648-
except ValueError:
649-
msg = "Error opening Python3 pickled session on Python2 [%s]"
650-
log_loading.error(msg, session_name)
651-
except EOFError:
652-
log_loading.error("Error opening session [%s]", session_name)
653-
except AttributeError:
654-
log_loading.error("Error opening session [%s]. "
655-
"Attribute missing", session_name)
656-
657-
if SESSION:
658-
if "conf" in SESSION:
659-
conf.configure(SESSION["conf"])
660-
conf.session = session_name
661-
SESSION["conf"] = conf
662-
else:
663-
conf.session = session_name
664-
else:
665-
conf.session = session_name
666-
SESSION = {"conf": conf}
667-
else:
668-
SESSION = {"conf": conf}
522+
SESSION = {"conf": conf} # type: Dict[str, Any]
669523

670524
SESSION.update(scapy_builtins)
671525
SESSION["_scpybuiltins"] = scapy_builtins.keys()
@@ -678,6 +532,7 @@ def init_session(session_name, # type: Optional[Union[str, None]]
678532
return SESSION
679533
return None
680534

535+
681536
################
682537
# Main #
683538
################
@@ -810,8 +665,6 @@ def interact(mydict=None,
810665
STARTUP_FILE = DEFAULT_STARTUP_FILE
811666
PRESTART_FILE = DEFAULT_PRESTART_FILE
812667

813-
session_name = None
814-
815668
if argv is None:
816669
argv = sys.argv
817670

@@ -824,8 +677,6 @@ def interact(mydict=None,
824677
conf.fancy_banner = False
825678
conf.verb = 1
826679
conf.logLevel = logging.WARNING
827-
elif opt == "-s":
828-
session_name = param
829680
elif opt == "-c":
830681
STARTUP_FILE = param
831682
elif opt == "-C":
@@ -857,7 +708,7 @@ def interact(mydict=None,
857708
default=DEFAULT_PRESTART,
858709
)
859710

860-
SESSION = init_session(session_name, mydict=mydict, ret=True)
711+
SESSION = init_session(mydict=mydict, ret=True)
861712

862713
if STARTUP_FILE:
863714
_read_config_file(
@@ -1090,13 +941,10 @@ def ptpython_configure(repl):
1090941
)
1091942
# Start Python
1092943
elif conf.interactive_shell == "python":
1093-
code.interact(banner=banner_text, local=SESSION)
944+
code.interact(banner=banner_text)
1094945
else:
1095946
raise ValueError("Invalid conf.interactive_shell")
1096947

1097-
if conf.session:
1098-
save_session(conf.session, SESSION)
1099-
1100948

1101949
if __name__ == "__main__":
1102950
interact()

test/regression.uts

Lines changed: 1 addition & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -625,72 +625,6 @@ try:
625625
except SystemExit:
626626
assert True
627627

628-
= Session test
629-
630-
import builtins
631-
632-
# This is automatic when using the console
633-
def get_var(var):
634-
return builtins.__dict__["scapy_session"][var]
635-
636-
def set_var(var, value):
637-
builtins.__dict__["scapy_session"][var] = value
638-
639-
def del_var(var):
640-
del builtins.__dict__["scapy_session"][var]
641-
642-
init_session(None, {"init_value": 123})
643-
set_var("test_value", "8.8.8.8") # test_value = "8.8.8.8"
644-
save_session()
645-
del_var("test_value")
646-
load_session()
647-
update_session()
648-
assert get_var("test_value") == "8.8.8.8" #test_value == "8.8.8.8"
649-
assert get_var("init_value") == 123
650-
651-
= Session test with fname
652-
653-
session_name = tempfile.mktemp()
654-
init_session(session_name)
655-
set_var("test_value", IP(dst="192.168.0.1")) # test_value = IP(dst="192.168.0.1")
656-
save_session(fname="%s.dat" % session_name)
657-
del_var("test_value")
658-
659-
set_var("z", True) #z = True
660-
load_session(fname="%s.dat" % session_name)
661-
try:
662-
get_var("z")
663-
assert False
664-
except:
665-
pass
666-
667-
set_var("z", False) #z = False
668-
update_session(fname="%s.dat" % session_name)
669-
assert get_var("test_value").dst == "192.168.0.1" #test_value.dst == "192.168.0.1"
670-
assert not get_var("z")
671-
672-
= Clear session files
673-
674-
os.remove("%s.dat" % session_name)
675-
676-
= Test temporary file creation
677-
~ ci_only
678-
679-
scapy_delete_temp_files()
680-
681-
tmpfile = get_temp_file(autoext=".ut")
682-
tmpfile
683-
if WINDOWS:
684-
assert "scapy" in tmpfile and "AppData\\Local\\Temp" in tmpfile
685-
else:
686-
import platform
687-
BYPASS_TMP = platform.python_implementation().lower() == "pypy" or DARWIN
688-
assert "scapy" in tmpfile and (BYPASS_TMP == True or "/tmp/" in tmpfile)
689-
690-
assert conf.temp_files[0].endswith(".ut")
691-
scapy_delete_temp_files()
692-
assert len(conf.temp_files) == 0
693-
694628
= Emulate interact()
695629
~ interact
696630

@@ -2181,6 +2115,7 @@ p.show()
21812115

21822116
= Variable creations
21832117
from io import BytesIO
2118+
import base64
21842119
pcapfile = BytesIO(b'\xd4\xc3\xb2\xa1\x02\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00e\x00\x00\x00\xcf\xc5\xacVo*\n\x00(\x00\x00\x00(\x00\x00\x00E\x00\x00(\x00\x01\x00\x00@\x06|\xcd\x7f\x00\x00\x01\x7f\x00\x00\x01\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00P\x02 \x00\x91|\x00\x00\xcf\xc5\xacV_-\n\x00\x1c\x00\x00\x00\x1c\x00\x00\x00E\x00\x00\x1c\x00\x01\x00\x00@\x11|\xce\x7f\x00\x00\x01\x7f\x00\x00\x01\x005\x005\x00\x08\x01r\xcf\xc5\xacV\xf90\n\x00\x1c\x00\x00\x00\x1c\x00\x00\x00E\x00\x00\x1c\x00\x01\x00\x00@\x01|\xde\x7f\x00\x00\x01\x7f\x00\x00\x01\x08\x00\xf7\xff\x00\x00\x00\x00')
21852120
pcapngfile = BytesIO(b'\n\r\r\n\\\x00\x00\x00M<+\x1a\x01\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00,\x00File created by merging: \nFile1: test.pcap \n\x04\x00\x08\x00mergecap\x00\x00\x00\x00\\\x00\x00\x00\x01\x00\x00\x00\\\x00\x00\x00e\x00\x00\x00\xff\xff\x00\x00\x02\x006\x00Unknown/not available in original file format(libpcap)\x00\x00\t\x00\x01\x00\x06\x00\x00\x00\x00\x00\x00\x00\\\x00\x00\x00\x06\x00\x00\x00H\x00\x00\x00\x00\x00\x00\x00\x8d*\x05\x00/\xfc[\xcd(\x00\x00\x00(\x00\x00\x00E\x00\x00(\x00\x01\x00\x00@\x06|\xcd\x7f\x00\x00\x01\x7f\x00\x00\x01\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00P\x02 \x00\x91|\x00\x00H\x00\x00\x00\x06\x00\x00\x00<\x00\x00\x00\x00\x00\x00\x00\x8d*\x05\x00\x1f\xff[\xcd\x1c\x00\x00\x00\x1c\x00\x00\x00E\x00\x00\x1c\x00\x01\x00\x00@\x11|\xce\x7f\x00\x00\x01\x7f\x00\x00\x01\x005\x005\x00\x08\x01r<\x00\x00\x00\x06\x00\x00\x00<\x00\x00\x00\x00\x00\x00\x00\x8d*\x05\x00\xb9\x02\\\xcd\x1c\x00\x00\x00\x1c\x00\x00\x00E\x00\x00\x1c\x00\x01\x00\x00@\x01|\xde\x7f\x00\x00\x01\x7f\x00\x00\x01\x08\x00\xf7\xff\x00\x00\x00\x00<\x00\x00\x00')
21862121
pcapnanofile = BytesIO(b"M<\xb2\xa1\x02\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00e\x00\x00\x00\xcf\xc5\xacV\xc9\xc1\xb5'(\x00\x00\x00(\x00\x00\x00E\x00\x00(\x00\x01\x00\x00@\x06|\xcd\x7f\x00\x00\x01\x7f\x00\x00\x01\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00P\x02 \x00\x91|\x00\x00\xcf\xc5\xacV-;\xc1'\x1c\x00\x00\x00\x1c\x00\x00\x00E\x00\x00\x1c\x00\x01\x00\x00@\x11|\xce\x7f\x00\x00\x01\x7f\x00\x00\x01\x005\x005\x00\x08\x01r\xcf\xc5\xacV\x9aL\xcf'\x1c\x00\x00\x00\x1c\x00\x00\x00E\x00\x00\x1c\x00\x01\x00\x00@\x01|\xde\x7f\x00\x00\x01\x7f\x00\x00\x01\x08\x00\xf7\xff\x00\x00\x00\x00")

0 commit comments

Comments
 (0)