├── .gitignore
├── LICENSE
├── README.md
├── certmon
├── cert
│ ├── __init__.py
│ ├── cert.py
│ ├── certmon_conf.py
│ └── record.py
├── certmon.py
└── mail
│ ├── __init__.py
│ ├── mail_config.py
│ ├── mail_list.py
│ └── mailer.py
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 |
5 | # C extensions
6 | *.so
7 |
8 | # Distribution / packaging
9 | .Python
10 | env/
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | *.egg-info/
23 | .installed.cfg
24 | *.egg
25 |
26 | # PyInstaller
27 | # Usually these files are written by a python script from a template
28 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
29 | *.manifest
30 | *.spec
31 |
32 | # Installer logs
33 | pip-log.txt
34 | pip-delete-this-directory.txt
35 |
36 | # Unit test / coverage reports
37 | htmlcov/
38 | .tox/
39 | .coverage
40 | .coverage.*
41 | .cache
42 | nosetests.xml
43 | coverage.xml
44 | *,cover
45 |
46 | # Translations
47 | *.mo
48 | *.pot
49 |
50 | # Django stuff:
51 | *.log
52 |
53 | # Sphinx documentation
54 | docs/_build/
55 |
56 | # PyBuilder
57 | target/
58 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
341 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | certmon
2 | =======
3 |
4 | certmon.py is a simple certificate expiration monitor script. It will connect to a given server on a given port, dump the certificate, and check if the certificate has expired or not.
5 |
6 | Additionally, it will also report if a certificate is about to expire in x nr of days. (Default: 30 days).
7 |
8 | On top of that, you can check the contents of certain fields in the certificate & see if it contains a keyword that should be there (to see if the certificate has been changed).
9 |
10 | Reports will be sent via email, allowing you to schedule the script to run on regular intervals.
11 |
12 | This script requires Python v3 and has been written/tested on Windows 7.
13 | (Unless you know how to fix OpenSSL on Mac/Linux, please run this script on Windows only, with administrator privileges)
14 |
15 |
16 | Installation instructions (Windows 7)
17 | -------------------------------------
18 |
19 | This script requires Python v3 and some libraries. It has been developed and tested using Python v3.4.3, on Windows 7 SP1, 64bit.
20 | Most of the required libraries are installed by default, but others require manual installation.
21 | (pyOpenSSL, docopt, PySocks)
22 |
23 | Download Python3 from https://www.python.org/downloads and launch the installation package with Administrator privileges.
24 | Perform a default install 'for all users', install in the default installation folder.
25 |
26 | Next, open an Administrator command prompt and run the following commands to install the missing libraries:
27 |
28 | **PyOpenSSL:**
29 |
30 | ```
31 | c:
32 | cd\python34
33 | cd scripts
34 | pip install pyOpenSSL
35 | ```
36 | (Make sure the machine has direct access to the internet before running the 'pip' command)
37 |
38 | If all goes well, you should see something like this:
39 | ```
40 | Collecting pyOpenSSL
41 | Downloading pyOpenSSL-0.14.tar.gz (128kB)
42 | 100% |################################| 131kB 1.4MB/s
43 | Collecting cryptography>=0.2.1 (from pyOpenSSL)
44 | Downloading cryptography-0.8-cp34-none-win32.whl (960kB)
45 | 100% |################################| 962kB 391kB/s
46 | Collecting six>=1.5.2 (from pyOpenSSL)
47 | Downloading six-1.9.0-py2.py3-none-any.whl
48 | Collecting pyasn1 (from cryptography>=0.2.1->pyOpenSSL)
49 | Downloading pyasn1-0.1.7.tar.gz (68kB)
50 | 100% |################################| 69kB 723kB/s
51 | Requirement already satisfied (use --upgrade to upgrade): setuptools in c:\python34\lib\site-packages (from cryptography
52 | >=0.2.1->pyOpenSSL)
53 | Collecting cffi>=0.8 (from cryptography>=0.2.1->pyOpenSSL)
54 | Downloading cffi-0.9.2-cp34-none-win32.whl (82kB)
55 | 100% |################################| 86kB 1.6MB/s
56 | Collecting pycparser (from cffi>=0.8->cryptography>=0.2.1->pyOpenSSL)
57 | Downloading pycparser-2.10.tar.gz (206kB)
58 | 100% |################################| 208kB 975kB/s
59 | Installing collected packages: pycparser, cffi, pyasn1, six, cryptography, pyOpenSSL
60 | Running setup.py install for pycparser
61 |
62 | Running setup.py install for pyasn1
63 |
64 |
65 | Running setup.py install for pyOpenSSL
66 | Successfully installed cffi-0.9.2 cryptography-0.8 pyOpenSSL-0.14 pyasn1-0.1.7 pycparser-2.10 six-1.9.0
67 | ```
68 |
69 | **PySocks:**
70 |
71 | ```
72 | pip install PySocks
73 | ```
74 | Output:
75 | ```
76 | Collecting PySocks
77 | Downloading PySocks-1.5.3.tar.gz
78 | Installing collected packages: PySocks
79 | Running setup.py install for PySocks
80 | Successfully installed PySocks-1.5.3
81 | ```
82 |
83 | **docopt:**
84 |
85 | ```
86 | pip install docopt
87 | ```
88 | Output
89 | ```
90 | Collecting docopt
91 | Downloading docopt-0.6.2.tar.gz
92 | Installing collected packages: docopt
93 | Running setup.py install for docopt
94 | Successfully installed docopt-0.6.2
95 | ```
96 |
97 |
98 | Finally, download the certmon script zip file: https://github.com/corelan/certmon/archive/master.zip and extract it to a folder (e.g. c:\certmon)
99 | (or simply clone the repository via git to a local folder)
100 |
101 |
102 | Syntax
103 | ------
104 |
105 | ```
106 | C:\certmon>c:\python34\python.exe certmon.py -h
107 |
108 | __
109 | ____ ____________/ |_ _____ ____ ____
110 | _/ ___\/ __ \_ __ \ __\/ \ / _ \ / \
111 | \ \__\ ___/| | \/| | | Y Y ( <_> ) | \
112 | \___ >___ >__| |__| |__|_| /\____/|___| /
113 | \/ \/ \/ \/
114 |
115 | corelanc0d3r - www.corelan.be
116 | https://github.com/corelan/certmon
117 |
118 | certmon - Monitor TLS Certificates
119 |
120 | Usage:
121 | certmon.py [-v] [--tor] [-c=] [-s=] [-w=]
122 | certmon.py (-h | --help)
123 | certmon.py --test-mail
124 |
125 | Options:
126 | -h --help Show this help screen.
127 | -c= Full path to cert config file [default: certmon.conf].
128 | -s= Full path to smtp config file [default: certmon_smtp.conf].
129 | -w= Warn of upcoming expiration nr of days in advance [default: 30].
130 | --test-mail Test e-mail configuration.
131 | -v Show verbose information about the certificates.
132 | --tor Make certificate requests via default tor socks proxy localhost 9050.
133 | ```
134 |
135 |
136 | Usage
137 | -----
138 |
139 | The script takes 2 input files, which are expected to be placed in the current folder.
140 | (You can specify an alternate location using parameters -c and -s)
141 |
142 | `certmon.conf`
143 |
144 | This is where you can specify the hostnames & ports to connect to.
145 |
146 | `certmon_smtp.conf`
147 |
148 | This file contains information about your SMTP server, and the email addresses to use.
149 |
150 | You can tweak the warning threshold with parameter -w.
151 |
152 |
153 | certmon.conf syntax
154 | -------------------
155 |
156 | This file contains the hostnames and portnumbers (default 443) to connect to.
157 | Syntax:
158 | ```
159 | hostname:port
160 | ```
161 | (only specify one hostname:port combination per line)
162 |
163 | If you want certmon to also monitor the certificate itself, you can specify which keywords it should contain in certain fields. Supported fields are:
164 |
165 | ```
166 | subject
167 | issuer
168 | version
169 | serial
170 | ```
171 |
172 | Example: Let's say I want to monitor the certificate on www.corelan.be, and I want to be sure that the subject field contains 'www.corelan.be', the issuer field contains the keyword 'StartCom', and the serial number field contains '1056083', then the line inside the certmon.conf file should look like this:
173 |
174 | ```
175 | www.corelan.be:443;issuer=StartCom;serial=1056083;subject=www.corelan.be
176 | ```
177 |
178 | (The fields must be ; separated, and the first field must contain the hostname and port).
179 |
180 | This configuration will trigger the following behaviour:
181 |
182 | If the certificate on www.corelan.be (port 443) will expire in 30 days or less, you will get an email warning.
183 |
184 | If the certificate on www.corelan.be (port 443) has expired, you will get an email alert.
185 |
186 | If one of the 3 fields doesn't contain the corresponding keywords, you will get an email alert.
187 |
188 |
189 | (Hint: If you want to know what exactly is inside the various fields, simply use option -v)
190 |
191 | Note: The field compliance check will be performed against a lowercase conversion of the field & the keyword.
192 |
193 |
194 | certmon_smtp.conf syntax
195 | ------------------------
196 |
197 | This is easy. If the script is unable to find the smtp configuration file, it will ask you a couple of questions & create the file for you.
198 | If you want to check if the mail configuration works correctly simply run the script with option -mail.
199 | You should get a test email in your mailbox.
200 |
201 |
202 | limitations / known issues
203 | --------------------------
204 | The script is not able to handle host headers or URI's. It will simply connect to a server on a port, and dump the certificate.
205 |
206 |
207 | License
208 | -------
209 | GPL
210 |
211 |
--------------------------------------------------------------------------------
/certmon/cert/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/corelan/certmon/ecbe7f030139f4c894c8a0c220b9f6ed9953145a/certmon/cert/__init__.py
--------------------------------------------------------------------------------
/certmon/cert/cert.py:
--------------------------------------------------------------------------------
1 | # certmon.py - Certificate Expiration monitor
2 | # Copyright (C) 2015 - Peter 'corelanc0d3r' Van Eeckhoutte - www.corelan.be
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import ssl
18 | import OpenSSL
19 | import datetime
20 | import logging
21 |
22 | log = logging.getLogger(__name__)
23 |
24 | class Cert:
25 | def __init__(self, host=None, ip=None, port=None, fieldcheck=None):
26 | self.ip = ip
27 | self.port = port
28 | self.host = host
29 | self.fieldcheck = fieldcheck
30 |
31 | self.x509 = None
32 | self.certinfo = None
33 |
34 | # self.target = None
35 | # self.target_port = None
36 | # self.target_host = None
37 | # self.target_ip = None
38 |
39 | self.issuer = None
40 | self.serial = None
41 | self.subject = None
42 | self.version = None
43 |
44 | self.issuerok = True
45 | self.serialok = True
46 | self.subjectok = True
47 | self.versionok = True
48 | self.certchanged = False
49 |
50 | self.expire_date = None
51 | self.delta = None
52 |
53 | if ip != None and port != None:
54 | self.fetch()
55 | self.parse()
56 |
57 | def fetch(self):
58 | self.certinfo = ssl.get_server_certificate((self.ip, self.port))
59 |
60 | def parse(self):
61 | # Note - need to examine why the string replacement needs to happen
62 | certinfo = self.certinfo.replace("=-----END", "=\n-----END")
63 | self.x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, certinfo)
64 |
65 | self.issuer = self.x509.get_issuer()
66 | self.serial = self.x509.get_serial_number()
67 | self.subject = self.x509.get_subject()
68 | self.version = self.x509.get_version()
69 |
70 | self._check_fields()
71 | self._parse_cert_datetime()
72 |
73 | def is_expired(self):
74 | self.delta = self.expire_date - self._curr_date()
75 | if self.delta.days < 0:
76 | log.info("\t*** CERTIFICATE HAS EXPIRED ON %s (%d days ago) ***" %
77 | (self.expire_date, (self.delta.days * -1)))
78 | return True
79 | else:
80 | return False
81 |
82 | def is_alertbefore(self, alertbefore):
83 | self.delta = self.expire_date - self._curr_date()
84 | if self.delta.days == 0:
85 | log.info("*** CERTIFICATE EXPIRES TODAY ***")
86 | return True
87 | elif self.delta.days < alertbefore:
88 | log.info("** Warning: certificate will expire in less than %d days" % alertbefore)
89 | # NOTE return True xor False?!
90 | return True
91 | else:
92 | log.info("Cert expiration OK")
93 | log.info("Certificate will expire on %s (%d days from now)" % (self.expire_date, self.delta.days))
94 | return False
95 |
96 | def is_changed(self):
97 | self._check_fields()
98 | return self.certchanged
99 |
100 | def msg(self):
101 | #def createMsg(x509, targethost, targetport, targetip, expirdate, diff):
102 | msg = ""
103 |
104 | # NOTE handle the DIFF
105 | diff = self.delta.days
106 | extratxt = ""
107 | if diff < 0:
108 | extratxt = " ({} days ago)".format(diff * -1)
109 | else:
110 | extratxt = " (will expire in {} days)".format(diff)
111 |
112 | msg += "Host: {}, Port: {}, IP: {}\n".format(self.host, self.port, self.ip)
113 | msg += self._dump_fields(extratxt)
114 |
115 | if not self.subjectok:
116 | log.info("Subject field contains '%s'" % subject)
117 | log.info("Expected to contain: '%s'" % fieldcheck["subject"])
118 | thismsg += "** Subject field does not contain '{}'\n".format(fieldcheck["subject"])
119 | if not self.issuerok:
120 | log.info("Issuer field contains '%s'" % issuer)
121 | log.info("Expected to contain: '%s'" %fieldcheck["issuer"])
122 | thismsg += "** Issuer field does not contain '{}'\n".format(fieldcheck["issuer"])
123 | if not self.versionok:
124 | log.info("Version field contains '%s'" % version)
125 | log.info("Expected to contain: '%s'" % fieldcheck["version"])
126 | thismsg += "** Version field does not contain '{}'\n".format(fieldcheck["version"])
127 | if not self.serialok:
128 | log.info("Serial field contains '%s'" % serial)
129 | log.info("Expected to contain: '%s'" % fieldcheck["serial"])
130 | thismsg += "** Serial field does not contain '{}'\n".format(fieldcheck["serial"])
131 |
132 | return msg
133 |
134 | def _dump_fields(self, extratxt=""):
135 | msg = ""
136 | msg += " Subject: {}\n".format(self.subject)
137 | msg += " Expiration date: {}{}\n".format(self.expire_date, extratxt)
138 | msg += " Issuer: {}\n".format(self.issuer)
139 | msg += " Version: {}\n".format(self.version)
140 | msg += " Serial: {}\n".format(self.serial)
141 | return msg
142 |
143 |
144 | def _check_fields(self):
145 | for fieldname in self.fieldcheck:
146 | if fieldname == "issuer":
147 | if not self.fieldcheck[fieldname] in str(self.issuer).lower():
148 | self.issuerok = False
149 | self.certchanged = True
150 | elif fieldname == "subject":
151 | if not self.fieldcheck[fieldname] in str(self.subject).lower():
152 | self.subjectok = False
153 | self.certchanged = True
154 | elif fieldname == "version":
155 | if not self.fieldcheck[fieldname] in str(self.version).lower():
156 | self.versionok = False
157 | self.certchanged = True
158 | elif fieldname == "serial":
159 | if not self.fieldcheck[fieldname] in str(self.serial).lower():
160 | self.serialok = False
161 | self.certchanged = True
162 |
163 | def _curr_date(self):
164 | return datetime.datetime.now()
165 |
166 | def _parse_cert_datetime(self):
167 | expire_date_str = str(self.x509.get_notAfter()).replace("b'", "").replace("'", "")
168 | self.expire_date = datetime.datetime.strptime(expire_date_str, "%Y%m%d%H%M%SZ")
169 |
170 |
171 | def _show_verbose(self):
172 | pass
173 |
--------------------------------------------------------------------------------
/certmon/cert/certmon_conf.py:
--------------------------------------------------------------------------------
1 | # certmon.py - Certificate Expiration monitor
2 | # Copyright (C) 2015 - Peter 'corelanc0d3r' Van Eeckhoutte - www.corelan.be
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import os
18 | from .record import Record
19 | import logging
20 | import sys
21 |
22 | log = logging.getLogger(__name__)
23 |
24 | class CertmonConf:
25 |
26 | def __init__(self, certconfig_filename=''):
27 | self.serverlist = []
28 | self.records = []
29 | self.certconfigfile = None
30 |
31 | if certconfig_filename != '':
32 | self.load(certconfig_filename)
33 |
34 | def open(self, certconfig_filename=''):
35 | if os.path.isfile(certconfig_filename):
36 | self.certconfigfile = open(certconfig_filename, "r")
37 | else:
38 | log.error("Oops, file {} does not exist".format(certconfig_filename))
39 | log.error("Desired format: host:port (one entry per line)")
40 | sys.exit(1)
41 |
42 | def close(self):
43 | self.certconfigfile.close()
44 |
45 | def load(self, certconfig_filename=''):
46 | # NOTE not sure if should be checking for just str xor unicode
47 | if certconfig_filename == None or not isinstance(certconfig_filename, str):
48 | # NOTE probably should rais an error here
49 | return
50 | # NOTE should verify is string
51 | self.open(certconfig_filename)
52 | self._parse()
53 | self.close()
54 |
55 | def _parse(self):
56 | content = self.certconfigfile.readlines()
57 | for l in content:
58 | checkdata = []
59 | lstripped = l.replace("\n", "").replace("\r", "").replace("\t", "")
60 | if not lstripped.startswith("#") and len(l) > 0:
61 | lineparts = lstripped.split(";")
62 |
63 | targetparts = lineparts[0].split(":")
64 |
65 | rport = 443
66 | rhost = targetparts[0]
67 | if len(targetparts) > 1:
68 | try:
69 | rport = int(targetparts[1])
70 | except:
71 | pass
72 |
73 | check = ""
74 | if len(lineparts) > 1:
75 | i = 1
76 | while i < len(lineparts):
77 | checkdata.append(lineparts[i])
78 | i += 1
79 |
80 | thisserver = [rhost, rport, checkdata]
81 | if not thisserver in self.serverlist:
82 | self.serverlist.append(thisserver)
83 |
84 | fieldcheck = {}
85 | for checkitem in checkdata:
86 | thisitemparts = checkitem.split("=")
87 | if len(thisitemparts) > 1:
88 | fieldname = thisitemparts[0].lower().replace(" ", "")
89 | remainingparts = thisitemparts[1:]
90 | fieldkeyword = "=".join(x for x in remainingparts)
91 | fieldkeyword = fieldkeyword.lower().replace(
92 | "\n",
93 | "").replace(
94 | "\r",
95 | "")
96 | if not fieldname in fieldcheck:
97 | fieldcheck[fieldname] = fieldkeyword
98 | self.records.append(Record(rhost, rport, checkdata, fieldcheck))
99 |
100 | def getRecords(self):
101 | return self.records
--------------------------------------------------------------------------------
/certmon/cert/record.py:
--------------------------------------------------------------------------------
1 | # certmon.py - Certificate Expiration monitor
2 | # Copyright (C) 2015 - Peter 'corelanc0d3r' Van Eeckhoutte - www.corelan.be
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import socket
18 | from socket import gethostname
19 | from .cert import Cert
20 | import logging
21 |
22 | log = logging.getLogger(__name__)
23 |
24 | class Record:
25 |
26 | def __init__(self, target_host, target_port, checkdata, fieldcheck):
27 | self.fields_to_check = {}
28 | self.host = target_host
29 | self.port = target_port
30 | self.checkdata = checkdata
31 | self.fieldcheck = fieldcheck
32 | self.IPs = None
33 |
34 | self._get_IPs()
35 |
36 | def _get_IPs(self):
37 | # Note this needs null error validation and try,except block
38 | self.IPs = [socket.gethostbyname(self.host)]
39 |
40 | def fetch_certs(self):
41 | certs = []
42 | for ip in self.IPs:
43 | certs.append(Cert(host=self.host, ip=ip, port=self.port, fieldcheck=self.fieldcheck))
44 | return certs
--------------------------------------------------------------------------------
/certmon/certmon.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # certmon.py - Certificate Expiration monitor
4 | # Copyright (C) 2015 - Peter 'corelanc0d3r' Van Eeckhoutte - www.corelan.be
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | import os
21 | import sys
22 | import datetime
23 | import traceback
24 | import logging
25 | import socks
26 | import socket
27 | import urllib.request
28 |
29 | __doc__ = """certmon - Monitor TLS Certificates
30 |
31 | Usage:
32 | certmon.py [-v] [--tor] [-c=] [-s=] [-w=]
33 | certmon.py (-h | --help)
34 | certmon.py --test-mail
35 |
36 | Options:
37 | -h --help Show this help screen.
38 | -c= Full path to cert config file [default: certmon.conf].
39 | -s= Full path to smtp config file [default: certmon_smtp.conf].
40 | -w= Warn of upcoming expiration nr of days in advance [default: 30].
41 | --test-mail Test e-mail configuration.
42 | -v Show verbose information about the certificates.
43 | --tor Make certificate requests via default tor socks proxy localhost 9050.
44 |
45 | """
46 | from docopt import docopt
47 |
48 | from mail.mail_list import MailList
49 | from mail.mailer import Mailer
50 | from mail.mail_config import MailConfig
51 |
52 | from cert.record import Record
53 | from cert.certmon_conf import CertmonConf
54 |
55 | log = logging.getLogger(__name__)
56 | curdate = datetime.datetime.now()
57 | siteurl = "https://github.com/corelan/certmon"
58 |
59 |
60 | def getNow():
61 | return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
62 |
63 |
64 | def showBanner():
65 |
66 | print ("""
67 | __
68 | ____ ____________/ |_ _____ ____ ____
69 | _/ ___\/ __ \_ __ \ __\/ \ / _ \ / \\
70 | \ \__\ ___/| | \/| | | Y Y ( <_> ) | \\
71 | \___ >___ >__| |__| |__|_| /\____/|___| /
72 | \/ \/ \/ \/
73 |
74 | corelanc0d3r - www.corelan.be
75 | %s
76 | """ % siteurl)
77 |
78 | return
79 |
80 |
81 | def init_changed_mail_list(mailer=None):
82 | changed_list = MailList(mailer)
83 | changed_list.body_header = "Hi,\n\n"
84 | changed_list.body_header += "The following certificates may have been changed:\n\n"
85 | changed_list.subject="Certificate Change Alert (certmon.py)"
86 | return changed_list
87 |
88 |
89 | def init_warn_mail_list(mailer=None):
90 | warn_list = MailList(mailer)
91 | warn_list.body_header = "Hi,\n\n"
92 | warn_list.body_header += "The following certificates will expire in less than %d days:\n\n" % alertbefore
93 | warn_list.subject="Upcoming Certificate Expiration Warning (certmon.py)"
94 | return warn_list
95 |
96 |
97 | def init_expired_mail_list(mailer=None):
98 | expired_list = MailList(mailer)
99 | expired_list.body_header = "Hi,\n\n"
100 | expired_list.body_header += "The following certificates have expired:\n\n"
101 | expired_list.subject="Expired Certificates Alert (certmon.py)"
102 | return expired_list
103 |
104 |
105 | if __name__ == "__main__":
106 |
107 | showBanner()
108 |
109 | arguments = docopt(__doc__, version='0.0.1')
110 |
111 | mailconfigerror = True
112 | mailconfigfile = arguments['-s']
113 | certconfigfile = arguments['-c']
114 | alertbefore = int(arguments['-w'])
115 | verbose = arguments['-v']
116 |
117 | if verbose:
118 | logging.basicConfig(level=logging.INFO)
119 | else:
120 | logging.basicConfig(format="[+] %(message)s",level=logging.INFO)
121 |
122 |
123 | log.info("Current date: %s", getNow())
124 | log.info("Warn about upcoming expirations in less than %d days", alertbefore)
125 |
126 | cEmailConfig = MailConfig(mailconfigfile)
127 | if not cEmailConfig.configFileExists():
128 | log.warning("Oops, email config file %s doesn't exist yet", mailconfigfile)
129 | cEmailConfig.initConfigFile()
130 | else:
131 | log.info("Using mail config file %s", mailconfigfile)
132 | cEmailConfig.readConfigFile()
133 |
134 | if arguments['--test-mail']:
135 | log.info("Test Mail Configuration")
136 | content = []
137 | mailhandler = Mailer(mailconfigfile)
138 | info = ['certmon.py email test']
139 | mailhandler.sendmail(info, content, 'Email test')
140 | sys.exit(0)
141 |
142 | mailhandler = Mailer(mailconfigfile)
143 | warn_list = init_warn_mail_list(mailer=mailhandler)
144 | expired_list = init_expired_mail_list(mailer=mailhandler)
145 | changed_list = init_changed_mail_list(mailer=mailhandler)
146 |
147 | if arguments['--tor']:
148 | original_socket = socket.socket
149 | socks.set_default_proxy(socks.SOCKS5, "localhost", 9050)
150 | socket.socket = socks.socksocket
151 | log.info("socks public ip: " + str(urllib.request.urlopen('http://ip.42.pl/raw').read()))
152 |
153 | all_certs = []
154 | certmon_conf = CertmonConf(certconfigfile)
155 | for record in certmon_conf.records:
156 | all_certs += record.fetch_certs()
157 |
158 |
159 | for cert in all_certs:
160 | log.info("")
161 | log.info("-" * 75)
162 | log.info("Checking cert on %s (%s), port %s" % (cert.host, cert.ip, cert.port))
163 | if verbose:
164 | log.info(cert._dump_fields())
165 | if cert.is_expired():
166 | expired_list.cert_msgs.append(cert.msg())
167 | if cert.is_alertbefore(alertbefore):
168 | warn_list.cert_msgs.append(cert.msg())
169 | if cert.is_changed():
170 | changed_list.cert_msgs.append(cert.msg())
171 | log.info("-" * 75)
172 |
173 | if arguments['--tor']:
174 | socket.socket = original_socket
175 | log.info("public ip: " + str(urllib.request.urlopen('http://ip.42.pl/raw').read()))
176 |
177 | expired_list.send()
178 | warn_list.send()
179 | changed_list.send()
180 |
181 |
--------------------------------------------------------------------------------
/certmon/mail/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/corelan/certmon/ecbe7f030139f4c894c8a0c220b9f6ed9953145a/certmon/mail/__init__.py
--------------------------------------------------------------------------------
/certmon/mail/mail_config.py:
--------------------------------------------------------------------------------
1 | # certmon.py - Certificate Expiration monitor
2 | # Copyright (C) 2015 - Peter 'corelanc0d3r' Van Eeckhoutte - www.corelan.be
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import os
18 | import logging
19 |
20 | log = logging.getLogger(__name__)
21 |
22 | class MailConfig:
23 |
24 | """
25 | Class to manage SMTP email config
26 | """
27 |
28 | serverinfo = {}
29 |
30 | def __init__(self, filename):
31 | self.filename = filename
32 | self.fullpath = filename
33 |
34 | def configFileExists(self):
35 | return os.path.isfile(self.fullpath)
36 |
37 | def readConfigFile(self):
38 | f = open(self.fullpath, "r")
39 | content = f.readlines()
40 | f.close()
41 | serverdata = {}
42 | thisid = ""
43 | for l in content:
44 | line = l.replace("\n", "").replace("\r", "")
45 | if line.startswith("[") and line.endswith("]"):
46 | # new config
47 | # if we already have a config, save it first
48 | if thisid != "" and len(
49 | serverdata) > 0 and not thisid in self.serverinfo:
50 | self.serverinfo[thisid] = serverdata
51 | thisid = line[1:-1]
52 | serverdata = {}
53 | if not line.startswith("#") and len(line) > 0 and "=" in line:
54 | lineparts = line.split("=")
55 | configparam = lineparts[0]
56 | if len(lineparts) > 1 and len(
57 | configparam) > 0 and len(line) > len(configparam):
58 | configval = line[len(configparam) + 1:]
59 | serverdata[configparam] = configval
60 | # save the last one too
61 | if thisid != "" and len(
62 | serverdata) > 0 and not thisid in self.serverinfo:
63 | self.serverinfo[thisid] = serverdata
64 |
65 | return
66 |
67 | def writeConfigFile(self):
68 | filecontent = []
69 | for configid in self.serverinfo:
70 | thisdata = self.serverinfo[configid]
71 | filecontent.append("[%s]" % str(configid))
72 | filecontent += thisdata
73 |
74 | f = open(self.fullpath, "wb")
75 | for l in filecontent:
76 | f.write(bytes("%s\n" % l, 'UTF-8'))
77 | f.close()
78 | log.info("Saved new config file.")
79 | return
80 |
81 | def initConfigFile(self):
82 | log.info("Creating a new config file.")
83 | i_server = ""
84 | i_port = 25
85 | i_timeout = 300
86 | i_auth = "no"
87 | i_user = ""
88 | i_pass = ""
89 | i_from = ""
90 | i_to = ""
91 | i_tls = "no"
92 |
93 | while True:
94 | i_server = input(' > Enter smtp mail server IP or hostname: ')
95 | if not i_server == "":
96 | break
97 |
98 | while True:
99 | i_port = input(' > Enter mail server port (default: 25): ')
100 | if not str(i_port) == "":
101 | try:
102 | i_port = int(i_port)
103 | break
104 | except:
105 | continue
106 | else:
107 | i_port = 25
108 | break
109 |
110 | while True:
111 | i_from = input(" > Enter 'From' email address: ")
112 | if not i_from == "":
113 | break
114 |
115 | while True:
116 | i_to = input(" > Enter 'To' email address: ")
117 | if not i_to == "":
118 | break
119 |
120 | while True:
121 | i_timeout = input(
122 | ' > Enter mail server timeout (in seconds, default: 300): ')
123 | if not str(i_timeout) == "":
124 | try:
125 | i_timeout = int(i_timeout)
126 | break
127 | except:
128 | continue
129 | else:
130 | i_timeout = 300
131 | break
132 |
133 | while True:
134 | i_auth = input(
135 | ' > Does server require authentication? (yes/no, default: no): ')
136 | i_auth = i_auth.lower()
137 | if i_auth == "":
138 | i_auth = "no"
139 | if i_auth in ["yes", "no"]:
140 | break
141 |
142 | if i_auth == "yes":
143 | while True:
144 | i_user = input(' > Username: ')
145 | if not i_user == "":
146 | break
147 | while True:
148 | i_pass = input(' > Password: ')
149 | if not i_pass == "":
150 | break
151 |
152 | while True:
153 | i_tls = input(
154 | ' > Does server require/support STARTTLS ? (yes/no, default: no): ')
155 | i_tls = i_tls.lower()
156 | if i_tls == "":
157 | i_tls = "no"
158 | if i_tls in ["yes", "no"]:
159 | break
160 |
161 | initserverdata = []
162 | initserverdata.append("server=%s" % i_server)
163 | initserverdata.append("port=%d" % i_port)
164 | initserverdata.append("from=%s" % i_from)
165 | initserverdata.append("to=%s" % i_to)
166 | initserverdata.append("timeout=%d" % i_timeout)
167 | initserverdata.append("auth=%s" % i_auth)
168 | initserverdata.append("user=%s" % i_user)
169 | initserverdata.append("pass=%s" % i_pass)
170 | initserverdata.append("tls=%s" % i_tls)
171 |
172 | self.serverinfo = {}
173 | self.serverinfo[i_server] = initserverdata
174 | self.writeConfigFile()
175 | return
--------------------------------------------------------------------------------
/certmon/mail/mail_list.py:
--------------------------------------------------------------------------------
1 | # certmon.py - Certificate Expiration monitor
2 | # Copyright (C) 2015 - Peter 'corelanc0d3r' Van Eeckhoutte - www.corelan.be
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | siteurl = "https://github.com/corelan/certmon"
18 |
19 | import datetime
20 | import logging
21 |
22 | log = logging.getLogger(__name__)
23 |
24 | def getNow():
25 | return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
26 |
27 | class MailList:
28 |
29 | def __init__(self, mailer=None):
30 | self.cert_msgs = []
31 | self.footer = "\n\nThis report has been auto-generated with certmon.py - %s - %s\n " % (siteurl, getNow())
32 | self.body_header = "Hi,\n\n"
33 | self.body_header += "The following certificates may have been Xed:\n\n"
34 | self.subject="[certmon.py] mail list subject"
35 | self.send_verbose = ""
36 | self.mailer = mailer
37 |
38 | def gen_mail_body(self):
39 | mail_body = self.body_header
40 | for cert_msg in self.cert_msgs:
41 | mail_body += cert_msg
42 | mail_body += "-" * 75
43 | mail_body += "\n"
44 | mail_body += "\n\n"
45 | mail_body += self.footer
46 |
47 | return mail_body
48 |
49 | def send(self):
50 | # NOTE should this be mail content be a method?
51 | if len(self.cert_msgs) > 0:
52 | self.mailer.sendmail(self.gen_mail_body().split('\n'), mailsubject=self.subject)
--------------------------------------------------------------------------------
/certmon/mail/mailer.py:
--------------------------------------------------------------------------------
1 | # certmon.py - Certificate Expiration monitor
2 | # Copyright (C) 2015 - Peter 'corelanc0d3r' Van Eeckhoutte - www.corelan.be
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from .mail_config import MailConfig
18 |
19 | import smtplib
20 | from email.mime.text import MIMEText
21 | from email.mime.multipart import MIMEMultipart
22 |
23 | import time
24 | import socket
25 | from socket import gethostname
26 | import logging
27 |
28 | log = logging.getLogger(__name__)
29 |
30 | siteurl = "https://github.com/corelan/certmon"
31 |
32 | def check_port(host, port):
33 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
34 | try:
35 | s.connect((host, port))
36 | return True
37 | except:
38 | return False
39 |
40 | class Mailer:
41 |
42 | """
43 | Class to handle email notifications
44 | """
45 |
46 | def __init__(self, smtpconfigfile):
47 | self.server = "127.0.0.1"
48 | self.timeout = 300
49 | self.port = 25
50 | self.to = "root@127.0.0.1"
51 | self.fromaddress = "root@127.0.0.1"
52 | self.login = ""
53 | self.password = ""
54 | self.requirelogin = False
55 | self.usetls = False
56 |
57 | # read the config file
58 | cEmailConfig = MailConfig(smtpconfigfile)
59 | cEmailConfig.readConfigFile()
60 | serverconfigs = cEmailConfig.serverinfo
61 | # connect to the first one that is listening
62 | log.info(
63 | "Config file appears to contain %d mail server definitions" %
64 | len(serverconfigs))
65 | for mailid in serverconfigs:
66 | thisconfig = serverconfigs[mailid]
67 | if "server" in thisconfig:
68 | self.server = thisconfig["server"]
69 | if "port" in thisconfig:
70 | self.port = int(thisconfig["port"])
71 | log.info(
72 | "Checking if %s:%d is reachable" %
73 | (self.server, self.port))
74 | if check_port(self.server, self.port):
75 | # fill out the rest and terminate the loop
76 | log.info("Yup, port is open")
77 | if "timeout" in thisconfig:
78 | self.timeout = int(thisconfig["timeout"])
79 | if "auth" in thisconfig:
80 | if thisconfig["auth"] == "yes":
81 | self.requirelogin = True
82 | else:
83 | self.requirelogin = False
84 | if "user" in thisconfig:
85 | self.login = thisconfig["user"]
86 | if "pass" in thisconfig:
87 | self.password = thisconfig["pass"]
88 | if "tls" in thisconfig:
89 | if thisconfig["tls"] == "yes":
90 | self.usetls = True
91 | else:
92 | self.usetls = False
93 | if "to" in thisconfig:
94 | self.to = thisconfig["to"]
95 | if "from" in thisconfig:
96 | self.fromaddress = thisconfig["from"]
97 | break
98 | else:
99 | log.info(" Nope")
100 | return
101 |
102 | def sendmail(self, info, logfile=[], mailsubject="Certmon Alert"):
103 | msg = MIMEMultipart()
104 | bodytext = "\n".join(x for x in info)
105 | logtext = "\n".join(x for x in logfile)
106 | mailbody = MIMEText(bodytext, 'plain')
107 | msg.attach(mailbody)
108 |
109 | msg['Subject'] = '%s - %s' % (gethostname(), mailsubject)
110 | msg['From'] = self.fromaddress
111 | # uncomment the next line if you don't want return receipts
112 | # msg['Disposition-Notification-To'] = self.fromaddress
113 | msg['To'] = self.to
114 | msg['X-Priority'] = '2'
115 |
116 | if len(logfile) > 0:
117 | part = MIMEBase('application', "octet-stream")
118 | part.set_payload(logtext)
119 | Encoders.encode_base64(part)
120 | part.add_header(
121 | 'Content-Disposition',
122 | 'attachment; filename="certmon.txt"')
123 | msg.attach(part)
124 | noerror = False
125 | thistimeout = 5
126 | while not noerror:
127 | try:
128 | log.info("")
129 | log.info(
130 | "Connecting to %s on port %d" %
131 | (self.server, self.port))
132 | s = smtplib.SMTP(
133 | self.server,
134 | self.port,
135 | 'minicase',
136 | self.timeout)
137 | log.info("Connected")
138 | if self.usetls:
139 | log.info("Issuing STARTTLS")
140 | s.starttls()
141 | log.info("STARTTLS established")
142 | if self.requirelogin:
143 | log.info("Authenticating")
144 | s.login(self.login, self.password)
145 | log.info("Authenticated")
146 | log.info("Sending email")
147 | s.sendmail(self.to, [self.to], msg.as_string())
148 | log.info("Mail sent, disconnecting")
149 | s.quit()
150 | noerror = True
151 | except smtplib.SMTPServerDisconnected as e:
152 | log.error("Server disconnected unexpectedly. This is probably okay")
153 | noerror = True
154 | except smtplib.SMTPResponseException as e:
155 | log.error(
156 | "Server returned %s : %s" %
157 | (str(
158 | e.smtp_code),
159 | e.smtp_error))
160 | except smtplib.SMTPSenderRefused as e:
161 | log.error(
162 | "Sender refused %s : %s" %
163 | (str(
164 | e.smtp_code),
165 | smtp_error))
166 | except smtplib.SMTPRecipientsRefused as e:
167 | log.error("Recipients refused", exc_info=True)
168 | except smtplib.SMTPDataError as e:
169 | log.error("Server refused to accept the data", exc_info=True)
170 | except smtplib.SMTPConnectError as e:
171 | log.error("Error establishing connection to server", exc_info=True)
172 | except smtplib.SMTPHeloError as e:
173 | log.error("HELO Error", exc_info=True)
174 | except smtplib.SMTPAuthenticationError as e:
175 | log.error("Authentication", exc_info=True)
176 | except smtplib.SMTPException as e:
177 | log.error("Sending email", exc_info=True)
178 | except:
179 | log.error("Unable to send email !")
180 |
181 | if not noerror:
182 | log.info("I'll try again in %d seconds" % thistimeout)
183 | time.sleep(thistimeout)
184 | if thistimeout < 1200:
185 | thistimeout += 5
186 | return
187 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | cffi==0.9.2
2 | cryptography==0.8.1
3 | docopt==0.6.2
4 | pyasn1==0.1.7
5 | pycparser==2.10
6 | pyopenssl ~> 17.5.0
7 | PySocks==1.5.3
8 | six==1.9.0
9 |
--------------------------------------------------------------------------------