Skip to content

Commit

Permalink
Refactor code, Improve Readability and Add type hinting
Browse files Browse the repository at this point in the history
The commit contains several improvements over the current codebase in terms of following python code styling standards, adhering to DRY principles, and making the code more readable. A majority of the changes are of renaming methods and variables to follow the snake case naming convention as per PEP 8 & including decorators for property methods.

Type hinting is added where necessary providing better understanding of the type of data a function accepts or returns. This also improves tooling as it provides better autocomplete suggestions and early error detection.

Instead of traditional str concatenation using "+" operator, "f" string formatting syntax is used in many places for readability and better performance. Also exception handling is improved where required.

Python built-in functions like partition and startswith are used in place of more complex manual implementations.

Also, version is updated in setup.py and some required packages are added to requirements.txt. And removed some redundant whitespaces and added relevant comments where needed.
  • Loading branch information
L1ghtn1ng committed Aug 13, 2023
1 parent 88b49df commit 95f725b
Show file tree
Hide file tree
Showing 13 changed files with 360 additions and 380 deletions.
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ Ported from Python v2 to v3 by Jay Townsend (theHarvester, Discover, and DNSreco

Requirements:
```pip3 install -r requirements.txt```

Run as root to install or run it out of the directory:
```python3 setup.py install```
Install the requirements in a virtualenv

Running:
sslstrip can be run from the source base without installation.
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ setuptools==68.0.0
Twisted==22.10.0
pyopenssl==23.2.0
cryptography==41.0.3
service_identity==23.1.0
service_identity==23.1.0
black==23.7.0
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
shutil.copyfile("sslstrip.py", "sslstrip/sslstrip")

setup(name='sslstrip',
version='1.0',
version='2.0',
description='A MITM tool that implements Moxie Marlinspike\'s HTTPS stripping attacks.',
author='Moxie Marlinspike',
author_email='[email protected]',
Expand Down
153 changes: 80 additions & 73 deletions sslstrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,89 +24,96 @@
"""

from twisted.web import http
import argparse
import logging

from twisted.internet import reactor
from twisted.web import http

from sslstrip.CookieCleaner import CookieCleaner
from sslstrip.StrippingProxy import StrippingProxy
from sslstrip.URLMonitor import URLMonitor
from sslstrip.CookieCleaner import CookieCleaner

import sys, getopt, logging, traceback, string, os

gVersion = "1.0"


def usage():
print("\nsslstrip " + gVersion + " by Moxie Marlinspike")
print("Usage: sslstrip <options>\n")
print("Options:")
print("-w <filename>, --write=<filename> Specify file to log to (optional).")
print("-p , --post Log only SSL POSTs. (default)")
print("-s , --ssl Log all SSL traffic to and from server.")
print("-a , --all Log all SSL and HTTP traffic to and from server.")
print("-l <port>, --listen=<port> Port to listen on (default 10000).")
print("-f , --favicon Substitute a lock favicon on secure requests.")
print("-k , --killsessions Kill sessions in progress.")
print("-h Print this help message.")
print("")


def parseOptions(argv):
logFile = 'sslstrip.log'
logLevel = logging.WARNING
listenPort = 10000
spoofFavicon = False
killSessions = False

try:
opts, args = getopt.getopt(argv, "hw:l:psafk",
["help", "write=", "post", "ssl", "all", "listen=",
"favicon", "killsessions"])

for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-w", "--write"):
logFile = arg
elif opt in ("-p", "--post"):
logLevel = logging.WARNING
elif opt in ("-s", "--ssl"):
logLevel = logging.INFO
elif opt in ("-a", "--all"):
logLevel = logging.DEBUG
elif opt in ("-l", "--listen"):
listenPort = arg
elif opt in ("-f", "--favicon"):
spoofFavicon = True
elif opt in ("-k", "--killsessions"):
killSessions = True

return logFile, logLevel, listenPort, spoofFavicon, killSessions

except getopt.GetoptError:
usage()
sys.exit(2)


def main(argv):
(logFile, logLevel, listenPort, spoofFavicon, killSessions) = parseOptions(argv)

logging.basicConfig(level=logLevel, format='%(asctime)s %(message)s',
filename=logFile, filemode='w')

URLMonitor.getInstance().setFaviconSpoofing(spoofFavicon)
CookieCleaner.getInstance().setEnabled(killSessions)
class SSLStripConfig:
VERSION = "2.0"
DEFAULT_LOGFILE = "sslstrip.log"
DEFAULT_LOGLEVEL = logging.WARNING
DEFAULT_LISTEN_PORT = 10000
DEFAULT_SPOOF_FAVICON = False
DEFAULT_KILL_SESSIONS = False

strippingFactory = http.HTTPFactory(timeout=10)
strippingFactory.protocol = StrippingProxy

reactor.listenTCP(int(listenPort), strippingFactory)
def initialize_logger(logFile, logLevel):
logging.basicConfig(
level=logLevel, format="%(asctime)s %(message)s", filename=logFile, filemode="w"
)

print("\nsslstrip " + gVersion + " by Moxie Marlinspike running...")

def start_reactor(listenPort, spoofFavicon, killSessions):
URLMonitor.getInstance().setFaviconSpoofing(spoofFavicon)
CookieCleaner.getInstance().set_enabled(killSessions)
strippingFactory = http.HTTPFactory(timeout=10)
strippingFactory.protocol = StrippingProxy
reactor.listenTCP(int(listenPort), strippingFactory)
print(f"\nsslstrip {SSLStripConfig.VERSION} by Moxie Marlinspike running...")
reactor.run()


if __name__ == '__main__':
main(sys.argv[1:])
def main():
parser = argparse.ArgumentParser(description="sslstrip")
parser.add_argument(
"-w",
"--write",
default=SSLStripConfig.DEFAULT_LOGFILE,
help="Specify file to log to (optional).",
)
parser.add_argument(
"-p",
"--post",
default=False,
action="store_true",
help="Log only SSL POSTs. (default)",
)
parser.add_argument(
"-s",
"--ssl",
default=False,
action="store_true",
help="Log all SSL traffic to and from server.",
)
parser.add_argument(
"-a",
"--all",
default=False,
action="store_true",
help="Log all SSL and HTTP traffic to and from server.",
)
parser.add_argument(
"-l",
"--listen",
default=SSLStripConfig.DEFAULT_LISTEN_PORT,
help="Port to listen on.",
)
parser.add_argument(
"-f",
"--favicon",
default=SSLStripConfig.DEFAULT_SPOOF_FAVICON,
action="store_true",
help="Substitute a lock favicon on secure requests.",
)
parser.add_argument(
"-k",
"--killsessions",
default=SSLStripConfig.DEFAULT_KILL_SESSIONS,
action="store_true",
help="Kill sessions in progress.",
)
args = parser.parse_args()

initialize_logger(args.write, SSLStripConfig.DEFAULT_LOGLEVEL)
start_reactor(args.listen, args.favicon, args.killsessions)


if __name__ == "__main__":
main()
17 changes: 0 additions & 17 deletions sslstrip/.github/dependabot.yml

This file was deleted.

Loading

0 comments on commit 95f725b

Please sign in to comment.