question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mitmproxy as a windows service fails to SSL

See original GitHub issue

Problem Description

Mitmproxy works fine if run directly but fails to intercept SSL requests when run as a windows service. I run the code as Administrator.

Steps to reproduce the behavior:

This code works fine:

class AddHeader:
    def __init__(self):
        self.num = 0

    def response(self, flow):
        self.num = self.num + 1
        flow.response.headers["count"] = str(self.num)

if __name__ == '__main__':
    options = Options(listen_host='127.0.0.1', listen_port=8081)
    config = ProxyConfig(options)
    master = ProxyMaster(options, with_termlog=DEBUG, with_dumper=DEBUG)
    master.server = ProxyServer(config)
    master.addons.add(AddHeader())
    master.run()

But this code that uses mitmproxy within a service does not work and produces an error:

import socket

import win32serviceutil

import servicemanager
import win32event
import win32service

from mitmproxy.options import Options
from mitmproxy.proxy.config import ProxyConfig
from mitmproxy.proxy.server import ProxyServer
from mitmproxy.tools.dump import DumpMaster

class SMWinservice(win32serviceutil.ServiceFramework):
    '''Base class to create winservice in Python'''

    _svc_name_ = 'pythonService'
    _svc_display_name_ = 'Python Service'
    _svc_description_ = 'Python Service Description'

    @classmethod
    def parse_command_line(cls):
        '''
        ClassMethod to parse the command line
        '''
        win32serviceutil.HandleCommandLine(cls)

    def __init__(self, args):
        '''
        Constructor of the winservice
        '''
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        '''
        Called when the service is asked to stop
        '''
        self.stop()
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        '''
        Called when the service is asked to start
        '''
        #self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        self.start()
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        self.main()

    def start(self):
        '''
        Override to add logic before the start
        eg. running condition
        '''
        pass

    def stop(self):
        '''
        Override to add logic before the stop
        eg. invalidating running condition
        '''
        pass

    def main(self):
        '''
        Main class to be overridden to add logic
        '''
        pass

class AddHeader:
    def __init__(self):
        self.num = 0

    def response(self, flow):
        self.num = self.num + 1
        flow.response.headers["count"] = str(self.num)

class PythonCornerExample(SMWinservice):
    _svc_name_ = "service"
    _svc_display_name_ = "just a service"
    _svc_description_ = "doesn't do much"

    def start(self):
        self._install()
        self.isrunning = True

    def stop(self):
        self.isrunning = False
        self.master.shutdown()

    def main(self):
        options = Options(listen_host='127.0.0.1', listen_port=8081, confdir=r"C:\Users\username\.mitmproxy")
        config = ProxyConfig(options)
        self.master = ProxyMaster(options, with_termlog=True, with_dumper=True)
        self.master.server = ProxyServer(config)
        self.master.addons.add(AddHeader())

        try:
            self.master.run()
        except Exception as e:
            servicemanager.LogErrorMsg("Some error happened running MitmProxy. Is port 8080 free?\n{}".format(e))

if __name__ == '__main__':
    PythonCornerExample.parse_command_line()

The error happens when an SSL packet gets to mitmproxy: << Cannot establish TLS with example.com:443 (sni: example.com): TlsException('SSL handshake error: WantReadError()')

And can be run with:

python script.py debug

I set confdir=r"C:\Users\username\.mitmproxy" just in case since it runs as Administrator it is not looking for the certs in the folder where I have them but still fails. What am I missing? Thank you in advance

System Information

Mitmproxy: 5.3.0
Python:    3.7.1
OpenSSL:   OpenSSL 1.1.1h  22 Sep 2020
Platform:  Windows-10-10.0.20241-SP0

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
illera88commented, Jan 8, 2021

It’s fixed in 7.0

0reactions
mhilscommented, Dec 11, 2020

FYI, everything in mitmproxy.proxy is about to be swapped out with a new sans-io implementation in a few days/weeks. You may want to take a look at the sans-io branch, which could also give you a better error message here. See #1775 and https://github.com/mitmproxy/mitmproxy/projects/4. I think we’re unlikely to merge nontrivial changes to mitmproxy.proxy until then.

Read more comments on GitHub >

github_iconTop Results From Across the Web

mitmproxy - Mitm proxy using on Windows - Stack Overflow
I have installed and run mitm proxy (on a Windows machine). Now I want to get the SSL key of the proxy. So...
Read more >
How to Man in the Middle HTTPS Using mitmproxy - Earthly Blog
If you are on Windows, follow this guide to add the MITM root certificate as a trusted root certificate authority. Installing The Cert...
Read more >
Certificates - mitmproxy docs
For security reasons, the mitmproxy CA is generated uniquely on the first start and is not shared between mitmproxy installations on different devices....
Read more >
Intercepting SSL And HTTPS Traffic With mitmproxy and ...
Mitmproxy generates certificates on-the-fly to fool the client into believing that they are communicating with the server. To make the client ...
Read more >
Capture, Analyze and Debug HTTPS traffic with MITMProxy
Mitmproxy is an enormously flexible tool. Knowing exactly how the proxying process works will help you deploy it creatively, and take into ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found