diff --git a/.DS_Store b/.DS_Store
new file mode 100644
index 0000000..d9e4ee9
Binary files /dev/null and b/.DS_Store differ
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..4607af9
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,188 @@
+/Dockerfile
+/venv
+/endpoint_reports/
+/logging/
+/.gitignore
+/Config_information/
+/certificate_information/
+
+
+### VirtualEnv template
+# Virtualenv
+# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
+.Python
+[Bb]in
+[Ii]nclude
+[Ll]ib
+[Ll]ib64
+[Ll]ocal
+[Ss]cripts
+pyvenv.cfg
+.venv
+pip-selfcheck.json
+
+### Python template
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# poetry
+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
+# This is especially recommended for binary packages to ensure reproducibility, and is more
+# commonly ignored for libraries.
+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
+#poetry.lock
+
+# pdm
+# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
+#pdm.lock
+# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
+# in version control.
+# https://pdm.fming.dev/#use-with-ide
+.pdm.toml
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+# PyCharm
+# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
+# and can be added to the global gitignore or merged into this file. For a more nuclear
+# option (not recommended) you can uncomment the following to ignore the entire idea folder.
+#.idea/
+
+
+
+
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..97e5a26
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,247 @@
+### VisualStudioCode template
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+*.code-workspace
+
+# Local History for Visual Studio Code
+.history/
+
+### JetBrains template
+# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
+# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
+
+# User-specific stuff
+.idea/**/workspace.xml
+.idea/**/tasks.xml
+.idea/**/usage.statistics.xml
+.idea/**/dictionaries
+.idea/**/shelf
+
+# Generated files
+.idea/**/contentModel.xml
+
+# Sensitive or high-churn files
+.idea/**/dataSources/
+.idea/**/dataSources.ids
+.idea/**/dataSources.local.xml
+.idea/**/sqlDataSources.xml
+.idea/**/dynamic.xml
+.idea/**/uiDesigner.xml
+.idea/**/dbnavigator.xml
+
+# Gradle
+.idea/**/gradle.xml
+.idea/**/libraries
+
+# Gradle and Maven with auto-import
+# When using Gradle or Maven with auto-import, you should exclude module files,
+# since they will be recreated, and may cause churn. Uncomment if using
+# auto-import.
+# .idea/artifacts
+# .idea/compiler.xml
+# .idea/jarRepositories.xml
+# .idea/modules.xml
+# .idea/*.iml
+# .idea/modules
+# *.iml
+# *.ipr
+
+# CMake
+cmake-build-*/
+
+# Mongo Explorer plugin
+.idea/**/mongoSettings.xml
+
+# File-based project format
+*.iws
+
+# IntelliJ
+out/
+
+# mpeltonen/sbt-idea plugin
+.idea_modules/
+
+# JIRA plugin
+atlassian-ide-plugin.xml
+
+# Cursive Clojure plugin
+.idea/replstate.xml
+
+# Crashlytics plugin (for Android Studio and IntelliJ)
+com_crashlytics_export_strings.xml
+crashlytics.properties
+crashlytics-build.properties
+fabric.properties
+
+# Editor-based Rest Client
+.idea/httpRequests
+
+# Android studio 3.1+ serialized cache file
+.idea/caches/build_file_checksums.ser
+
+### VirtualEnv template
+# Virtualenv
+# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
+.Python
+[Bb]in
+[Ii]nclude
+[Ll]ib
+[Ll]ib64
+[Ll]ocal
+[Ss]cripts
+pyvenv.cfg
+.venv
+pip-selfcheck.json
+
+### Python template
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+config.yaml
+
+
+/.pfx
+
+/certificate_information/
+/logging/
+/Config_information/
+/endpoint_reports/
+.tar
+/coldclarity.tar
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..1844003
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,15 @@
+FROM --platform=linux/amd64 python:3.9-slim AS x86_64_image
+
+LABEL authors="Osamuede Obasuyi"
+LABEL description="This image contains a portable version of ColdClarity."
+LABEL version="1.0"
+LABEL license="GPL"
+
+
+COPY ./* ColdClarity/
+WORKDIR ColdClarity
+
+RUN pip install -r requirements.txt
+
+
+CMD ["python3.9", "./term_access.py", "--config_file", "config.yaml"]
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
new file mode 100755
index 0000000..f3e30da
--- /dev/null
+++ b/README.md
@@ -0,0 +1,61 @@
+# Cold Clarity
+
+Endpoint Reporting App for Identity Service Engine (ISE)
+
+
+
+## Table of Contents
+- [Reporting](#Reporting)
+- [Templates](#Templates)
+- [FAQs](#FAQs)
+- [Requirements](#Requirements)
+
+## Reporting
+### Using Source
+```shell
+# make sure you in the ColdClarity Dir.
+# Also if the config YAML is in the current dir or the subdir Config_information you only need to specify the file name
+# otherwise specify the complete PATH
+python3.8 term_access.py --config_file config.yaml
+```
+### Using Containers
+```shell
+# you can use either docker or podman, but the following is created for podman.
+# you can also run it natively with out this script as its only if you want to ensure the app runs and exits properly
+# one use-case for this is running this on a cron job in a environment where the app will not work natively
+# please edit the BASH file appropriately and give it the correct rights to run
+./cold_watcher.bash
+```
+## Templates
+### Generating ISE Certificates for Client Based Auth
+If you are using client based authentication for your ISE deployment AND YOU DONT have a client based Cert that ISE has a CA for,
+please look at the `self.signed_cert.bash` in the templates DIR on general instructions on how it works with this APP and ISE
+```bash
+# running the script is simple please make you give it correct permission
+./self.signed_cert.bash
+```
+### Configuration YAML
+1. In the `report` section please fill it out with the information you have and make sure `send_email` is set to `true`
+if you want to send this report automatically with the `prepared_for` specifying the receiver of the report.
+2. In `authentication` specify whether you are using user/password or certificate based login
+3. If you are sending this report make sure your specify your mail relay settings.
+
+
+## FAQs
+**Q**: We have all of our devices in audit mode but our reports are generating that those endpoints are compliant when in ISE under the Failed Conditions
+I see hits for those endpoints. how come?
+
+**A**: Since ISE treats all audit Policies as Passes, this app will parse the posture Policy _AND NOT_ posture condition to give a more accurate totaling of endpoints status.
+
+**Q**: In the reports my total endpoints and profiled endpoints are not matching my logical profiles buckets
+
+**A**: As of ISE v3.1, it doest support the de-confliction of logical profile assigned to an endpoint. So if you have a
+situation where you have the parent profile and child profile in the same ISE logical profile. ISE will just append the same logical profile to the endpoint. The same case holds true if you also assign the multiple logical profiles to the same endpoint
+
+
+## Requirements
+This app requires the following environment
+```
+python >= 3.8
+Cisco ISE >= 3.3
+```
\ No newline at end of file
diff --git a/cold_watcher.bash b/cold_watcher.bash
new file mode 100644
index 0000000..67f5a43
--- /dev/null
+++ b/cold_watcher.bash
@@ -0,0 +1,96 @@
+#!/bin/bash
+
+# made for RHEL PODMAN but can be switched for DOCKER
+IMAGE_NAME="coldclarity"
+CONTAINER_NAME="ColdClaritySVCS_$RANDOM"
+CONFIG_LOCATION="/path/to/config"
+CERT_PFX_LOCATION="PATH/TO/CERT"
+WORKING_DIR="/opt/$IMAGE_NAME"
+LOGGING_FILE="$WORKING_DIR/logs/$IMAGE_NAME.log"
+MAX_RETRIES=4
+RETRIES=0
+
+# Script should run from the /OPT directory; configs can be anywhere
+# IF YOU DONT USE CERT DROP "-v "$CERT_PFX_LOCATION":/ColdClarity/certificate_information/ise_client_cert.pfx:Z" from the command line
+
+# Check or create logging Dir and file
+if [ ! -d "$WORKING_DIR/logs" ]; then
+ # If the directory doesn't exist, create it
+ mkdir -p "$WORKING_DIR/logs"
+ echo "$(date): $WORKING_DIR/logs created." >> "$LOGGING_FILE"
+else
+ echo "$(date): $WORKING_DIR/logs already exists." >> "$LOGGING_FILE"
+fi
+
+
+start_container() {
+ podman run -it --privileged -v "$CONFIG_LOCATION":/ColdClarity/Config_information/config.yaml:Z -v "$CERT_PFX_LOCATION":/ColdClarity/certificate_information/ise_client_cert.pfx:Z --name "$CONTAINER_NAME" "$IMAGE_NAME"
+}
+
+cleanup_containers() {
+ podman rm -f "$CONTAINER_NAME"
+ echo "$(date): Cleaning up and removing used $CONTAINER_NAME" >> "$LOGGING_FILE"
+}
+
+# Trap exit signal to ensure cleanup even on script interruption
+trap cleanup_containers EXIT
+
+while true; do
+ # start container
+ init_container=$(start_container)
+ echo "$(date): INFO: $init_container" >> "$LOGGING_FILE"
+
+
+ # check to make sure the container really started
+ container_started=$(podman ps -a | grep $CONTAINER_NAME)
+
+
+ # Wait for the container to exit
+ podman wait "$CONTAINER_NAME"
+
+ # Get the exit status of the container
+ container_status=$(podman inspect -f "{{.State.ExitCode}}" "$CONTAINER_NAME")
+
+
+
+ if [[ $container_started == *"$CONTAINER_NAME"* ]]; then
+ echo "$(date): $CONTAINER_NAME started successfully" >> "$LOGGING_FILE"
+
+ # Check if the container exited gracefully (with an exit status of 0)
+ if [ "$container_status" -eq 0 ]; then
+ echo "$(date): ColdClarity has completed" >> "$LOGGING_FILE"
+ break
+ else
+ # if we failed because the container started but problem is from app
+ echo "$(date): ERROR: ColdClarity did not execute properly (Exit Status: $container_status)." >> "$LOGGING_FILE"
+
+ # Increment the retry counter
+ RETRIES=$((RETRIES + 1))
+
+ # Check if we've exceeded the maximum number of retries
+ if [ $RETRIES -ge $MAX_RETRIES ]; then
+ echo "$(date): ERROR: Maximum number of retries reached. Exiting." >> "$LOGGING_FILE"
+ exit 1
+ else
+ echo "$(date): ERROR: Retrying (Attempt $RETRIES)..." >> "$LOGGING_FILE"
+ sleep 5
+ fi
+ fi
+ else
+ echo "$(date): ERROR Container failed to start" >> "$LOGGING_FILE"
+ # Increment the retry counter
+ RETRIES=$((RETRIES + 1))
+
+ # Check if we've exceeded the maximum number of retries
+ if [ $RETRIES -ge $MAX_RETRIES ]; then
+ echo "$(date): ERROR: Maximum number of retries reached. Exiting." >> "$LOGGING_FILE"
+ exit 1
+ else
+ echo "$(date): Retrying (Attempt $RETRIES)..." >> "$LOGGING_FILE"
+ sleep 5
+ fi
+
+ fi
+done
+
+
diff --git a/ise_control.py b/ise_control.py
new file mode 100755
index 0000000..c3de619
--- /dev/null
+++ b/ise_control.py
@@ -0,0 +1,329 @@
+import base64
+import json
+
+import pandas as pd
+import requests
+from tqdm import tqdm
+
+from utilities import Rutils, log_collector
+from requests_pkcs12 import Pkcs12Adapter
+from os import getpid
+
+requests.packages.urllib3.disable_warnings()
+
+
+class ISE:
+ HEADER_DATA = {
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:106.0) Gecko/20100101 Firefox/106.0',
+ }
+ UTILS = Rutils()
+
+ def __init__(self, config: str = "config.yaml"):
+ self.logger = log_collector()
+
+ # move config file to new folder
+ config = self.UTILS.create_file_path('Config_information', config)
+ self.config = self.UTILS.get_yaml_config(config, self)
+ # not ideal but meh
+ self.logger = log_collector(self.config.get('debug_console_login'))
+
+ # ISE username and password
+ if self.config['authentication']['text_based']['use']:
+ self.login_type = 'text'
+ if self.config['authentication']['pipeline']:
+ ise_username = self.config['authentication']['text_based']['username']
+ ise_password = self.config['authentication']['text_based']['password']
+ else:
+ ise_username = input("username: ")
+ ise_password = input("password: ")
+
+ # encode cred str to pass as a post msg to ISE
+ self.user = self.UTILS.encode_data(ise_username, base64=False)
+ self.password = self.UTILS.encode_data(ise_password, base64=False)
+ self.auth_source = self.config['authentication']['text_based']['auth_source']
+ # cert based
+ elif self.config['authentication']['cert_based']['use']:
+ self.login_type = 'cert'
+ cert_location = self.config['authentication']['cert_based']['cert_pfx_location']
+ # move cert to new folder
+ self.cert_location = self.UTILS.create_file_path('certificate_information', cert_location)
+ self.cert_passwd = self.config['authentication']['cert_based']['cert_password']
+
+ # auth information
+ self.ip = self.config['ise']['ip']
+ # session information
+ self.get_session()
+ self.init_ise_session()
+ self.phase = self.config['EndpointData']['phase']
+
+ def get_session(self):
+ self.logger.debug('Obtaining Session Object')
+ self.session = requests.Session()
+ self.session.verify = False
+
+ def init_ise_session(self):
+ url_csrf = f"https://{self.ip}/admin/JavaScriptServlet"
+ # obtain CSRF token
+ token_info = None
+ csrf_header = self.HEADER_DATA.copy()
+ csrf_header['FETCH-CSRF-TOKEN'] = '1'
+ # Needed FOR USER/PASS AUTH
+ if self.login_type == 'text':
+ self.session.get(f'https://{self.ip}/admin/', headers=csrf_header)
+
+ response = self.session.post(url_csrf, headers=csrf_header, data={})
+ if response.status_code == 200:
+ if 'CSRF' in response.text:
+ token_info = response.text.split(':')
+ self.csrf_token = {token_info[0]: token_info[1]}
+
+ if self.login_type == 'text':
+ url_login = f"https://{self.ip}/admin/LoginAction.do"
+ login_payload = f"username={self.user}" \
+ f"&password={self.password}" \
+ f"&samlLogin=false" \
+ f"&rememberme=on" \
+ f"&name={self.user}" \
+ f"&password={self.password}" \
+ f"&authType={self.auth_source}" \
+ f"&newPassword=" \
+ f"&destinationURL=" \
+ f"&CSRFTokenNameValue={token_info[0]}%3D{token_info[1]}" \
+ f"&OWASP_CSRFTOKEN={token_info[1]}" \
+ f"&locale=en&" \
+ f"hasSelectedLocale=false" \
+ # f"&isPreLoginBannerAccepted=true"
+ else:
+ url_login = f"https://{self.ip}/admin/"
+ login_payload = "preloginbanner=displayed"
+ self.session.mount(f"https://{self.ip}", Pkcs12Adapter(pkcs12_filename=self.cert_location, pkcs12_password=self.cert_passwd))
+
+ login_header = self.HEADER_DATA.copy()
+ login_header['Referer'] = f'https://{self.ip}admin/'
+ login_header['Content-Type'] = 'application/x-www-form-urlencoded'
+ response = self.session.post(url_login, data=login_payload, headers=login_header, verify=False, allow_redirects=True)
+ if response.status_code == 200:
+ if 'lastLoginSuccess' in response.text:
+ self.HEADER_DATA.update(self.csrf_token)
+ self.logger.debug('CSRF TOKEN Obtained')
+ self.logger.info('Authentication Successful')
+ return True
+ self.logger.critical('Authentication Failed, Please Check Configuration and Try Again')
+ quit()
+
+ def logout_ise_session(self):
+ self.session.get(f'https://{self.ip}/admin/logout.jsp')
+
+ def get_all_endpoint_data(self):
+ endpoints = []
+ step_page = 1
+ control_size = 500
+ while True:
+ # step thru endpoint pages
+ search_field = f'status=CONTEXT_EXTACT_MATCH_connected' \
+ f'&columns=' \
+ f'&sortBy=MACAddress' \
+ f'&startAt={step_page}' \
+ f'&pageSize={control_size}' \
+ f'&total_pages=5000' \
+ f'&total_entries={control_size}'
+ if not bool(self.config.get('only_connected')):
+ search_field = search_field.replace('status=CONTEXT_EXTACT_MATCH_connected&', '')
+
+ # change header for search params
+ header = self.HEADER_DATA.copy()
+ header['_QPH_'] = self.UTILS.encode_data(search_field)
+ response = self.session.get(f'https://{self.ip}/admin/rs/uiapi/visibility', headers=header)
+
+ if response.status_code == 200:
+ ep_data = response.json()
+ if len(ep_data) > 0:
+ endpoints = endpoints + ep_data
+ step_page += 1
+ else:
+ break
+ else:
+ self.logger.critical(f'received HTTP CODE {response.status_code} terminating')
+ raise RuntimeError
+
+ # clean list and transform json str to dicts to load into DF
+ endpoints = list(set(endpoints))
+ endpoints = [json.loads(epd) for epd in endpoints]
+ self.logger.info(f'Gathered {len(endpoints)} endpoints from ISE')
+ self.endpoints = pd.DataFrame(endpoints)
+
+ def get_endpoint_data(self, mac_address,pbar_func=None):
+ self.logger.debug(f'spawning new process for endpoint_data on {getpid()}')
+ # Mac addr must be 11:11:11:11:11:11 notation
+ response = self.session.get(f'https://{self.ip}/admin/rs/uiapi/visibility/endpoint/{mac_address}', headers=self.HEADER_DATA)
+ # if we are using progress bar increment it
+ if pbar_func:
+ pbar_func.update(1)
+ if response.status_code == 200:
+ ep_info = response.json()
+ return ep_info
+ self.logger.debug(f'Could not receive data for mac address: {mac_address}')
+
+ def get_metadata_from_endpoints(self, specific: str = False):
+ pbar = tqdm(desc='Getting Endpoint Metadata',total=len(self.endpoints['MACAddress']),colour='red')
+ try:
+ if specific:
+ self.endpoints[specific] = self.endpoints['MACAddress'].apply(lambda x: self.get_endpoint_data(x,pbar).get(specific))
+ else:
+ # gather macs and get all attr from them
+ ep_name_list = self.endpoints['MACAddress'].to_list()
+ ep_data = [self.get_endpoint_data(i,pbar) for i in ep_name_list]
+ self.endpoints = pd.DataFrame(ep_data)
+ except Exception as execpt_error:
+ self.logger.debug(f'META_PILL_ERROR: {execpt_error}')
+ if specific:
+ self.endpoints[specific] = self.endpoints['Calling-Station-ID'].apply(lambda x: self.get_endpoint_data(x,pbar).get(specific))
+ else:
+ # gather macs and get all attr from them
+ ep_name_list = self.endpoints['Calling-Station-ID'].to_list()
+ ep_data = [self.get_endpoint_data(i,pbar) for i in ep_name_list]
+ self.endpoints = pd.DataFrame(ep_data)
+ pbar.close()
+ self.endpoints.replace({None: 'unknown'}, inplace=True)
+
+ def get_license_info(self):
+ self.logger.debug('Collecting primary node SN')
+ header = self.HEADER_DATA.copy()
+
+ license_field = 'command=loadSlConfigDetail&dojo.preventCache=1664971537253'
+ header['_QPH_'] = self.UTILS.encode_data(license_field)
+ header['Content-Type'] = 'application/x-www-form-urlencoded'
+
+ response = self.session.get(f'https://{self.ip}/admin/licenseAction.do', headers=header)
+ if response.status_code == 200:
+ license_data = response.json()
+ self.logger.info('Obtained Device Serial Number')
+ return license_data['serialNo']
+ self.logger.debug(f'Could not obtain primary node SN - Received HTTP status code:{str(response.status_code)}')
+
+ def get_endpoint_software_info(self):
+ # applications data
+ host_sw = 'pageType=app&columns=productName%2Cversion%2CvendorName%2Ccategories%2CoperatingSystem%2CnoOfDevicesPerApp&sortBy=productName&startAt=1&pageSize=10000'
+ # transform to base64 then into the str representation of it
+ host_sw = base64.b64encode(str.encode(host_sw)).decode('utf-8')
+ # session cookie are persistence so only need to add this header that was implemented from the JS caller
+ headers = {'_QPH_': host_sw}
+ url = f"https://{self.ip}/admin/rs/uiapi/visibility"
+ self.sw_catalog = self.session.get(url, headers=headers)
+
+ def get_endpoint_hardware_info(self, mac_address, high_level=False):
+ url = f"https://{self.ip}/admin/rs/uiapi/hwvisibility"
+ if not high_level:
+ # can only get data one at a time per mac
+ header_data = f'columns=NoOfDevicesPerHw%2CMACAddress&sortBy=name&MACAddress={mac_address}&startAt=1&pageSize=10000'
+ else:
+ header_data = 'pageType=hw&' \
+ 'columns=MACAddress,manufacture,serialNum,noOfAttachments,cpuUsage,memoryUsage,hdUsage,NAS-Port-Id,status,NetworkDeviceName,PhoneID,ip&' \
+ 'sortBy=MACAddress&' \
+ 'startAt=1&' \
+ 'pageSize=10&' \
+ 'total_pages=1&' \
+ 'total_entries=1'
+
+ # transform to base64 then into the str representation of it
+ header_data = base64.b64encode(str.encode(header_data)).decode('utf-8')
+ # session cookie are persistence so only need to add this header that was implemented from the JS caller
+ header = self.HEADER_DATA.copy()
+ header['_QPH_'] = header_data
+ response = self.session.get(url, headers=header)
+ # so we dont break compability with old caller in report_data
+ if not high_level:
+ return response
+
+ if response.status_code == 200:
+ try:
+ hw_data = json.loads(response.json()[0])
+ except Exception as error:
+ self.logger.debug(f'Could not receive data for mac address: {mac_address} error: {str(error)}')
+ hw_data = 'None'
+ return hw_data
+
+ def special_reporting_data(self):
+ special_rep = self.config['special_reporting']
+ reporting_location = special_rep.get('reporting_location')
+ find_files = special_rep.get('files_to_look_for')
+ filter_list = special_rep.get('filter_list')
+ special_items = special_rep.get('filter_specifics')
+ attr_to_look_for = special_rep.get('get_attribute_from_endpoint')
+ fnames = self.UTILS.get_files_from_loc(reporting_location, find_files)
+ # df holder
+ self.endpoints = pd.DataFrame([])
+ for f in fnames:
+ ep_df = pd.read_csv(f'{reporting_location}/{f}')
+ ep_df = self.filter_data(ep_df, filter_list, special_items)
+ self.endpoints = pd.concat([self.endpoints, ep_df], ignore_index=True)
+ self.UTILS.create_file_path('archive', f, parent_dir=reporting_location)
+ self.get_metadata_from_endpoints(attr_to_look_for)
+ self.logger.info('Endpoint special data collection complete')
+
+ def join_hw_data(self):
+ try:
+ ep_name = self.endpoints['Calling-Station-ID'][self.endpoints['PostureReport'] != 'unknown'].tolist()
+ except Exception as error:
+ self.logger.exception(f'somethings wrong with the dataframe....:\n {error} \n\n QUITING')
+ self.logout_ise_session()
+ return
+ hw_data = [self.get_endpoint_hardware_info(i.replace('-',':'),high_level=True) for i in ep_name]
+ hw_data = pd.DataFrame(hw_data)
+ # conform hw data to match self endpoints so we can merge them
+ hw_data.rename(columns={'MACAddress':'Calling-Station-ID'},inplace=True)
+ # since we might not have anything in the df lets error check and if it doesnt skip hw processing
+ try:
+ hw_data['Calling-Station-ID'] = hw_data['Calling-Station-ID'].apply(lambda x: x.replace(':','-'))
+ self.endpoints = pd.concat([self.endpoints, hw_data], axis=1)
+ self.endpoints.replace({None: 'unknown'}, inplace=True)
+ except Exception as error:
+ self.logger.exception(f'somethings wrong with the dataframe....:\n {error} \n\n QUITING')
+ return
+
+ def filter_data(self, raw_df: pd.DataFrame, filter_list: list, data_matching: dict = None):
+ raw_df.drop(columns=filter_list, inplace=True)
+ # if we have specifics we want to match on
+ if data_matching:
+ for k, v in data_matching.items():
+ # try to see if we fit a usecase if not keep going
+ try:
+ raw_df = raw_df[raw_df[k].astype(int) > v]
+ continue
+ except Exception as error:
+ self.logger.debug(error)
+
+ try:
+ raw_df = raw_df[raw_df[k].str.contains(v)]
+ continue
+ except Exception as error:
+ self.logger.debug(error)
+ return raw_df
+
+ def retrieve_endpoint_data(self):
+ # deployment ID
+ self.sn = self.get_license_info()
+ self.endpoint_policies = None
+ self.logger.debug('Collecting endpoint data')
+ self.get_all_endpoint_data()
+ # pull N or all
+ if bool(self.config.get('test_endpoint_pull')):
+ self.logger.info(f'Sample Size of {self.config.get("test_endpoint_pull")} Endpoints being used.')
+ self.endpoints = self.endpoints.loc[:self.config.get('test_endpoint_pull')]
+
+ # since we dont need that much info in step 1 just pull the logical profile else pull all data
+ if self.config['EndpointData']['phase'] == 1:
+ self.get_metadata_from_endpoints(specific='LogicalProfile')
+ elif self.config['EndpointData']['phase'] == 2:
+ self.get_metadata_from_endpoints()
+ # need to get hardware serials also
+ self.join_hw_data()
+ # since ISE doesn't de-conflict logical profiles when two logical profiles are assigned to the same endpoint, take the first res. for more see FAQ
+ self.endpoints['LogicalProfile'] = self.endpoints['LogicalProfile'].apply(lambda x: x.split(',')[0])
+ self.logger.info('Endpoint data collection complete')
+ self.logout_ise_session()
+
+
+if __name__ == '__main__':
+ ise = ISE()
+ ise.retrieve_endpoint_data()
diff --git a/messaging.py b/messaging.py
new file mode 100755
index 0000000..4238779
--- /dev/null
+++ b/messaging.py
@@ -0,0 +1,108 @@
+import mimetypes
+import smtplib
+import ssl
+from email import encoders
+from email.mime.base import MIMEBase
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+from email.mime.application import MIMEApplication
+from utilities import Rutils, log_collector
+
+
+class Messaging:
+ UTILS = Rutils()
+
+ def __init__(self, config_data: dict):
+ self.cfg = config_data
+ self.smtp_server = self.cfg['smtp']['server']
+ self.port = self.cfg['smtp']['port']
+ self.sender_email = self.cfg['smtp']['email']
+ self.password = self.cfg['smtp']['password']
+ self.dest_email = self.cfg['smtp']['destination_email']
+ self.text_body = self.cfg['smtp']['body']
+ self.send_cc = self.cfg['smtp']['destination_email_cc'] if self.cfg['smtp']['destination_email_cc'] else None
+ self.reporting_name = self.cfg["report"]["program name"]
+ self.logger = log_collector()
+
+ def prep_message(self, attachment_name: str, msg_attac_loc_or_buf):
+ message = MIMEMultipart("alternative")
+ # if we need to use a alt name
+ if not self.cfg.get('special_reporting').get('use'):
+ message["Subject"] = f"{self.cfg['report']['organization']} {self.reporting_name} step {self.cfg['EndpointData']['step']} Interim Report"
+ else:
+ message["Subject"] = self.cfg['smtp']['alt_subject']
+ message["From"] = self.sender_email
+ message["To"] = self.dest_email
+ if self.send_cc is not None:
+ message["Cc"] = ', '.join(self.send_cc)
+
+ # message body
+ message.attach(MIMEText(self.text_body, 'plain'))
+ # message attachment
+ try:
+ ctype, encoding = mimetypes.guess_type(msg_attac_loc_or_buf)
+ if ctype is None or encoding is not None:
+ ctype = "application/octet-stream"
+ maintype, subtype = ctype.split("/", 1)
+
+ with open(msg_attac_loc_or_buf, "rb") as fp:
+ part = MIMEBase(maintype, subtype)
+ part.set_payload(fp.read())
+ except Exception as error:
+ self.logger.debug(f'ISE_MESSAGING: {error}')
+ part = MIMEApplication(self.UTILS.df_to_string_buffer(msg_attac_loc_or_buf))
+
+ encoders.encode_base64(part)
+ part.add_header("Content-Disposition", f"attachment; filename={attachment_name}", )
+ message.attach(part)
+ return message
+
+ def send_message(self, msg_attac_loc_or_buf, attachment_name=None):
+ if not attachment_name:
+ if '/' in msg_attac_loc_or_buf:
+ attachment_name = msg_attac_loc_or_buf.split('/')[-1]
+ else:
+ attachment_name = msg_attac_loc_or_buf.split('\/')[-1]
+ else:
+ attachment_name = attachment_name
+
+ # Test case
+ if self.cfg.get('test_messaging_svc'):
+ message = self.test_prep_message()
+ else:
+ message = self.prep_message(attachment_name, msg_attac_loc_or_buf)
+
+ if self.cfg['smtp']['port'] == 587:
+ # Create a secure SSL context
+ context = ssl._create_unverified_context()
+ else:
+ context = None
+
+ # Try to log in to server and send email
+ try:
+ server = smtplib.SMTP(self.smtp_server, self.port)
+ # SMTP-TLS
+ if context is not None:
+ server.ehlo()
+ server.starttls(context=context)
+ server.ehlo()
+
+ if self.password:
+ server.login(self.sender_email, self.password)
+
+ server.send_message(message)
+ server.quit()
+ except Exception as e:
+ print(e)
+
+ def test_prep_message(self):
+ message = MIMEMultipart("alternative")
+ message["Subject"] = f"{self.cfg['report']['organization']} {self.reporting_name} step {self.cfg['EndpointData']['step']} Report"
+ message["From"] = self.sender_email
+ message["To"] = self.dest_email
+ if self.send_cc is not None:
+ message["Cc"] = ', '.join(self.send_cc)
+
+ # message body
+ message.attach(MIMEText(self.text_body, 'plain'))
+ return message
diff --git a/report_data.py b/report_data.py
new file mode 100755
index 0000000..ef605d9
--- /dev/null
+++ b/report_data.py
@@ -0,0 +1,223 @@
+import csv
+import time
+from json import loads
+from os import path
+import pandas as pd
+from tqdm import tqdm
+
+from ise_control import ISE
+from messaging import Messaging
+from utilities import Rutils
+
+pd.options.mode.chained_assignment = None
+
+
+class ISEReport:
+ def __init__(self, config_file='config.yaml'):
+ self.timestr = time.strftime("%d%b%Y")
+ self.top_dir = path.dirname(path.abspath(__file__))
+ self.utils = Rutils()
+
+ self.ise = ISE(config=config_file)
+
+ self.ise_summary_list = self.ise.config.get('endpoint_buckets_match')
+ self.custom_profiles = self.ise.config.get('custom_profiles_match')
+ # get title of the report
+ self.reporting_name = self.ise.config["report"]["program name"]
+
+ def create_ise_endpoint_report(self, incl_report_type=None):
+
+ # special reports
+ if self.ise.config.get('special_reporting').get('use'):
+ self.create_special_reporting()
+ quit()
+
+ # reg report
+ fname = self.utils.create_file_path('endpoint_reports', f'{self.ise.config["report"]["organization"]}_step{self.ise.phase}_{self.timestr}.csv')
+ # pull ep data
+ self.ise.retrieve_endpoint_data()
+ ise_eps = self.ise.endpoints.copy()
+
+ if incl_report_type == 'ep_attributes':
+ workstation_mac_addrs = ise_eps.loc[ise_eps['EndPointPolicy'].str.contains('Workstation')]['MACAddress'].to_list()
+ self.create_ise_sw_hw_report(type_='software')
+ self.create_ise_sw_hw_report(type_='hardware', hw_mac_list=workstation_mac_addrs)
+
+ # change profile of custom profile to fit report standards if custom list exist
+ if self.ise.config.get('custom_profiles_match') is not None:
+ custom_profiles_match = self.ise.config.get('custom_profiles_match')
+ # fold list of dicts to one list to use in df op
+ custom_profiles_match = {k: v for dict_item in custom_profiles_match for k, v in dict_item.items()}
+ ise_eps["EndPointPolicy"].replace(custom_profiles_match, inplace=True)
+
+ with open(fname, 'w+', newline='') as f:
+ writer = csv.writer(f)
+ writer.writerow([self.ise.config['report']['policy_name'], 'Active'])
+ writer.writerow([f'{self.reporting_name} Interim Reporting'])
+ writer.writerow([f'{self.reporting_name}-Reporting Information'])
+ writer.writerow(['Owner: ' + self.ise.config['report']['owner']])
+ writer.writerow(['Area of Operations: ' + self.ise.config['report']['area_of_operation']])
+ writer.writerow([f'Deployment ID:{self.ise.sn}'])
+ writer.writerow([f'{self.reporting_name}-Step{self.ise.phase}-2.0-MER-Information'])
+ # logical profile summary
+ if self.ise.config['EndpointData']['phase'] == 1:
+ self.ise_step_1(writer, ise_eps)
+ elif self.ise.config['EndpointData']['phase'] == 2:
+ self.ise_step_2(writer)
+
+ self.ise.logger.info(f'Report Done!. Save file at: {fname}')
+
+ # send email
+ if self.ise.config["report"]['send_email']:
+ messager = Messaging(self.ise.config)
+ messager.send_message(msg_attac_loc_or_buf=fname)
+
+ def ise_step_1(self, writer, ise_eps):
+ writer.writerow([f'{self.reporting_name}-Step{self.ise.phase}-2.1 {self.ise.config["report"]["prepared_for"]} Device Category', self.ise.endpoints.shape[0]])
+ for cat in self.ise_summary_list:
+ logical_group = ise_eps[ise_eps['LogicalProfile'] == cat]
+ if not logical_group.empty:
+ writer.writerow([cat, logical_group.shape[0]])
+ else:
+ writer.writerow([cat, 0])
+ # endpoint policy summary
+ writer.writerow([f'{self.reporting_name}-Step{self.ise.phase}-2.2 Operating System Summary', self.ise.endpoints.shape[0]])
+ grouped_eps = ise_eps.groupby(by=['EndPointPolicy'])
+ grouped_eps_names = list(grouped_eps.groups)
+ for gp_name in grouped_eps_names:
+ writer.writerow([gp_name, grouped_eps.get_group(gp_name).shape[0]])
+
+ def ise_step_2(self, writer):
+ # get Posture conditions
+ posture_cons = self.ise.config['step2_conditions_match']
+ # check if it exist if so join it to origin
+ extended_pos_cons = self.ise.config.get('step2_conditions_custom')
+ if extended_pos_cons:
+ posture_cons = posture_cons + extended_pos_cons
+
+ # normalize df
+ step2_data = self.ise.endpoints.copy()
+ step2_data.columns = step2_data.columns.str.lower()
+ step2_data = step2_data.apply(lambda x: x.astype(str).str.lower())
+
+ # total active endpoints
+ writer.writerow(['Total Discovered Endpoints', step2_data.shape[0]])
+ # devices that can posture
+ writer.writerow(['Total Managed Endpoints', step2_data[step2_data["devicecompliance"] != 'unknown'].shape[0]])
+ # device that cant posture
+ writer.writerow(['Total Non-Managed Endpoints', step2_data[step2_data["devicecompliance"] == 'unknown'].shape[0]])
+ # devices that can auth via 8021.x
+ writer.writerow(['Total 802.1X Endpoints', step2_data[step2_data["authenticationmethod"].isin(['x509_pki'])].shape[0]])
+ # devices that are MAB
+ writer.writerow(['Total MAB Endpoints', step2_data[step2_data["authenticationmethod"] == 'lookup'].shape[0]])
+ # how many profiles we have
+ writer.writerow(['Total Profiled Endpoints', step2_data[step2_data["endpointpolicy"] != 'unknown'].shape[0]])
+ # if we are doing webauth or some type of auth???
+ writer.writerow(['Total Authenticated Other (SNMP etc)', step2_data[~step2_data["authenticationmethod"].isin(['unknown', 'lookup', 'x509_pki'])].shape[0]])
+
+ # reporting Break
+ writer.writerow([])
+
+ # only get user endpoints
+ non_svr_ep = step2_data[~step2_data['ad-operating-system'].str.contains('windows server | red hat | rhel', regex=True)]
+ # how many user endpoints are reporting posture
+ writer.writerow(['Non-svr/Wkstn Managed Devices', non_svr_ep[non_svr_ep["devicecompliance"] != 'unknown'].shape[0]])
+ # how many are not
+ writer.writerow(['Non-svr/Wkstn Non-Managed Devices', non_svr_ep[non_svr_ep["devicecompliance"] == 'unknown'].shape[0]])
+
+ # reporting Break
+ writer.writerow([])
+
+ # just all logically profiled Workstation and Servers
+ wrk_svr_data = step2_data[step2_data['logicalprofile'] == 'workstations and servers']
+ writer.writerow(['Total Workstations and Servers', wrk_svr_data.shape[0]])
+ # wrk/svrs not/are in posture
+ writer.writerow(['Unmanaged Workstations and Servers', wrk_svr_data[wrk_svr_data["devicecompliance"] == 'unknown'].shape[0]])
+ writer.writerow(['Managed Workstations and Servers', wrk_svr_data[wrk_svr_data["devicecompliance"] != 'unknown'].shape[0]])
+
+ # reporting Break
+ writer.writerow([])
+
+ # Posture compliance
+ pos_stat = step2_data[step2_data["devicecompliance"] != 'unknown']
+ # get posture status by condition
+ for match_conditions in posture_cons:
+ for k, v in match_conditions.items():
+ k, v = k.lower(), v.lower()
+ pos_stat[f'{k}_hits'] = pos_stat['posturereport'].apply(lambda x: self.posture_report_spliter(x, v))
+
+ # get all k values from matched conditions for slotting
+ matched_keys = [k for match_conditions in posture_cons for k in match_conditions.keys()]
+ # write the total hits per condition
+ for mk in matched_keys:
+ writer.writerow([f'{mk} Compliant', pos_stat[pos_stat[f'{mk}_hits'.lower()] == 'passed'].shape[0]])
+ writer.writerow([f'{mk} Non-Compliant', pos_stat[pos_stat[f'{mk}_hits'.lower()] == 'failed'].shape[0]])
+
+ # collect bios serials and sum
+ writer.writerow(['Serial Number Collected', step2_data[step2_data['serial number'] != 'unknown'].shape[0]])
+
+ @staticmethod
+ def posture_report_spliter(x, get_policy):
+ # split by the conditions matched
+ posture_report = x.split(',')
+ # now split from con name to pass/fail
+ for i in posture_report:
+ # check if we have a policy match
+ if f'{get_policy}\\' in i:
+ # parse and return whether this device passed if not return not_applicable
+ return i.split(';')[1].strip('\\')
+ return 'not_applicable'
+
+ def create_ise_sw_hw_report(self, type_='software', hw_mac_list: list = None):
+ # function import until we plop this on the devops server
+ fname = self.utils.create_file_path('endpoint_reports', f'{self.ise.config["report"]["organization"]}_step{self.ise.phase}_{self.timestr}.csv')
+ vis = None
+ if type_ == 'software':
+ self.ise.logger.info('Collecting Endpoint software information from ISE')
+ self.ise.get_endpoint_software_info()
+ vis = pd.DataFrame(loads(self.ise.sw_catalog.text))
+ vis.drop(columns=['id', 'productId'], inplace=True)
+ else:
+ self.ise.logger.info('Collecting Endpoint hardware information from ISE')
+ hw_count = 0
+ hw_attr_list = []
+ if hw_mac_list is not None:
+ for hw_mac in tqdm(hw_mac_list, total=(len(hw_mac_list)), desc="Getting Hardware info from endpoints", colour='red'):
+ hw_catalog = self.ise.get_endpoint_hardware_info(hw_mac)
+ try:
+ hw_catalog = loads(hw_catalog.text)
+ if len(hw_catalog) < 1:
+ # No Hardware Endpoint Data to report
+ raise ValueError
+ hw_count += 1
+ for hwa in hw_catalog:
+ hw_attr_list.append(hwa)
+ except Exception as error:
+ self.ise.logger.debug(f'CHWR: {error}')
+ pass
+ # DONT KNOW WHAT THE FUCK IS THAT
+ # hw_attr_list = [dict(t) for t in {tuple(d.items()) for d in l}]
+ if len(hw_attr_list) < 1:
+ self.ise.logger.error(f'No {type_} Data to Report')
+ return
+ vis = pd.DataFrame(hw_attr_list)
+ vis['endpoint_count'] = hw_count
+ vis.drop(columns=['vendorId', 'productId'], inplace=True)
+ vis.to_csv(fname, index=False)
+ self.ise.logger.info(f'Endpoint {type_} Report Done! Saved to: {fname}')
+ # send email
+ if self.ise.config["report"]['send_email']:
+ messager = Messaging(self.ise.config)
+ messager.send_message(msg_attac_loc_or_buf=fname)
+
+ def create_special_reporting(self):
+ self.ise.special_reporting_data()
+ # send email
+ if self.ise.config["report"]['send_email']:
+ messager = Messaging(self.ise.config)
+ messager.send_message(msg_attac_loc_or_buf=self.ise.endpoints, attachment_name=self.ise.config['special_reporting']['name_of_file_to_send'])
+
+
+if __name__ == '__main__':
+ c2r = ISEReport()
+ c2r.create_ise_endpoint_report(incl_report_type='None')
diff --git a/requests_pkcs12.py b/requests_pkcs12.py
new file mode 100644
index 0000000..0d2ebad
--- /dev/null
+++ b/requests_pkcs12.py
@@ -0,0 +1,186 @@
+from __future__ import division, print_function, unicode_literals
+
+__copyright__ = '''\
+Copyright (C) m-click.aero GmbH
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+'''
+# https://github.com/m-click/requests_pkcs12
+import cryptography.hazmat.backends
+import cryptography.hazmat.primitives.asymmetric.rsa
+import cryptography.hazmat.primitives.hashes
+import cryptography.hazmat.primitives.serialization.pkcs12
+import cryptography.x509.oid
+import datetime
+import os
+import requests.adapters
+import ssl
+import tempfile
+
+try:
+ from ssl import PROTOCOL_TLS as default_ssl_protocol
+except ImportError:
+ from ssl import PROTOCOL_SSLv23 as default_ssl_protocol
+
+def check_cert_not_after(cert):
+ cert_not_after = cert.not_valid_after
+ if cert_not_after < datetime.datetime.utcnow():
+ raise ValueError('Client certificate expired: Not After: {cert_not_after:%Y-%m-%d %H:%M:%SZ}'.format(**locals()))
+
+
+def create_ssl_sslcontext(pkcs12_data, pkcs12_password_bytes, ssl_protocol=default_ssl_protocol):
+ private_key, cert, ca_certs = cryptography.hazmat.primitives.serialization.pkcs12.load_key_and_certificates(
+ pkcs12_data,
+ pkcs12_password_bytes
+ )
+ check_cert_not_after(cert)
+ ssl_context = ssl.SSLContext(ssl_protocol)
+ with tempfile.NamedTemporaryFile(delete=False) as c:
+ try:
+ pk_buf = private_key.private_bytes(
+ cryptography.hazmat.primitives.serialization.Encoding.PEM,
+ cryptography.hazmat.primitives.serialization.PrivateFormat.TraditionalOpenSSL,
+ cryptography.hazmat.primitives.serialization.BestAvailableEncryption(password=pkcs12_password_bytes)
+ )
+ c.write(pk_buf)
+ buf = cert.public_bytes(cryptography.hazmat.primitives.serialization.Encoding.PEM)
+ c.write(buf)
+ if ca_certs:
+ for ca_cert in ca_certs:
+ check_cert_not_after(ca_cert)
+ buf = ca_cert.public_bytes(cryptography.hazmat.primitives.serialization.Encoding.PEM)
+ c.write(buf)
+ c.flush()
+ c.close()
+ ssl_context.load_cert_chain(c.name, password=pkcs12_password_bytes)
+ finally:
+ os.remove(c.name)
+ return ssl_context
+
+class Pkcs12Adapter(requests.adapters.HTTPAdapter):
+
+ def __init__(self, *args, **kwargs):
+ pkcs12_data = kwargs.pop('pkcs12_data', None)
+ pkcs12_filename = kwargs.pop('pkcs12_filename', None)
+ pkcs12_password = kwargs.pop('pkcs12_password', None)
+ ssl_protocol = kwargs.pop('ssl_protocol', default_ssl_protocol)
+ if pkcs12_data is None and pkcs12_filename is None:
+ raise ValueError('Both arguments "pkcs12_data" and "pkcs12_filename" are missing')
+ if pkcs12_data is not None and pkcs12_filename is not None:
+ raise ValueError('Argument "pkcs12_data" conflicts with "pkcs12_filename"')
+ if pkcs12_password is None:
+ raise ValueError('Argument "pkcs12_password" is missing')
+ if pkcs12_filename is not None:
+ with open(pkcs12_filename, 'rb') as pkcs12_file:
+ pkcs12_data = pkcs12_file.read()
+ if isinstance(pkcs12_password, bytes):
+ pkcs12_password_bytes = pkcs12_password
+ else:
+ pkcs12_password_bytes = pkcs12_password.encode('utf8')
+ self.ssl_context = create_ssl_sslcontext(pkcs12_data, pkcs12_password_bytes, ssl_protocol)
+ super(Pkcs12Adapter, self).__init__(*args, **kwargs)
+
+ def init_poolmanager(self, *args, **kwargs):
+ if self.ssl_context:
+ kwargs['ssl_context'] = self.ssl_context
+ return super(Pkcs12Adapter, self).init_poolmanager(*args, **kwargs)
+
+ def proxy_manager_for(self, *args, **kwargs):
+ if self.ssl_context:
+ kwargs['ssl_context'] = self.ssl_context
+ return super(Pkcs12Adapter, self).proxy_manager_for(*args, **kwargs)
+
+def request(*args, **kwargs):
+ pkcs12_data = kwargs.pop('pkcs12_data', None)
+ pkcs12_filename = kwargs.pop('pkcs12_filename', None)
+ pkcs12_password = kwargs.pop('pkcs12_password', None)
+ ssl_protocol = kwargs.pop('ssl_protocol', default_ssl_protocol)
+ if pkcs12_data is None and pkcs12_filename is None and pkcs12_password is None:
+ return requests.request(*args, **kwargs)
+ if 'cert' in kwargs:
+ raise ValueError('Argument "cert" conflicts with "pkcs12_*" arguments')
+ with requests.Session() as session:
+ pkcs12_adapter = Pkcs12Adapter(
+ pkcs12_data=pkcs12_data,
+ pkcs12_filename=pkcs12_filename,
+ pkcs12_password=pkcs12_password,
+ ssl_protocol=ssl_protocol,
+ )
+ session.mount('https://', pkcs12_adapter)
+ return session.request(*args, **kwargs)
+
+def delete(*args, **kwargs):
+ return request('delete', *args, **kwargs)
+
+def get(*args, **kwargs):
+ kwargs.setdefault('allow_redirects', True)
+ return request('get', *args, **kwargs)
+
+def head(*args, **kwargs):
+ kwargs.setdefault('allow_redirects', False)
+ return request('head', *args, **kwargs)
+
+def options(*args, **kwargs):
+ kwargs.setdefault('allow_redirects', True)
+ return request('options', *args, **kwargs)
+
+def patch(*args, **kwargs):
+ return request('patch', *args, **kwargs)
+
+def post(*args, **kwargs):
+ return request('post', *args, **kwargs)
+
+def put(*args, **kwargs):
+ return request('put', *args, **kwargs)
+
+def selftest():
+ key = cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(public_exponent=65537, key_size=4096)
+ cert = cryptography.x509.CertificateBuilder().subject_name(
+ cryptography.x509.Name([
+ cryptography.x509.NameAttribute(cryptography.x509.oid.NameOID.COMMON_NAME, 'test'),
+ ])
+ ).issuer_name(
+ cryptography.x509.Name([
+ cryptography.x509.NameAttribute(cryptography.x509.oid.NameOID.COMMON_NAME, 'test'),
+ ])
+ ).public_key(
+ key.public_key()
+ ).serial_number(
+ cryptography.x509.random_serial_number()
+ ).not_valid_before(
+ datetime.datetime.utcnow()
+ ).not_valid_after(
+ datetime.datetime.utcnow() + datetime.timedelta(days=1)
+ ).sign(
+ key,
+ cryptography.hazmat.primitives.hashes.SHA512(),
+ cryptography.hazmat.backends.default_backend()
+ )
+ pkcs12_data = cryptography.hazmat.primitives.serialization.pkcs12.serialize_key_and_certificates(
+ name=b'test',
+ key=key,
+ cert=cert,
+ cas=[cert, cert, cert],
+ encryption_algorithm=cryptography.hazmat.primitives.serialization.BestAvailableEncryption(b'correcthorsebatterystaple')
+ )
+ response = get(
+ 'https://example.com/',
+ pkcs12_data=pkcs12_data,
+ pkcs12_password='correcthorsebatterystaple'
+ )
+ if response.status_code != 200:
+ raise Exception('Unexpected response: {response!r}'.format(**locals()))
+ print('Selftest succeeded.')
+
+if __name__ == '__main__':
+ selftest()
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
new file mode 100755
index 0000000..b13a872
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,5 @@
+cryptography
+pandas
+PyYAML
+requests
+tqdm
diff --git a/templates/config_templete.yaml b/templates/config_templete.yaml
new file mode 100755
index 0000000..00ed028
--- /dev/null
+++ b/templates/config_templete.yaml
@@ -0,0 +1,102 @@
+report:
+ policy_name: 'NAC Policy Name'
+ owner: 'einetworks'
+ area_of_operation: ' North Campus'
+ # the script will output the file in the same dir where it was ran, specify a path to change where you want to save it at.
+ destination_filepath: 'Absolute/Path/ISEDeviceReport.csv'
+ send_email: False
+ organization: 'einetworks'
+ prepared_for: 'John Doe'
+ program name: 'endpoint records'
+
+ise:
+ hostname: ''
+ ip: ''
+
+
+authentication:
+ text_based:
+ use: False
+ auth_source: 'Internal'
+ username: False
+ password: False
+ cert_based:
+ use: True
+ cert_pfx_location: 'ise_client_cert.pfx'
+ cert_password: False
+ #pipeline use ise_api creds in ise
+ pipeline: False
+
+smtp:
+ email: isereporter@mailrelay.local
+ password: False
+ server: mailrelay.local
+ port: 25
+ destination_email: bigbossman@mailrelay.local
+ destination_email_cc:
+ - otherpeoplewholikeuselessemails@mailrelay.local
+ body: prepared reports for review!
+
+# if you have custom profiles and want them to fall under another profile for the report in the key value enter the real
+# name and in the value portion enter the name it should go in the report
+custom_profiles_match:
+ - 'test': 'Unknown'
+ - 'test': 'Unknown'
+ - test': 'Unknown'
+ - 'test': 'Microsoft-Workstation'
+ - 'test': 'Microsoft-Workstation'
+ - 'test': 'Microsoft-Workstation'
+
+# logical buckets to which endpoints will be matched too. these are created from ISE logical profile
+endpoint_buckets_match:
+ - 'test'
+ - 'test'
+ - 'test'
+ - 'test'
+ - 'test'
+ - 'test'
+ - 'test'
+ - 'unknown'
+
+# if your doing step 2 you will need this to match the posture policy (we are matching on posture rule and NOT the
+# posture condition since one rule can have many conditions to be compliant) creating in ISE, enter the ISE created
+# policy the right (the key value)
+step2_conditions_match:
+ - anti_mw: example_anti_malware_policy_name
+ - patching: example_patching_policy_name
+ - fw: example_anti_fw_policy_name
+ - encrypt: example_disk_encrypt_policy_name
+
+# SAME RULES APPLIES AS ABOVE if more col are needed in the report post them here the key value (item to the left)
+# will be a column in the report, while the value with the amount
+step2_conditions_custom:
+ - usb: example_custom_policy_name
+
+
+# if you need a custom report thats already sitting in the repository server
+special_reporting:
+ use: False
+ reporting_location: '/path/to/reports'
+ files_to_look_for:
+ - 'test'
+ name_of_file_to_send: 'suff_to_send.csv'
+ filter_list:
+ - 'useless Col data'
+ filter_specifics:
+ 'ACCT_SESSION_TIME': 0
+ 'AUTHENTICATION_RULE': 'Allow Guest Users'
+ get_attribute_from_endpoint: 'MAC ADDRESS'
+
+# get all endpoints or just connected ones
+only_connected: True
+
+
+EndpointData:
+ step: 1
+
+
+
+# DIAG
+test_endpoint_pull: 0
+test_messaging_svc: False
+debug_console_login: False
\ No newline at end of file
diff --git a/templates/san.cnf b/templates/san.cnf
new file mode 100644
index 0000000..142b62c
--- /dev/null
+++ b/templates/san.cnf
@@ -0,0 +1,16 @@
+[req]
+distinguished_name = req_distinguished_name
+req_extensions = san_extensions
+prompt = no
+
+[req_distinguished_name]
+CN = YourCommonName
+
+[san_extensions]
+subjectAltName = @alt_names
+keyUsage = digitalSignature
+extendedKeyUsage = clientAuth, serverAuth
+
+[alt_names]
+DNS.1 = example.com
+
diff --git a/templates/self_signed_cert.bash b/templates/self_signed_cert.bash
new file mode 100644
index 0000000..c831f3b
--- /dev/null
+++ b/templates/self_signed_cert.bash
@@ -0,0 +1,23 @@
+# Generate the Root CA certificate
+openssl genrsa -aes256 -passout pass:CREATE_A_SECURE_PASSWORD -out ca.pass.key 4096
+openssl rsa -passin pass:CREATE_A_SECURE_PASSWORD -in ca.pass.key -out ca.key
+openssl req -new -x509 -days 1095 -key ca.key -out ca.crt -subj "/CN=$HOSTNAME"
+
+# create client cert
+openssl genrsa -aes256 -passout pass:CREATE_A_SECURE_PASSWORD -out ise_client_key.pass.key 4096
+openssl rsa -passin pass:CREATE_A_SECURE_PASSWORD -in ise_client_key.pass.key -out ise_client_key.key
+
+# PLEASE EDIT THE SAN.cnf FILE APPROPRIATELY
+openssl req -new -key ise_client_key.key -out ise_client_cert.csr -config san.cnf
+openssl req -in ise_client_cert.csr -text -noout
+
+# self sign the cert for 3 years!
+openssl x509 -req -days 365 -in ise_client_cert.csr -CA ca.crt -CAkey ca.key -out ise_client_cert.crt -CAcreateserial -req
+openssl x509 -in ise_client_cert.crt -text -noout
+
+# create a pk12(identity) cert with a exportable key password protected
+cat ise_client_key.key ise_client_cert.crt ca.crt > ise_client_cert.pem
+openssl pkcs12 -export -out ise_client_cert.pfx -inkey ise_client_key.key -in ise_client_cert.pem -certfile ca.crt
+
+# Give ISE the Root CA cert and when importing the self-signed cert make sure you elect to use the cert for admin auth.
+# you can delete all of the private keys. as you only need to keep the PFX and remember the password to use it.
\ No newline at end of file
diff --git a/term_access.py b/term_access.py
new file mode 100755
index 0000000..648ed42
--- /dev/null
+++ b/term_access.py
@@ -0,0 +1,17 @@
+from argparse import ArgumentParser
+
+from report_data import ISEReport
+
+
+def term_access():
+ parser = ArgumentParser(prog='coldClarity')
+ cold_args = parser.add_argument_group(title='coldClarity Fields')
+ cold_args.add_argument('--config_file', help='location of config file', default= 'config.yaml', type=str)
+ args = parser.parse_args()
+
+ c2r = ISEReport(config_file=args.config_file)
+ c2r.create_ise_endpoint_report()
+
+
+if __name__ == '__main__':
+ term_access()
diff --git a/utilities.py b/utilities.py
new file mode 100755
index 0000000..2b90060
--- /dev/null
+++ b/utilities.py
@@ -0,0 +1,113 @@
+from base64 import b64encode
+from gzip import open as gzopen
+from logging.handlers import TimedRotatingFileHandler
+from os import path, makedirs, rename, remove, replace,walk
+from urllib.parse import quote as url_quote
+from io import StringIO
+import yaml
+
+import logging
+
+
+class Rutils:
+
+ def verify_config(self, config):
+ return all(self.cfg[config].values())
+
+ def load_config(self, config="config_lab.yml"):
+ with open(config, 'r') as stream:
+ try:
+ self.cfg = yaml.safe_load(stream)
+ except yaml.YAMLError as exc:
+ print(exc)
+
+ def __init__(self):
+ self.cfg = None
+
+ @staticmethod
+ def create_file_path(folder: str, file_name: str,parent_dir=None):
+ parent_dir = path.dirname(path.abspath(__file__)) if not parent_dir else parent_dir
+ file_path = path.join(parent_dir,folder)
+
+ fName = f'{file_path}/{file_name}'
+ if not path.exists(f'{file_path}'):
+ makedirs(f'{file_path}')
+
+ # move file to correct dir if needed
+ if not path.exists(fName):
+ try:
+ replace(f'{parent_dir}/{file_name}', fName)
+ except:
+ # file has yet to be created or not in top path
+ pass
+
+ return fName
+
+ @staticmethod
+ def encode_data(data, base64=True):
+ if base64:
+ return b64encode(str.encode(data)).decode('utf-8')
+ else:
+ return url_quote(data, safe='')
+
+ @staticmethod
+ def get_yaml_config(config, self_instance):
+ if isinstance(config, str):
+ with open(config, 'r') as stream:
+ try:
+ return yaml.safe_load(stream)
+ except yaml.YAMLError as exc:
+ self_instance.logger.info(f'Error processing config file. Error recevied {exc}')
+
+ @staticmethod
+ def get_files_from_loc(fold_loc:str,files_to_look_for:list):
+ _, _, filenames = next(walk(fold_loc))
+ fnames = [names for names in filenames for filames in files_to_look_for if filames in names]
+ return fnames
+
+ @staticmethod
+ def df_to_string_buffer(df):
+ with StringIO() as buffer:
+ df.to_csv(buffer,index=False)
+ return buffer.getvalue()
+
+
+def log_collector(log_all=False,file_name='ise_reporting_logs.log'):
+ fName = Rutils().create_file_path('logging', file_name)
+
+ if not log_all:
+ logger = logging.getLogger('ColdClarity')
+ else:
+ logger = logging.getLogger()
+ import http.client as http_client
+ http_client.HTTPConnection.debuglevel = 1
+
+ logger.setLevel(logging.DEBUG)
+ if logger.hasHandlers():
+ logger.handlers = []
+
+ conHandler = logging.StreamHandler()
+ conHandler.setLevel(logging.INFO)
+ logformatCon = logging.Formatter('%(asctime)s %(levelname)s %(message)s', datefmt='%d-%b-%y %H:%M:%S')
+ conHandler.setFormatter(logformatCon)
+ logger.addHandler(conHandler)
+
+ fileHandler = TimedRotatingFileHandler(filename=fName, when='midnight', backupCount=90, interval=1)
+ fileHandler.setLevel(logging.DEBUG)
+ logformatfile = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s', datefmt='%d-%b-%y %H:%M:%S')
+ fileHandler.setFormatter(logformatfile)
+ fileHandler.rotator = GZipRotator()
+ logger.addHandler(fileHandler)
+ return logger
+
+
+class GZipRotator:
+
+ def __call__(self, source, dest):
+ rename(source, dest)
+ f_in = open(dest, 'rb')
+ f_out = gzopen("{}.gz".format(dest), 'wb')
+ f_out.writelines(f_in)
+ f_out.close()
+ f_in.close()
+ remove(dest)