Repository: SecUSo/privacy-friendly-netmonitor Branch: master Commit: c92753328596 Files: 152 Total size: 530.7 KB Directory structure: gitextract_et81zfgx/ ├── .github/ │ └── workflows/ │ └── changelog.yml ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING ├── LICENSE.txt ├── README.md ├── app/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ ├── de/ │ │ │ │ └── bjoernr/ │ │ │ │ └── ssllabs/ │ │ │ │ ├── Api.java │ │ │ │ ├── Console.java │ │ │ │ └── ConsoleUtilities.java │ │ │ └── org/ │ │ │ └── secuso/ │ │ │ └── privacyfriendlynetmonitor/ │ │ │ ├── Activities/ │ │ │ │ ├── AboutActivity.java │ │ │ │ ├── Adapter/ │ │ │ │ │ ├── AppListRecyclerAdapter.java │ │ │ │ │ ├── ExpandableHistoryListAdapter.java │ │ │ │ │ ├── ExpandableListAdapter.java │ │ │ │ │ ├── ExpandableReportAdapter.java │ │ │ │ │ ├── FragmentDayListAdapter.java │ │ │ │ │ └── PagerAdapter.java │ │ │ │ ├── AppConnections_Chart.java │ │ │ │ ├── BaseActivity.java │ │ │ │ ├── HelpActivity.java │ │ │ │ ├── HelpDataDump.java │ │ │ │ ├── HistoryActivity.java │ │ │ │ ├── HistoryDetailActivity.java │ │ │ │ ├── MainActivity.java │ │ │ │ ├── ReportDetailActivity.java │ │ │ │ ├── SelectHistoryAppsActivity.java │ │ │ │ ├── SettingsActivity.java │ │ │ │ ├── SplashActivity.java │ │ │ │ └── TutorialActivity.java │ │ │ ├── Assistant/ │ │ │ │ ├── AsyncCertVal.java │ │ │ │ ├── AsyncDNS.java │ │ │ │ ├── Const.java │ │ │ │ ├── ExecCom.java │ │ │ │ ├── KnownPorts.java │ │ │ │ ├── PrefManager.java │ │ │ │ ├── RunStore.java │ │ │ │ ├── TLType.java │ │ │ │ └── ToolBox.java │ │ │ ├── ConnectionAnalysis/ │ │ │ │ ├── Collector.java │ │ │ │ ├── Detector.java │ │ │ │ ├── PassiveService.java │ │ │ │ ├── Report.java │ │ │ │ └── ServiceHandler.java │ │ │ ├── DatabaseUtil/ │ │ │ │ ├── DBApp.java │ │ │ │ ├── GenerateReportEntities.java │ │ │ │ └── ReportEntity.java │ │ │ └── fragment/ │ │ │ ├── Fragment_day.java │ │ │ ├── Fragment_month.java │ │ │ └── Fragment_week.java │ │ └── res/ │ │ ├── drawable/ │ │ │ ├── background_border.xml │ │ │ ├── button_fullwidth.xml │ │ │ ├── ic_clear.xml │ │ │ ├── ic_delete.xml │ │ │ ├── ic_help.xml │ │ │ ├── ic_history.xml │ │ │ ├── ic_menu_info.xml │ │ │ ├── ic_play_arrow.xml │ │ │ ├── ic_refresh.xml │ │ │ ├── ic_search_white_24dp.xml │ │ │ ├── ic_settings.xml │ │ │ ├── ic_sort_white_24dp.xml │ │ │ ├── ic_stop.xml │ │ │ ├── ic_tutorial.xml │ │ │ ├── ic_tutorial_inverted.xml │ │ │ └── splash_screen.xml │ │ ├── layout/ │ │ │ ├── activity_about.xml │ │ │ ├── activity_help.xml │ │ │ ├── activity_help_content.xml │ │ │ ├── activity_history.xml │ │ │ ├── activity_main.xml │ │ │ ├── activity_main_app_bar.xml │ │ │ ├── activity_main_content.xml │ │ │ ├── activity_report.xml │ │ │ ├── activity_report_app_bar.xml │ │ │ ├── activity_report_content.xml │ │ │ ├── activity_report_detail.xml │ │ │ ├── activity_report_detail_content.xml │ │ │ ├── activity_select_history_apps.xml │ │ │ ├── activity_settings.xml │ │ │ ├── activity_splash.xml │ │ │ ├── activity_tutorial.xml │ │ │ ├── app_list_group.xml │ │ │ ├── app_list_item.xml │ │ │ ├── app_report_detail_layout.xml │ │ │ ├── content_history.xml │ │ │ ├── content_select_history_apps.xml │ │ │ ├── fragment_charts.xml │ │ │ ├── fragment_list_item.xml │ │ │ ├── help_list_group.xml │ │ │ ├── help_list_item.xml │ │ │ ├── history_list_group.xml │ │ │ ├── history_list_item.xml │ │ │ ├── main_nav_header.xml │ │ │ ├── report_detail_item.xml │ │ │ ├── report_list_group.xml │ │ │ ├── report_list_group_header.xml │ │ │ ├── report_list_item.xml │ │ │ ├── toolbar.xml │ │ │ ├── tutorial_slide1.xml │ │ │ ├── tutorial_slide2.xml │ │ │ └── tutorial_slide3.xml │ │ ├── menu/ │ │ │ ├── applistseletion_menu.xml │ │ │ ├── main_drawer.xml │ │ │ └── toolbar_menu.xml │ │ ├── values/ │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ ├── values-de/ │ │ │ └── strings.xml │ │ ├── values-ja/ │ │ │ └── strings.xml │ │ └── xml/ │ │ ├── preferences.xml │ │ └── searchable.xml │ └── test/ │ └── java/ │ └── bjoernr/ │ └── ssllabs/ │ ├── ApiAssert.java │ └── ApiTest.java ├── build.gradle ├── fastlane/ │ └── metadata/ │ └── android/ │ ├── ar/ │ │ └── summary.txt │ ├── de/ │ │ ├── full_description.txt │ │ ├── short_description.txt │ │ └── title.txt │ ├── de-DE/ │ │ ├── full_description.txt │ │ ├── short_description.txt │ │ └── title.txt │ ├── en-US/ │ │ ├── full_description.txt │ │ ├── short_description.txt │ │ └── title.txt │ ├── eo/ │ │ └── summary.txt │ ├── es/ │ │ └── summary.txt │ ├── fr/ │ │ └── summary.txt │ ├── he/ │ │ └── summary.txt │ ├── it/ │ │ └── summary.txt │ ├── ja/ │ │ └── summary.txt │ ├── nb/ │ │ └── summary.txt │ ├── nn/ │ │ └── summary.txt │ ├── pl/ │ │ └── summary.txt │ ├── pt/ │ │ └── summary.txt │ ├── pt-BR/ │ │ └── summary.txt │ ├── pt-PT/ │ │ └── summary.txt │ ├── ro/ │ │ └── summary.txt │ ├── ru/ │ │ └── summary.txt │ ├── tr/ │ │ └── summary.txt │ ├── uk/ │ │ └── summary.txt │ ├── zh-CN/ │ │ └── summary.txt │ └── zh-TW/ │ └── summary.txt ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/changelog.yml ================================================ name: Changelog Generation on: release: types: [published] workflow_dispatch: jobs: changelog: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: submodules: 'recursive' ref: master - uses: rhysd/changelog-from-release/action@v3 with: file: CHANGELOG.md pull_request: true github_token: ${{ secrets.GITHUB_TOKEN }} commit_summary_template: 'update changelog for %s changes' args: -l 2 header: | # Changelog ================================================ FILE: .gitignore ================================================ # Built application files /*/build/ # Crashlytics configuations com_crashlytics_export_strings.xml # Local configuration file (sdk path, etc) local.properties # Gradle generated files .gradle/ #build files build/ # Idea configuations .idea/ # Signing files .signing/ # User-specific configurations .idea/libraries/ .idea/workspace.xml .idea/tasks.xml .idea/.name .idea/compiler.xml .idea/copyright/profiles_settings.xml .idea/encodings.xml .idea/misc.xml .idea/modules.xml .idea/scopes/scope_settings.xml .idea/vcs.xml *.iml # OS-specific files .DS_Store .DS_Store? ._* .Spotlight-V100 .Trashes ehthumbs.db Thumbs.db # Documents *.pdf *.doc *.docx *.odt #APK *.apk ================================================ FILE: CHANGELOG.md ================================================ # Changelog ## [Netmonitor (Privacy Friendly) v2.1](https://github.com/SecUSo/privacy-friendly-netmonitor/releases/tag/v2.1) - 24 Sep 2020 - small bugfixes - upgraded compile and target Android versions - updated dependencies and libraries - disabled for Android 10 and later - updated SECUSO references - fixed notification for newer Android versions [Changes][v2.1] ## [Privacy Friendly Netmonitor v2.0](https://github.com/SecUSo/privacy-friendly-netmonitor/releases/tag/v2.0) - 29 Mar 2018 * Improvement history function: Apps with the Internet permission can be chosen and monitored * Redesign [Changes][v2.0] ## [Privacy Friendly Netmonitor v1.2](https://github.com/SecUSo/privacy-friendly-netmonitor/releases/tag/v1.2) - 12 Oct 2017 - Bug fixing - Icon updates - Better handling of unknown apps [Changes][v1.2] ## [Privacy Friendly Net Monitor v1.1.4](https://github.com/SecUSo/privacy-friendly-netmonitor/releases/tag/v1.1.4) - 09 Mar 2017 Blocking of screenshots removed [Changes][v1.1.4] ## [Privacy Friendly Net Monitor v1.1.3](https://github.com/SecUSo/privacy-friendly-netmonitor/releases/tag/v1.1.3) - 04 Mar 2017 - Android 4 Support added - Icons refinements (list icons, splash icons, unloadable icons) - Help page refinement - Bug Fixes [Changes][v1.1.3] ## [Privacy Friendly Net Monitor v1.1.2](https://github.com/SecUSo/privacy-friendly-netmonitor/releases/tag/v1.1.2) - 28 Feb 2017 - MinSDK reset to 21 [Changes][v1.1.2] ## [Privacy Friendly Net Monitor v1.1.1](https://github.com/SecUSo/privacy-friendly-netmonitor/releases/tag/v1.1.1) - 21 Feb 2017 - Refinements of translations - Downgrade to SDK 23 is target [Changes][v1.1.1] ## [Privacy Friendly Net Monitor v1.1](https://github.com/SecUSo/privacy-friendly-netmonitor/releases/tag/v1.1) - 20 Feb 2017 Adding of SSL Rating [Changes][v1.1] ## [Privacy Friendly Net Monitor v1.0](https://github.com/SecUSo/privacy-friendly-netmonitor/releases/tag/v1.0) - 21 Jan 2017 Privacy Friendly Net Monitor is an Android application that can identify and monitor active network connections of applications that are installed on the mobile device. It monitors active network sockets and provides information about the scanned connections and apps. The invoking app is identified and listed with it's name, package and icon. The Connection's local and remote socket information (ip/port) is displayed along with a resolved hostname information and protocol evaluation based on well-known ports. Known un-/encrypted protocols are automatically marked. Privacy Friendly Net Monitor does not require a rooted device. Privacy Friendly Net Monitor is optimized regarding the user’s privacy. It doesn’t use any tracking mechanisms, neither it displays any advertisement. It belongs to the Privacy Friendly Apps group developed by the SECUSO research group at Technische Universität Darmstadt, Germany. [Changes][v1.0] [v2.1]: https://github.com/SecUSo/privacy-friendly-netmonitor/compare/v2.0...v2.1 [v2.0]: https://github.com/SecUSo/privacy-friendly-netmonitor/compare/v1.2...v2.0 [v1.2]: https://github.com/SecUSo/privacy-friendly-netmonitor/compare/v1.1.4...v1.2 [v1.1.4]: https://github.com/SecUSo/privacy-friendly-netmonitor/compare/v1.1.3...v1.1.4 [v1.1.3]: https://github.com/SecUSo/privacy-friendly-netmonitor/compare/v1.1.2...v1.1.3 [v1.1.2]: https://github.com/SecUSo/privacy-friendly-netmonitor/compare/v1.1.1...v1.1.2 [v1.1.1]: https://github.com/SecUSo/privacy-friendly-netmonitor/compare/v1.1...v1.1.1 [v1.1]: https://github.com/SecUSo/privacy-friendly-netmonitor/compare/v1.0...v1.1 [v1.0]: https://github.com/SecUSo/privacy-friendly-netmonitor/tree/v1.0 ================================================ FILE: CONTRIBUTING ================================================ # How to contribute We encourage open source developers to support the Privacy Friendly Apps. We also wish to keep it as easy as possible to contribute. There are a few guidelines that we need contributors to follow. For further questions we refer to the contact details on the [Privacy Friendly Apps website](https://secuso.org/pfa). ## Reporting of Issues * Make sure you have a [GitHub account](https://github.com/signup/free). * Open an issue in the corresponding app's repository, assuming one does not already exist. * Clearly describe the issue including steps to reproduce when it is a bug. In some cases screenshots can be supportive. * Make sure you mention the Android version and the device you have used when you encountered the issue. * Make your description as precise as possible. ## Making Changes * Make sure you have a [GitHub account](https://github.com/signup/free). * Find an issue that you wish to close. If the issue you wish to close is not present, open it. Make sure that the issue has one of the following labels which are set by our team: * Bug * Enhancement * Help wanted * No integration planned That means that we have already reviewed the issue. If you wish to add a translation, opening an issue is not required. * Fork the repository on GitHub. * Create a topic branch from where you want to base your work (usually master branch). * To quickly create a topic branch based on master, run `git checkout -b fix/master/my_contribution master`. * Please avoid working directly on the `master` branch. * Make commits of logical units in english language. * Make sure your commit messages are in the proper format. If the commit addresses an issue filed in the Github repository, start the first line of the commit with a hash followed by the issue number (e.g. #42). * Make sure you have added the necessary tests for your changes. * Run all available tests to assure nothing else was accidentally broken. ### Unwanted Changes The Privacy Friendly Apps are a group of Android apps that are optimized regarding the user's privacy. Therefore, Pull Requests that contain the following functionality will be rejected: * Analytics or advertisement frameworks * User tracking (e.g. sending of data to a third party) * Any that use of libraries that do not comply the license of the corresponding Privacy Friendly App (GPLv3 or Apache2). * Unnecessary use of Android permissions. If new functionality is added that requires the usage of an Android permission you should clearly explain the Pull Request why this permission is required. * New translations/languages ## Submitting Changes * Push your changes to a topic branch in your fork of the repository. * Submit a Pull Request to the repository of the corresponding Privacy Friendly App. * Indicate that you have read this policy by writing the second word of the section "unwanted changes" * Our team looks at Pull Requests on a regular basis and assigns a reviewer. * After feedback has been given we expect responses within one month. After one month we might close the pull request if no activity is shown. ================================================ FILE: LICENSE.txt ================================================ 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 . ================================================ FILE: README.md ================================================ [![Twitter](https://img.shields.io/badge/twitter-@SECUSOResearch-%231DA1F2.svg?&style=flat-square&logo=twitter&logoColor=1DA1F2)][Twitter] [![Mastodon](https://img.shields.io/badge/mastodon-@SECUSO__Research@baw%C3%BC.social-%233088D4.svg?&style=flat-square&logo=mastodon&logoColor=3088D4)][Mastodon] [Mastodon]: https://xn--baw-joa.social/@SECUSO_Research [Twitter]: https://twitter.com/SECUSOResearch Privacy Friendly Netmonitor Icon # Privacy Friendly Net Monitor # > :warning: :warning: :warning: **Please note:** This project is no longer officially maintained. In an attempt to focus our maintenance efforts, we have decided to stop the maintenance of some projects, including this one. This means that there will be no further feature updates or bugfixes planned for this app (exceptions only in cases of severe security or privacy issues). Consequently, the app has also been removed from the stores. If someone is interested in taking over the maintenance of this app, please do not hesitate to contact us: pfa@secuso.org This app monitors active network sockets and provides information on the scanned connections and apps. The invoking app is identified and listed with it's name, package and icon. The Connection's local and remote socket information (ip/port) is displayed along with a resolved hostname information and protocol evaluation based on well-known ports. Known un-/encrypted protocols are automatically marked. Additional features can be activated in the settings tab. This includes a panel for detailed technical information on connections, a logging functionality to keep scan results, a remote analysis of TLS-Servers via SSL-Labs API, a database connection to save selected reports in a history and charts to visualize the reports in different time intervals. This app is optimized regarding the user’s privacy. It doesn’t use any tracking mechanisms, neither it displays any advertisement. It belongs to the Privacy Friendly Apps group developed by the SECUSO research group at Karlsruhe Institute of Technology, Germany. ## Motivation ## This application has been developed to raise user awareness for the constant and unobserved communication behaviour of mobil device application. Additionally a coarse, technical analysis of the connections can help to identify unsecure, privacy-violating or malicious communicating behaviour of installed applications. ## Building ## ### API Reference ### Mininum SDK: 22 Target SDK: 26 ### Setup ### * Android Studio 3.0.1 ### Future Enhancements ### possible additional features - raw socket inspection - ip locating feature - export of identified information - display of additional remote host information (SSLLabs) - long term goal: addtitional active service, perfoming (deep) packet inspection with VPN-Capture implementation ### License ### Privacy Friendly Net Monitor is licensed under the GPLv3. Copyright (C) 2015 - 2018 Felix Tsala Schiller 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 http://www.gnu.org/licenses/. The icons used in the nagivation drawer are licensed under the CC BY 2.5. In addition to them the app uses icons from Google Design Material Icons licensed under Apache License Version 2.0. All other images (the logo of Privacy Friendly Apps, the SECUSO logo, the app logos and the spash screen icon) copyright [SECUSO](www.secuso.org) (2019). This application uses SSL Labs APIs v1.24.4 by Qualys SSL Labs (Terms of use: https://www.ssllabs.com/downloads/Qualys_SSL_Labs_Terms_of_Use.pdf) and Java SSL Labs API by Björn Roland GLicense: GPLv3, https://github.com/bjoernr-de/java-ssllabs-api) Privacy Friendly Net Monitor is a non-root variant of TLSMetric android app (https://bitbucket.org/schillef/tlsmetric/overview) by Felix Tsala Schiller. ### Contributors ### App Icon:
Markus Hau Developers:
Felix Tsala Schiller
Tobias Burger
Marco Egermaier Contributors (Github):
Yonjuni
Kamuno
di72nn
stevesoltys
FroggieFrog ================================================ FILE: app/.gitignore ================================================ /build ================================================ FILE: app/build.gradle ================================================ apply plugin: 'com.android.application' apply plugin: 'org.greenrobot.greendao' android { compileSdkVersion 29 defaultConfig { applicationId 'org.secuso.privacyfriendlynetmonitor' minSdkVersion 17 targetSdkVersion 29 versionCode 9 versionName "2.1" testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' vectorDrawables.useSupportLibrary = true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } productFlavors { } } android { lintOptions { disable 'MissingTranslation' } } //added by TB (needed for Studio 3.0.0) and for the charts allprojects { repositories { jcenter() google() maven { url "https://jitpack.io" } } } dependencies { implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3' implementation fileTree(include: ['*.jar'], dir: 'libs') androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', { exclude group: 'com.android.support', module: 'support-annotations' }) implementation 'androidx.appcompat:appcompat:1.0.0' implementation 'com.google.android.material:material:1.2.1' implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'org.greenrobot:greendao:3.3.0' implementation 'net.zetetic:android-database-sqlcipher:3.5.9' implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'androidx.appcompat:appcompat:1.0.0' implementation 'com.google.android.material:material:1.2.1' implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'androidx.cardview:cardview:1.0.0' implementation 'androidx.recyclerview:recyclerview:1.1.0' implementation 'com.github.PhilJay:MPAndroidChart:v3.0.0-beta1' testImplementation 'junit:junit:4.12' testImplementation 'org.json:json:20180813' } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in C:\Users\fs\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/de/bjoernr/ssllabs/Api.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package de.bjoernr.ssllabs; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * Java-SSLLabs-API *

* This Java library provides basic access to the SSL Labs API * and is build upon the official API documentation at * https://github.com/ssllabs/ssllabs-scan/blob/master/ssllabs-api-docs.md * * @author Björn Roland * @license GNU GENERAL PUBLIC LICENSE v3 */ public class Api { private static final String API_URL = "https://api.ssllabs.com/api/v2"; private static final String VERSION = "0.0.1-SNAPSHOT"; /** * Fetch API information * API Call: info * * @return JSONObject */ public JSONObject fetchApiInfo() { String jsonString; JSONObject json = new JSONObject(); try { jsonString = sendApiRequest("info", null); json = new JSONObject(jsonString); } catch (Exception ignored) { } return (json); } /** * Fetch host information * API Call: analyze * * @param host * @param publish * @param startNew * @param fromCache * @param maxAge * @param all * @param ignoreMismatch * @return JSONObject */ public JSONObject fetchHostInformation(String host, boolean publish, boolean startNew, boolean fromCache, String maxAge, String all, boolean ignoreMismatch) { String jsonString; JSONObject json = new JSONObject(); try { Map parameters = new HashMap(); parameters.put("host", host); parameters.put("publish", booleanToOnOffString(publish)); parameters.put("startNew", booleanToOnOffString(startNew)); parameters.put("fromCache", booleanToOnOffString(fromCache)); parameters.put("maxAge", maxAge); parameters.put("all", all); parameters.put("ignoreMismatch", booleanToOnOffString(ignoreMismatch)); jsonString = sendApiRequest("analyze", parameters); json = new JSONObject(jsonString); } catch (Exception ignored) { } return (json); } /** * Same as fetchHostInformation() but prefer caching * fetchHostInformation() with proper parameters can also be used * API Call: analyze * * @param host * @param maxAge * @param publish * @param ignoreMismatch * @return JSONObject */ public JSONObject fetchHostInformationCached(String host, String maxAge, boolean publish, boolean ignoreMismatch) { return (fetchHostInformation(host, publish, false, true, maxAge, "done", ignoreMismatch)); } /** * Fetch endpoint data * API Call: getEndpointData * * @param host * @param s * @param fromCache * @return JSONObject */ public JSONObject fetchEndpointData(String host, String s, boolean fromCache) { String jsonString; JSONObject json = new JSONObject(); try { Map parameters = new HashMap(); parameters.put("host", host); parameters.put("s", s); parameters.put("fromCache", booleanToOnOffString(fromCache)); jsonString = sendApiRequest("getEndpointData", parameters); json = new JSONObject(jsonString); } catch (Exception ignored) { } return (json); } /** * Fetch status codes * API Call: getStatusCodes * * @return JSONObject */ public JSONObject fetchStatusCodes() { String jsonString; JSONObject json = new JSONObject(); try { jsonString = sendApiRequest("getStatusCodes", null); json = new JSONObject(jsonString); } catch (Exception ignored) { } return (json); } /** * Send custom API request and return API response * * @param apiCall * @param parameters * @return String */ public String sendCustomApiRequest(String apiCall, Map parameters) { String jsonString = ""; try { jsonString = sendApiRequest(apiCall, parameters); } catch (Exception ignored) { } return (jsonString); } /** * Sends an api request and return api response * * @param apiCall * @param parameters * @return String * @throws IOException */ private String sendApiRequest(String apiCall, Map parameters) throws IOException { URL url = new URL(API_URL + "/" + apiCall); if (parameters != null) { url = new URL(url.toString() + buildGetParameterString(parameters)); } InputStream is = url.openStream(); int nextByteOfData = 0; StringBuffer apiResponseBuffer = new StringBuffer(); while ((nextByteOfData = is.read()) != -1) { apiResponseBuffer.append((char) nextByteOfData); } is.close(); return (apiResponseBuffer.toString()); } /** * Helper function to build GET parameter string * * @param parameters * @return String */ private String buildGetParameterString(Map parameters) { String getParameterString = ""; for (Map.Entry param : parameters.entrySet()) { if (param.getValue() == null) { continue; } getParameterString += (getParameterString.length() < 1) ? ("?") : ("&"); getParameterString += param.getKey() + "=" + param.getValue(); } return (getParameterString); } /** * Helper function to cast boolean to on/off string * * @param b * @return */ private String booleanToOnOffString(boolean b) { return (b == true) ? "on" : "off"; } /** * Getter for API_URL * * @return String */ public static String getApiUrl() { return API_URL; } /** * Getter for VERSION * * @return String */ public static String getVersion() { return VERSION; } } ================================================ FILE: app/src/main/java/de/bjoernr/ssllabs/Console.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package de.bjoernr.ssllabs; import org.json.JSONException; import org.json.JSONObject; import java.util.Map; /** * Command line interface class * * @author Björn Roland */ public class Console { public static void main(String[] args) { printHeader(); if (args.length == 1 && (args[0].equals("--info") || args[0].equals("-i"))) { handleInfo(); } else if ((args.length > 0 && args.length <= 6) && (args[0].equals("--host-information") || args[0].equals("-hi"))) { handleHostInformation(args); } else { printUsage(); } } public static void handleInfo() { Api ssllabsApi = new Api(); JSONObject apiInfo = ssllabsApi.fetchApiInfo(); Map map = null; try { map = ConsoleUtilities.jsonToMap(apiInfo); } catch (JSONException ignore) { } System.out.println("API information"); System.out.println(""); System.out.println(ConsoleUtilities.mapToConsoleOutput(map)); } public static void handleHostInformation(String[] args) { //API parameters String host = ConsoleUtilities.arrayValueMatchRegex(args, "-h=(.+)"); boolean publish = false; boolean startNew = false; boolean fromCache = false; String maxAge = null; String all = null; boolean ignoreMismatch = false; if (host == null) { //host not found in arguments printUsage(); return; } String[] possibleArguments = {"-p", "-c", "-m", "-a", "-i"}; for (String arg : possibleArguments) { if (ConsoleUtilities.arrayValueMatchRegex(args, arg) == null) { //if argument is not in args array, continue with next possible argument continue; } switch (arg) { case "-p": publish = true; break; case "-c": fromCache = true; break; case "-m": maxAge = ConsoleUtilities.arrayValueMatchRegex(args, "-m=(.+)"); break; case "-a": all = ConsoleUtilities.arrayValueMatchRegex(args, "-a=(.+)"); break; case "-i": ignoreMismatch = true; break; } } Api ssllabsApi = new Api(); JSONObject hostInformation = ssllabsApi.fetchHostInformation(host, publish, startNew, fromCache, maxAge, all, ignoreMismatch); Map map = null; try { map = ConsoleUtilities.jsonToMap(hostInformation); } catch (JSONException ignore) { } System.out.println("Host information"); System.out.println(""); System.out.println(ConsoleUtilities.mapToConsoleOutput(map)); } public static void printHeader() { System.out.println(""); System.out.println(" ___ _____ _____ _ _ _ ___ ______ _____ "); System.out.println(" |_ | / ___/ ___| | | | | | / _ \\ | ___ \\_ _|"); System.out.println(" | | __ ___ ____ _ \\ `--.\\ `--.| | | | __ _| |__ ___ / /_\\ \\| |_/ / | | "); System.out.println(" | |/ _` \\ \\ / / _` | `--. \\`--. \\ | | | / _` | '_ \\/ __| | _ || __/ | | "); System.out.println("/\\__/ / (_| |\\ V / (_| | /\\__/ /\\__/ / |____| |___| (_| | |_) \\__ \\ | | | || | _| |_ "); System.out.println("\\____/ \\__,_| \\_/ \\__,_| \\____/\\____/\\_____/\\_____/\\__,_|_.__/|___/ \\_| |_/\\_| \\___/ "); System.out.println("by Bjoern Roland "); System.out.println("and contributors (https://github.com/bjoernr-de/java-ssllabs-api/graphs/contributors)"); System.out.println("-------------------------------------------------"); System.out.println(""); } public static void printUsage() { String jarName = "java-ssllabs-api-" + Api.getVersion() + ".jar"; String jarExecution = "java -jar " + jarName; System.out.println("Help"); System.out.println(jarExecution); System.out.println(""); System.out.println("-i, --info"); System.out.println(" Fetch API information"); System.out.println(""); System.out.println("-hi, --host-information"); System.out.println(" Mandatory parameter:"); System.out.println(" -h, --host (String)"); System.out.println(""); System.out.println(" Additional parameter:"); System.out.println(" -p, --publish (boolean) - default value is false"); System.out.println(" -c, --fromCache (boolean) - default value is false"); System.out.println(" -m, --maxAge (String)"); System.out.println(" -a, --all (String)"); System.out.println(" -i, --ignoreMismatch (boolean) - default value is false"); System.out.println(""); System.out.println(" Example:"); System.out.println(" " + jarExecution + " -hi -h=https://ssllabs.com -p -c -m=\"1\""); } } ================================================ FILE: app/src/main/java/de/bjoernr/ssllabs/ConsoleUtilities.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package de.bjoernr.ssllabs; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConsoleUtilities { private static String newLine = "\n"; /* * Special thanks to Vikas Gupta (http://stackoverflow.com/users/2915208/vikas-gupta) * http://stackoverflow.com/questions/21720759/convert-a-json-string-to-a-hashmap * * START code of Vikas Gupta from stackoverflow */ public static Map jsonToMap(JSONObject json) throws JSONException { Map retMap = new HashMap(); if (json != JSONObject.NULL) { retMap = toMap(json); } return retMap; } public static Map toMap(JSONObject object) throws JSONException { Map map = new HashMap(); Iterator keysItr = object.keys(); while (keysItr.hasNext()) { String key = keysItr.next(); Object value = object.get(key); if (value instanceof JSONArray) { value = toList((JSONArray) value); } else if (value instanceof JSONObject) { value = toMap((JSONObject) value); } map.put(key, value); } return map; } public static List toList(JSONArray array) throws JSONException { List list = new ArrayList(); for (int i = 0; i < array.length(); i++) { Object value = array.get(i); if (value instanceof JSONArray) { value = toList((JSONArray) value); } else if (value instanceof JSONObject) { value = toMap((JSONObject) value); } list.add(value); } return list; } // END code of Vikas Gupta from stackoverflow public static String mapToConsoleOutput(Map map) { String consoleOutput = ""; for (Map.Entry entry : map.entrySet()) { consoleOutput += entry.getKey() + " = " + entry.getValue().toString(); consoleOutput += newLine; } return (consoleOutput); } public static String arrayValueMatchRegex(String[] array, String regex) { Pattern p = Pattern.compile(regex); for (int i = 0; i < array.length; i++) { Matcher m = p.matcher(array[i]); while (m.find()) { try { return (m.group(1)); } catch (Exception ignored) { //possible IndexOutOfBoundsException } } } return null; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/AboutActivity.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.os.Bundle; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.text.method.LinkMovementMethod; import android.view.View; import android.widget.TextView; import org.secuso.privacyfriendlynetmonitor.Assistant.RunStore; import org.secuso.privacyfriendlynetmonitor.BuildConfig; import org.secuso.privacyfriendlynetmonitor.R; /** * Activity displaying information about Privacy Friendly Net Monitor App */ public class AboutActivity extends AppCompatActivity { /** * * @param savedInstanceState */ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); RunStore.setContext(this); ActionBar ab = getSupportActionBar(); if (ab != null) { ab.setDisplayHomeAsUpEnabled(true); } View mainContent = findViewById(R.id.main_content); if (mainContent != null) { mainContent.setAlpha(0); mainContent.animate().alpha(1).setDuration(BaseActivity.MAIN_CONTENT_FADEIN_DURATION); } overridePendingTransition(0, 0); ((TextView) findViewById(R.id.javaAPIURL)).setMovementMethod(LinkMovementMethod.getInstance()); ((TextView) findViewById(R.id.APIURL)).setMovementMethod(LinkMovementMethod.getInstance()); ((TextView) findViewById(R.id.secusoWebsite)).setMovementMethod(LinkMovementMethod.getInstance()); ((TextView) findViewById(R.id.githubURL)).setMovementMethod(LinkMovementMethod.getInstance()); ((TextView) findViewById(R.id.textFieldVersionName)).setText(BuildConfig.VERSION_NAME); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/Adapter/AppListRecyclerAdapter.java ================================================ package org.secuso.privacyfriendlynetmonitor.Activities.Adapter; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.SwitchCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.Collector; import org.secuso.privacyfriendlynetmonitor.R; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.List; /** * Created by tobias on 09.03.18. */ public class AppListRecyclerAdapter extends RecyclerView.Adapter{ private List app_list_name; private Context context; private SharedPreferences selectedAppsPreferences; private SharedPreferences.Editor editor; public static class ViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case public TextView appGroupTitle; public TextView appInstallDate; public ImageView appIcon; public SwitchCompat appSwitch; public String appFullName; public ViewHolder(View view) { super(view); this.appGroupTitle = (TextView) view.findViewById(R.id.appGroupTitle); this.appInstallDate = (TextView) view.findViewById(R.id.appInstalledOn); this.appIcon = (ImageView) view.findViewById(R.id.appGroupIcon); this.appSwitch = (SwitchCompat) view.findViewById(R.id.switchAppOnOffHistory); this.appFullName = ""; } } public AppListRecyclerAdapter(List app_list_name, Context context) { this.app_list_name = app_list_name; this.context = context; selectedAppsPreferences = context.getSharedPreferences("SELECTEDAPPS", 0); editor = selectedAppsPreferences.edit(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.app_list_group, parent, false); return new ViewHolder(itemView); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { String appName = app_list_name.get(position); holder.appFullName = appName; if (Collector.getAppsToIncludeInScan().contains(holder.appFullName)) { holder.appSwitch.setChecked(true); } else { holder.appSwitch.setChecked(false); } PackageManager packageManager = context.getPackageManager(); try { holder.appGroupTitle.setText((String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(appName, PackageManager.GET_META_DATA))); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd. MMM yyyy, HH:mm"); Date date = new Date(packageManager.getPackageInfo(appName, 0).firstInstallTime); holder.appInstallDate.setText("Installed: " + simpleDateFormat.format(date)); holder.appIcon.setImageDrawable(packageManager.getApplicationIcon(appName)); } catch (PackageManager.NameNotFoundException e) { } holder.appSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) { String appName = holder.appFullName; if (bChecked) { if (!Collector.getAppsToIncludeInScan().contains(appName)) { Collector.addAppToIncludeInScan(appName); editor.putString(appName, appName); editor.commit(); holder.appSwitch.setChecked(true); } } else { if (Collector.getAppsToIncludeInScan().contains(appName)) { Collector.deleteAppFromIncludeInScan(appName); editor.remove(appName); editor.commit(); holder.appSwitch.setChecked(false); } } } }); } @Override public int getItemCount() { return app_list_name.size(); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/Adapter/ExpandableHistoryListAdapter.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities.Adapter; import android.content.Context; import android.content.pm.PackageManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ImageView; import android.widget.TextView; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.Collector; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntity; import org.secuso.privacyfriendlynetmonitor.R; import java.util.HashMap; import java.util.List; /** * Created by m4rc0 on 04.12.2017. * Adapter to display the Apps in the history */ public class ExpandableHistoryListAdapter extends BaseExpandableListAdapter { private Context context; private List uidList; private HashMap> reportListDetail; /** * * @param context * @param uidList * @param reportListDetail */ public ExpandableHistoryListAdapter(Context context, List uidList, HashMap> reportListDetail) { this.context = context; this.uidList = uidList; this.reportListDetail = reportListDetail; } /** * @param groupPosition * @param childPosititon * @return child */ @Override public Object getChild(int groupPosition, int childPosititon) { return this.reportListDetail.get(this.uidList.get(groupPosition)) .get(childPosititon); } /** * @param groupPosition * @param childPosition * @return child id */ @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } /** * @param groupPosition * @param childPosition * @param isLastChild * @param convertView * @param parent * @return chield view */ @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { ReportEntity reportEntity = ((ReportEntity) getChild(groupPosition, childPosition)); final String dnsHostName = reportEntity.getRemoteHost(); if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.history_list_item, null); } TextView txtListChild = (TextView) convertView.findViewById(R.id.history_item_1); txtListChild.setText(dnsHostName); TextView history_item_2_type = (TextView) convertView.findViewById(R.id.history_item_2_type); history_item_2_type.setText(R.string.expandable_history_list_adapter_time_stamp); TextView history_item_2_val = (TextView) convertView.findViewById(R.id.history_item_2_val); history_item_2_val.setText(reportEntity.getTimeStamp()); return convertView; } /** * @param groupPosition * @return children count */ @Override public int getChildrenCount(int groupPosition) { return this.reportListDetail.get(this.uidList.get(groupPosition)).size(); } /** * @param groupPosition * @return group */ @Override public Object getGroup(int groupPosition) { return this.reportListDetail.get(groupPosition); } /** * @return group count */ @Override public int getGroupCount() { return this.reportListDetail.size(); } /** * @param groupPosition * @return group Position as ID */ @Override public long getGroupId(int groupPosition) { return groupPosition; } /** * @param groupPosition * @param isExpanded * @param convertView * @param parent * @return group View */ @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.history_list_group, null); String appName = ""; PackageManager packageManager = context.getPackageManager(); try { appName = reportListDetail.get(uidList.get(groupPosition)).get(0).getAppName(); } catch (IndexOutOfBoundsException e) { if (Collector.getKnownUIDs().containsKey(uidList.get(groupPosition))) { appName = Collector.getKnownUIDs().get(uidList.get(groupPosition)); } else { appName = packageManager.getNameForUid((new Integer(uidList.get(groupPosition)))); } } TextView historyGroupTitle = (TextView) convertView.findViewById(R.id.historyGroupTitle); TextView historyGroupSubtitle = (TextView) convertView.findViewById(R.id.historyGroupSubtitle); try { // if(reportListDetail == null || reportListDetail.isEmpty() || reportListDetail.get(appName) == null || reportListDetail.get(appName).isEmpty()){ if(getChildrenCount(groupPosition) != 0){ historyGroupTitle.setText((String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(appName, PackageManager.GET_META_DATA))); } else { historyGroupTitle.setText((String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(appName, PackageManager.GET_META_DATA)) + " " + context.getString(R.string.history_no_data_collected)); } } catch (PackageManager.NameNotFoundException e) { historyGroupTitle.setText(appName); } historyGroupSubtitle.setText(appName); ImageView imgView = (ImageView) convertView.findViewById(R.id.historyGroupIcon); try { imgView.setImageDrawable(packageManager.getApplicationIcon(appName)); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return convertView; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/Adapter/ExpandableListAdapter.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities.Adapter; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; import org.secuso.privacyfriendlynetmonitor.R; import java.util.HashMap; import java.util.List; /** * Adapter displaying contents in the help activity * Class structure taken from tutorial at http://www.journaldev.com/9942/android-expandablelistview-example-tutorial * last access 27th October 2016 */ public class ExpandableListAdapter extends BaseExpandableListAdapter { private Context context; private List expandableListTitle; private HashMap> expandableListDetail; /** * * @param context * @param expandableListTitle * @param expandableListDetail */ public ExpandableListAdapter(Context context, List expandableListTitle, HashMap> expandableListDetail) { this.context = context; this.expandableListTitle = expandableListTitle; this.expandableListDetail = expandableListDetail; } /** * * @param listPosition * @param expandedListPosition * @return child */ @Override public Object getChild(int listPosition, int expandedListPosition) { return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)) .get(expandedListPosition); } /** * * @param listPosition * @param expandedListPosition * @return child id */ @Override public long getChildId(int listPosition, int expandedListPosition) { return expandedListPosition; } /** * * @param listPosition * @param expandedListPosition * @param isLastChild * @param convertView * @param parent * @return child view */ @Override public View getChildView(int listPosition, final int expandedListPosition, boolean isLastChild, View convertView, ViewGroup parent) { final String expandedListText = (String) getChild(listPosition, expandedListPosition); if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.help_list_item, null); } TextView expandedListTextView = (TextView) convertView .findViewById(R.id.expandedListItem); expandedListTextView.setText(expandedListText); return convertView; } /** * * @param listPosition * @return children count */ @Override public int getChildrenCount(int listPosition) { return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)) .size(); } /** * * @param listPosition * @return group */ @Override public Object getGroup(int listPosition) { return this.expandableListTitle.get(listPosition); } /** * group count * @return */ @Override public int getGroupCount() { return this.expandableListTitle.size(); } /** * * @param listPosition * @return group id */ @Override public long getGroupId(int listPosition) { return listPosition; } /** * * @param listPosition * @param isExpanded * @param convertView * @param parent * @return group view */ @Override public View getGroupView(int listPosition, boolean isExpanded, View convertView, ViewGroup parent) { String listTitle = (String) getGroup(listPosition); if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater) this.context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.help_list_group, null); } TextView listTitleTextView = (TextView) convertView .findViewById(R.id.listTitle); listTitleTextView.setTypeface(null, Typeface.BOLD); listTitleTextView.setText(listTitle); return convertView; } /** * * @return false */ @Override public boolean hasStableIds() { return false; } /** * * @param listPosition * @param expandedListPosition * @return true */ @Override public boolean isChildSelectable(int listPosition, int expandedListPosition) { return true; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/Adapter/ExpandableReportAdapter.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities.Adapter; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Typeface; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ImageView; import android.widget.TextView; import org.secuso.privacyfriendlynetmonitor.Assistant.Const; import org.secuso.privacyfriendlynetmonitor.Assistant.KnownPorts; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.Collector; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.Report; import org.secuso.privacyfriendlynetmonitor.R; import java.util.HashMap; import java.util.List; /** * Adapter displaying information in the ReportActivity */ public class ExpandableReportAdapter extends BaseExpandableListAdapter { private Context context; private List uidList; private HashMap> reportListDetail; /** * * @param context * @param expandableListTitle * @param expandableListDetail */ public ExpandableReportAdapter(Context context, List expandableListTitle, HashMap> expandableListDetail) { this.context = context; this.uidList = expandableListTitle; this.reportListDetail = expandableListDetail; } /** * * @param listPosition * @param expandedListPosition * @return child */ @Override public Object getChild(int listPosition, int expandedListPosition) { return this.reportListDetail.get(this.uidList.get(listPosition)) .get(expandedListPosition); } /** * * @param listPosition * @param expandedListPosition * @return child id */ @Override public long getChildId(int listPosition, int expandedListPosition) { return expandedListPosition; } /** * * @param listPosition * @param expandedListPosition * @param isLastChild * @param convertView * @param parent * @return child view */ @Override public View getChildView(int listPosition, final int expandedListPosition, boolean isLastChild, View convertView, ViewGroup parent) { //Build information from reports of one App (UID) Report r = (Report) getChild(listPosition, expandedListPosition); final String item1; final String item2_type; final String item2_value; //Set hostname if resolved by AsyncDNS class if (Collector.hasHostName(r.remoteAdd.getHostAddress())) { item1 = Collector.getDnsHostName(r.remoteAdd.getHostAddress()); } else { item1 = "" + r.remoteAdd.getHostAddress(); } //Set connection info or server rating if (Collector.isCertVal && KnownPorts.isTlsPort(r.remotePort) && Collector.hasHostName(r.remoteAdd.getHostAddress())) { if (item1.equals(Collector.getCertHost(item1))) { item2_type = "SSL Server Rating:"; item2_value = Collector.getMetric(item1); } else { item2_type = "SSL Server Rating:"; if (item1.equals(Collector.getCertHost(item1))) { item2_value = Collector.getMetric(item1); } else { item2_value = Collector.getMetric(item1) + " (" + Collector.getCertHost(item1) + ")"; } } } else { item2_type = "Connection Info:"; item2_value = KnownPorts.CompileConnectionInfo(r.remotePort, r.type); } if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.report_list_item, null); } //Fill textviews TextView textView = (TextView) convertView.findViewById(R.id.report_item_1); //final int height = textView.getHeight(); textView.setText(item1); textView = (TextView) convertView.findViewById(R.id.report_item_2_type); textView.setText(item2_type); textView = (TextView) convertView.findViewById(R.id.report_item_2_val); textView.setText(item2_value); //Set warning colour if settings are set SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); textView.setTextColor(context.getResources().getColor(getWarningColor(item2_value))); if (!mSharedPreferences.getBoolean(Const.IS_HIGHLIGHTED, true)) { textView.setTextColor((int) R.color.text_dark); } return convertView; } /** * Get the warning color of a connection. * @param value * @return warning color as int */ private int getWarningColor(String value) { if (value.contains(Const.STATUS_TLS) || value.substring(0, 1).equals("A")) { return (R.color.green); } else if (value.contains(Const.STATUS_INCONCLUSIVE) || value.substring(0, 1).equals("B") || value.substring(0, 1).equals("C")) { return (R.color.orange); } else if (value.contains(Const.STATUS_UNSECURE) || value.substring(0, 1).equals("T") || value.substring(0, 1).equals("F") || value.substring(0, 1).equals("D") || value.substring(0, 1).equals("E")) { return R.color.red; } else { return R.color.text_dark; } } /** * * @param listPosition * @return children count */ @Override public int getChildrenCount(int listPosition) { return this.reportListDetail.get(this.uidList.get(listPosition)) .size(); } /** * * @param listPosition * @return group */ @Override public Object getGroup(int listPosition) { return this.uidList.get(listPosition); } /** * * @return group count */ @Override public int getGroupCount() { return this.uidList.size(); } /** * * @param listPosition * @return group id */ @Override public long getGroupId(int listPosition) { return listPosition; } /** * * @param listPosition * @param isExpanded * @param convertView * @param parent * @return group view */ @Override public View getGroupView(int listPosition, boolean isExpanded, View convertView, ViewGroup parent) { int uid = (int) getGroup(listPosition); if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater) this.context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.report_list_group, null); } TextView textViewTitle = (TextView) convertView.findViewById(R.id.reportGroupTitle); textViewTitle.setTypeface(null, Typeface.BOLD); TextView textViewSubtitle = (TextView) convertView.findViewById(R.id.reportGroupSubtitle); ImageView imgView = (ImageView) convertView.findViewById(R.id.reportGroupIcon); //add system app tag if (uid <= 10000) { textViewTitle.setText(Collector.getLabel(uid) + " (" + reportListDetail.get(uid).size() + ")" + " [System]"); } else { textViewTitle.setText(Collector.getLabel(uid) + " (" + reportListDetail.get(uid).size() + ")"); } textViewSubtitle.setText(Collector.getPackage(uid)); imgView.setImageDrawable(Collector.getIcon(uid)); return convertView; } /** * * @return false */ @Override public boolean hasStableIds() { return false; } /** * * @param listPosition * @param expandedListPosition * @return true */ @Override public boolean isChildSelectable(int listPosition, int expandedListPosition) { return true; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/Adapter/FragmentDayListAdapter.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities.Adapter; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import org.secuso.privacyfriendlynetmonitor.Activities.HistoryDetailActivity; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntity; import org.secuso.privacyfriendlynetmonitor.R; import java.sql.Date; import java.util.ArrayList; import java.util.List; /** * Created by m4rc0 on 14.01.2018. * Adapter adds reports to day, week and month fragments. */ public class FragmentDayListAdapter extends RecyclerView.Adapter { List reportEntities; Context context; /** * * @param reportEntities * @param context */ public FragmentDayListAdapter(List reportEntities, Context context) { this.reportEntities = reportEntities; this.context = context; } /** * View Holder for items. */ public static class ViewHolder extends RecyclerView.ViewHolder { public RelativeLayout relativeLayout; public ViewHolder(RelativeLayout itemView) { super(itemView); relativeLayout = itemView; } } /** * * @param parent * @param viewType * @return ViewHolder */ @Override public FragmentDayListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { RelativeLayout relativeLayout = (RelativeLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_list_item, parent, false); ViewHolder vh = new ViewHolder(relativeLayout); return vh; } /** * * @param holder * @param position */ @Override public void onBindViewHolder(FragmentDayListAdapter.ViewHolder holder, int position) { final ReportEntity reportEntity = reportEntities.get(position); TextView textViewAppName = holder.relativeLayout.findViewById(R.id.fragment_appname); TextView textViewTimestamp = holder.relativeLayout.findViewById(R.id.fragment_timestamp_value); TextView textViewConnectionInfo = holder.relativeLayout.findViewById(R.id.fragment_conncection_info_value); textViewAppName.setText(reportEntity.getRemoteAddress()); textViewTimestamp.setText(reportEntity.getTimeStamp()); textViewConnectionInfo.setText(reportEntity.getConnectionInfo()); holder.relativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List detailsList = prepareData(reportEntity); Intent intent = new Intent(context, HistoryDetailActivity.class); intent.putExtra("Details", (ArrayList) detailsList); context.startActivity(intent); } }); } /** * * @return item count */ @Override public int getItemCount() { return reportEntities.size(); } /** * * @param reportEntity * @return list with prepared data */ private List prepareData(ReportEntity reportEntity) { PackageManager packageManager = context.getPackageManager(); String details = ""; List detailsList = new ArrayList(); String appName = reportEntity.getAppName(); detailsList.add(appName); String uid = reportEntity.getUserID(); detailsList.add(uid); PackageInfo packageInfo = null; try { packageInfo = packageManager.getPackageInfo(appName, 0); } catch (PackageManager.NameNotFoundException e) { System.out.println("Could not find package info for " + appName + "."); } details = packageInfo.versionName; detailsList.add(details); details = new Date(packageInfo.firstInstallTime).toString(); detailsList.add(details); details = reportEntity.getRemoteAddress(); detailsList.add(details); details = reportEntity.getRemoteHex(); detailsList.add(details); details = reportEntity.getRemoteHost(); detailsList.add(details); details = reportEntity.getLocalAddress(); detailsList.add(details); details = reportEntity.getLocalHex(); detailsList.add(details); details = reportEntity.getServicePort(); detailsList.add(details); details = reportEntity.getPayloadProtocol(); detailsList.add(details); details = reportEntity.getTransportProtocol(); detailsList.add(details); details = reportEntity.getLocalPort(); detailsList.add(details); details = reportEntity.getTimeStamp(); detailsList.add(details); details = reportEntity.getConnectionInfo(); detailsList.add(details); return detailsList; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/Adapter/PagerAdapter.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities.Adapter; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import org.secuso.privacyfriendlynetmonitor.fragment.Fragment_day; import org.secuso.privacyfriendlynetmonitor.fragment.Fragment_month; import org.secuso.privacyfriendlynetmonitor.fragment.Fragment_week; /** * Created by tobias on 04.01.18. * Adapter for fragment pager. */ public class PagerAdapter extends FragmentStatePagerAdapter { int mNumOfTabs; Bundle data; /** * * @param fm * @param NumOfTabs * @param appSubName */ public PagerAdapter(FragmentManager fm, int NumOfTabs, String appSubName) { super(fm); this.mNumOfTabs = NumOfTabs; data = new Bundle(); data.putString("AppName", appSubName); } /** * * @param position * @return item */ @Override public Fragment getItem(int position) { switch (position) { case 0: Fragment_day tab_day = new Fragment_day(); tab_day.setArguments(data); return tab_day; case 1: Fragment_week tab_week = new Fragment_week(); tab_week.setArguments(data); return tab_week; case 2: Fragment_month tab_month = new Fragment_month(); tab_month.setArguments(data); return tab_month; default: return null; } } /** * * @return number of tabs */ @Override public int getCount() { return mNumOfTabs; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/AppConnections_Chart.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.os.Bundle; import com.google.android.material.tabs.TabLayout; import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.AppCompatActivity; import org.secuso.privacyfriendlynetmonitor.Activities.Adapter.PagerAdapter; import org.secuso.privacyfriendlynetmonitor.R; /** * Created by tobias on 04.01.18. * App Connection chart class to visualize reports in different time intervals. */ public class AppConnections_Chart extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String appName = getIntent().getStringExtra(("AppName")); setTitle(appName); String appSubName = getIntent().getStringExtra(("AppSubName")); setContentView(R.layout.app_report_detail_layout); TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); tabLayout.addTab(tabLayout.newTab().setText(R.string.app_connections_chart_day)); tabLayout.addTab(tabLayout.newTab().setText(R.string.app_connections_chart_week)); tabLayout.addTab(tabLayout.newTab().setText(R.string.app_connections_chart_month)); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); final ViewPager viewPager = (ViewPager) findViewById(R.id.pager); final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), appSubName); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/BaseActivity.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import com.google.android.material.navigation.NavigationView; import com.google.android.material.navigation.NavigationView.OnNavigationItemSelectedListener; import androidx.core.app.TaskStackBuilder; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.MenuItem; import android.view.View; import org.secuso.privacyfriendlynetmonitor.R; /** * Base activity for other activities */ public class BaseActivity extends AppCompatActivity implements OnNavigationItemSelectedListener { // delay to launch nav drawer item, to allow close animation to play static final int NAVDRAWER_LAUNCH_DELAY = 250; // fade in and fade out durations for the main content when switching between // different Activities of the app through the Nav Drawer static final int MAIN_CONTENT_FADEOUT_DURATION = 150; static final int MAIN_CONTENT_FADEIN_DURATION = 250; // Navigation drawer: DrawerLayout mDrawerLayout; NavigationView mNavigationView; // Helper private Handler mHandler; protected SharedPreferences mSharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mHandler = new Handler(); //ActionBar ab = getSupportActionBar(); //if (ab != null) { // mActionBar = ab; // ab.setDisplayHomeAsUpEnabled(true); //} overridePendingTransition(0, 0); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } protected int getNavigationDrawerID() { return 0; } @Override public boolean onNavigationItemSelected(MenuItem item) { final int itemId = item.getItemId(); return goToNavigationItem(itemId); } protected boolean goToNavigationItem(final int itemId) { if (itemId == getNavigationDrawerID()) { // just close drawer because we are already in this activity mDrawerLayout.closeDrawer(GravityCompat.START); return true; } // delay transition so the drawer can close mHandler.postDelayed(new Runnable() { @Override public void run() { callDrawerItem(itemId); } }, NAVDRAWER_LAUNCH_DELAY); mDrawerLayout.closeDrawer(GravityCompat.START); selectNavigationItem(itemId); // fade out the active activity View mainContent = findViewById(R.id.main_content); if (mainContent != null) { mainContent.animate().alpha(0).setDuration(MAIN_CONTENT_FADEOUT_DURATION); } return true; } // set active navigation item void selectNavigationItem(int itemId) { for (int i = 0; i < mNavigationView.getMenu().size(); i++) { boolean b = itemId == mNavigationView.getMenu().getItem(i).getItemId(); mNavigationView.getMenu().getItem(i).setChecked(b); } } /** * Enables back navigation for activities that are launched from the NavBar. See * {@code AndroidManifest.xml} to find out the parent activity names for each activity. * * @param intent */ private void createBackStack(Intent intent) { TaskStackBuilder builder = TaskStackBuilder.create(this); builder.addNextIntentWithParentStack(intent); builder.startActivities(); } private void callDrawerItem(final int itemId) { Intent intent; switch (itemId) { case R.id.nav_main: intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); break; case R.id.nav_history: intent = new Intent(this, HistoryActivity.class); createBackStack(intent); break; case R.id.nav_about: intent = new Intent(this, AboutActivity.class); createBackStack(intent); break; case R.id.nav_help: intent = new Intent(this, HelpActivity.class); createBackStack(intent); break; case R.id.nav_settings: intent = new Intent(this, SettingsActivity.class); intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, SettingsActivity.GeneralPreferenceFragment.class.getName()); intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true); createBackStack(intent); break; case R.id.nav_tutorial: TutorialActivity.setTutorial_click(true); intent = new Intent(this, TutorialActivity.class); createBackStack(intent); break; default: } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setToolbar(); } public void setToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (getSupportActionBar() == null) { setSupportActionBar(toolbar); } mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); mDrawerLayout.addDrawerListener(toggle); toggle.syncState(); mNavigationView = (NavigationView) findViewById(R.id.nav_view); mNavigationView.setNavigationItemSelectedListener(this); selectNavigationItem(getNavigationDrawerID()); View mainContent = findViewById(R.id.main_content); if (mainContent != null) { mainContent.setAlpha(0); mainContent.animate().alpha(1).setDuration(MAIN_CONTENT_FADEIN_DURATION); } } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/HelpActivity.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.os.Bundle; import android.widget.ExpandableListView; import org.secuso.privacyfriendlynetmonitor.Activities.Adapter.ExpandableListAdapter; import org.secuso.privacyfriendlynetmonitor.Assistant.RunStore; import org.secuso.privacyfriendlynetmonitor.R; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Activity for help contents * Class structure taken from tutorial at http://www.journaldev.com/9942/android-expandablelistview-example-tutorial */ public class HelpActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help); RunStore.setContext(this); ExpandableListAdapter expandableListAdapter; HelpDataDump helpDataDump = new HelpDataDump(this); ExpandableListView generalExpandableListView = (ExpandableListView) findViewById(R.id.generalExpandableListView); HashMap> expandableListDetail = helpDataDump.getDataGeneral(); List expandableListTitleGeneral = new ArrayList<>(expandableListDetail.keySet()); expandableListAdapter = new ExpandableListAdapter(this, expandableListTitleGeneral, expandableListDetail); generalExpandableListView.setAdapter(expandableListAdapter); overridePendingTransition(0, 0); } protected int getNavigationDrawerID() { return R.id.nav_help; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/HelpDataDump.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.content.Context; import org.secuso.privacyfriendlynetmonitor.R; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; /** * Activity for displaying help content. *

* Class structure taken from tutorial at http://www.journaldev.com/9942/android-expandablelistview-example-tutorial * last access 27th October 2016 */ class HelpDataDump { private Context context; HelpDataDump(Context context) { this.context = context; } HashMap> getDataGeneral() { HashMap> expandableListDetail = new LinkedHashMap<>(); List general = new ArrayList<>(); general.add(context.getResources().getString(R.string.help_whatis_answer)); expandableListDetail.put(context.getResources().getString(R.string.help_whatis), general); List features1 = new ArrayList<>(); features1.add(context.getResources().getString(R.string.help_feature_one_answer)); expandableListDetail.put(context.getResources().getString(R.string.help_feature_one), features1); List features2 = new ArrayList<>(); features2.add(context.getResources().getString(R.string.help_feature_two_answer)); expandableListDetail.put(context.getResources().getString(R.string.help_feature_two), features2); List features3 = new ArrayList<>(); features3.add(context.getResources().getString(R.string.help_feature_three_answer)); expandableListDetail.put(context.getResources().getString(R.string.help_feature_three), features3); List features4 = new ArrayList<>(); features4.add(context.getResources().getString(R.string.help_feature_four_answer)); expandableListDetail.put(context.getResources().getString(R.string.help_feature_four), features4); List features5 = new ArrayList<>(); features5.add(context.getResources().getString(R.string.help_feature_five_answer)); expandableListDetail.put(context.getResources().getString(R.string.help_feature_five), features5); List privacy = new ArrayList<>(); privacy.add(context.getResources().getString(R.string.help_privacy_answer)); expandableListDetail.put(context.getResources().getString(R.string.help_privacy), privacy); List permissions = new ArrayList<>(); permissions.add(context.getResources().getString(R.string.help_permission_answer)); expandableListDetail.put(context.getResources().getString(R.string.help_permission), permissions); List sysuser = new ArrayList<>(); sysuser.add(context.getResources().getString(R.string.help_sysuser_answer)); expandableListDetail.put(context.getResources().getString(R.string.help_sysuser), sysuser); List un_encrypted_ports = new ArrayList<>(); un_encrypted_ports.add(context.getResources().getString(R.string.help_un_encrypted_ports_answer)); expandableListDetail.put(context.getResources().getString(R.string.help_un_encrypted_ports), un_encrypted_ports); return expandableListDetail; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/HistoryActivity.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.appcompat.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ExpandableListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import org.secuso.privacyfriendlynetmonitor.Activities.Adapter.ExpandableHistoryListAdapter; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.Collector; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DBApp; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DaoSession; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntity; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntityDao; import org.secuso.privacyfriendlynetmonitor.R; import java.sql.Date; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; /** * Acitivity for handling the history. All the selected Apps are tracked and shown as a history */ public class HistoryActivity extends BaseActivity { private ExpandableListView expListView; private ExpandableHistoryListAdapter historyReportAdapter; private ReportEntityDao reportEntityDao; private HashMap> historyReportMap; private List keys; private SharedPreferences selectedAppsPreferences; private SharedPreferences.Editor editor; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); progressBar = findViewById(R.id.selectHistoryProgressBar); progressBar.setVisibility(View.GONE); // load DB DaoSession daoSession = ((DBApp) getApplication()).getDaoSession(); reportEntityDao = daoSession.getReportEntityDao(); selectedAppsPreferences = getSharedPreferences("SELECTEDAPPS", 0); editor = selectedAppsPreferences.edit(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { progressBar.setVisibility(View.VISIBLE); startActivity(new Intent(HistoryActivity.this, SelectHistoryAppsActivity.class)); } }); // delete DB Button deleteDB = (Button) findViewById(R.id.deleteDB); deleteDB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deleteConfirmation(); } }); activateHistoryView(); } @Override public void onPostResume() { super.onPostResume(); progressBar.setVisibility(View.GONE); } private void activateHistoryView() { expListView = (ExpandableListView) findViewById(R.id.list_history); final HashMap> historyReports = provideHistoryReports(); TextView textView = (TextView) findViewById(R.id.noData); if (historyReports.isEmpty()) { if (textView.getVisibility() == View.INVISIBLE) { textView.setVisibility(View.VISIBLE); } } else { if (textView.getVisibility() == View.VISIBLE) { textView.setVisibility(View.INVISIBLE); } } historyReportAdapter = new ExpandableHistoryListAdapter(this, new ArrayList<>(historyReports.keySet()), historyReports); expListView.setAdapter(historyReportAdapter); expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { ReportEntity reportEntity = historyReports.get(keys.get(groupPosition)).get(childPosition); List detailsList = prepareData(reportEntity); Intent intent = new Intent(getBaseContext(), HistoryDetailActivity.class); intent.putExtra("Details", (ArrayList) detailsList); startActivity(intent); return false; } }); expListView.setOnItemLongClickListener(new ExpandableListView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { TextView tx1 = (TextView) view.findViewById(R.id.historyGroupTitle); String appName = tx1.getText().toString(); TextView tx2 = (TextView) view.findViewById(R.id.historyGroupSubtitle); String appSubName = tx2.getText().toString(); Intent myIntent = new Intent(HistoryActivity.this, AppConnections_Chart.class); myIntent.putExtra("AppName", appName); myIntent.putExtra("AppSubName", appSubName); startActivity(myIntent); return false; } }); } /** * Get details from db entities an save in List * * @param reportEntity * @return details list */ private List prepareData(ReportEntity reportEntity) { PackageManager packageManager = getPackageManager(); String details = ""; List detailsList = new ArrayList(); String appName = reportEntity.getAppName(); detailsList.add(appName); String uid = reportEntity.getUserID(); detailsList.add(uid); PackageInfo packageInfo = null; try { packageInfo = packageManager.getPackageInfo(appName, 0); } catch (PackageManager.NameNotFoundException e) { System.out.println("Could not find package info for " + appName + "."); } details = packageInfo.versionName; detailsList.add(details); details = new Date(packageInfo.firstInstallTime).toString(); detailsList.add(details); details = reportEntity.getRemoteAddress(); detailsList.add(details); details = reportEntity.getRemoteHex(); detailsList.add(details); details = reportEntity.getRemoteHost(); detailsList.add(details); details = reportEntity.getLocalAddress(); detailsList.add(details); details = reportEntity.getLocalHex(); detailsList.add(details); details = reportEntity.getServicePort(); detailsList.add(details); details = reportEntity.getPayloadProtocol(); detailsList.add(details); details = reportEntity.getTransportProtocol(); detailsList.add(details); details = reportEntity.getLocalPort(); detailsList.add(details); details = reportEntity.getTimeStamp(); detailsList.add(details); details = reportEntity.getConnectionInfo(); detailsList.add(details); return detailsList; } /** * @return HashMap with saved Reports */ private HashMap> provideHistoryReports() { historyReportMap = new HashMap>(); List appendedApps = new ArrayList(); List userIDs = new ArrayList(); List allReportEntities = reportEntityDao.loadAll(); for (ReportEntity reportEntity : allReportEntities) { String userID = reportEntity.getUserID(); if (!userIDs.contains(userID)) { userIDs.add(userID); List tempReportList = new ArrayList(); tempReportList.add(reportEntity); if (!appendedApps.contains(reportEntity.getAppName())) { appendedApps.add(reportEntity.getAppName()); } historyReportMap.put(userID, tempReportList); } else { historyReportMap.get(userID).add(reportEntity); } } List appsToInclude = Collector.getAppsToIncludeInScan(); if (!appsToInclude.isEmpty()) { appsToInclude = new ArrayList(new LinkedHashSet(appsToInclude)); appsToInclude.removeAll(appendedApps); if (!appsToInclude.isEmpty()) { for (String appName : appsToInclude) { try { int uid = getPackageManager().getApplicationInfo(appName, 0).uid; if (!Collector.getKnownUIDs().containsKey(uid)) { Collector.addKnownUIDs((new String()).valueOf(uid), appName); } historyReportMap.put((new String()).valueOf(uid), new ArrayList()); } catch (PackageManager.NameNotFoundException e) { } } appsToInclude.clear(); } } keys = new ArrayList<>(historyReportMap.keySet()); for (String key : keys) { Collections.reverse(historyReportMap.get(key)); } return historyReportMap; } @Override public void onResume() { super.onResume(); activateHistoryView(); } protected int getNavigationDrawerID() { return R.id.nav_history; } /** * show confirmation after deletion. */ private void deleteConfirmation() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialogTitle); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { reportEntityDao.deleteAll(); activateHistoryView(); Toast.makeText(getApplicationContext(), "All reports have been deleted.", Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(), "Deletion canceled.", Toast.LENGTH_SHORT).show(); } }); System.out.println("Building complete"); AlertDialog dialog = builder.create(); dialog.show(); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/HistoryDetailActivity.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import androidx.drawerlayout.widget.DrawerLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import org.secuso.privacyfriendlynetmonitor.Assistant.RunStore; import org.secuso.privacyfriendlynetmonitor.R; import java.util.ArrayList; import java.util.List; /** * Created by m4rc0 on 06.12.2017. * This actitivty shows the details of on history report. */ public class HistoryDetailActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_report_detail); RunStore.setContext(this); //Get saved data from report entity List details = getIntent().getStringArrayListExtra("Details"); List detailList = prepareData(details); final HistoryDetailActivity.DetailAdapter adapter = new HistoryDetailActivity.DetailAdapter(this, R.layout.report_detail_item, detailList); final ListView listview = (ListView) findViewById(R.id.report_detail_list_view); listview.setAdapter(adapter); View view_header = getLayoutInflater().inflate(R.layout.report_list_group_header, null); PackageManager packageManager = this.getPackageManager(); String appName = details.get(0); ImageView imgView = (ImageView) view_header.findViewById(R.id.reportGroupIcon_header); TextView textView1 = (TextView) view_header.findViewById(R.id.reportGroupTitle_header); TextView textView2 = (TextView) view_header.findViewById(R.id.reportGroupSubtitle_header); try { imgView.setImageDrawable(packageManager.getApplicationIcon(appName)); textView1.setText((String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(appName, PackageManager.GET_META_DATA))); } catch (PackageManager.NameNotFoundException e) { } textView2.setText(appName); listview.addHeaderView(view_header); } /** * @param unpreparedDetails * @return prepared data as list. */ public List prepareData(List unpreparedDetails) { List detailsList = new ArrayList(); String[] details = new String[2]; details[0] = (getString(R.string.history_detail_activity_uid)); details[1] = unpreparedDetails.get(1); detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_app_version)); details[1] = unpreparedDetails.get(2); detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_installed_on)); details[1] = unpreparedDetails.get(3); detailsList.add(details); details = new String[2]; details[0] = ""; details[1] = ""; detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_remote_address)); details[1] = unpreparedDetails.get(4); detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_remote_hex)); details[1] = unpreparedDetails.get(5); detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_remote_host)); details[1] = unpreparedDetails.get(6); detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_local_address)); details[1] = unpreparedDetails.get(7); detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_local_hex)); details[1] = unpreparedDetails.get(8); detailsList.add(details); details = new String[2]; details[0] = ""; details[1] = ""; detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_service_port)); details[1] = unpreparedDetails.get(9); detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_payload_protocol)); details[1] = unpreparedDetails.get(10); detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_transport_protocol)); details[1] = unpreparedDetails.get(11); detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_local_port)); details[1] = unpreparedDetails.get(12); detailsList.add(details); details = new String[2]; details[0] = ""; details[1] = ""; detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_timestamp)); details[1] = unpreparedDetails.get(13); detailsList.add(details); details = new String[2]; details[0] = (getString(R.string.history_detail_activity_connection_info)); details[1] = unpreparedDetails.get(14); detailsList.add(details); return detailsList; } /** * Detail Adapter sets relevant information. */ public class DetailAdapter extends ArrayAdapter { DetailAdapter(Context context, int resource, List detailList) { super(context, resource, detailList); } @Override public View getView(int position, View convertView, ViewGroup parent) { mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.report_detail_item, null); } //Get string array and set it to text fields String[] detail = getItem(position); TextView type = (TextView) v.findViewById(R.id.report_detail_item_type); TextView value = (TextView) v.findViewById(R.id.report_detail_item_value); if (detail[0] != null && detail[1] != null) { type.setText(detail[0]); value.setText(detail[1]); } else { type.setText(""); value.setText(""); } return v; } } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/MainActivity.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import org.secuso.privacyfriendlynetmonitor.Activities.Adapter.ExpandableReportAdapter; import org.secuso.privacyfriendlynetmonitor.Assistant.Const; import org.secuso.privacyfriendlynetmonitor.Assistant.RunStore; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.Collector; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.PassiveService; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.Report; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DBApp; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DaoSession; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntityDao; import org.secuso.privacyfriendlynetmonitor.R; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Activity providing main service controls and reports inspection */ public class MainActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener { private SwipeRefreshLayout swipeRefreshLayout; private ExpandableListView expListView; private HashMap> reportMap; private static ReportEntityDao reportEntityDao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); RunStore.setContext(this); RunStore.setAppContext(getApplicationContext()); //Save context state DaoSession daoSession = ((DBApp) getApplication()).getDaoSession(); reportEntityDao = daoSession.getReportEntityDao(); // Uncomment to generate Dummy Database Entries // GenerateReportEntities.generateReportEntities(this, reportEntityDao); // Load apps to include in scan SharedPreferences selectedAppsPreferences = getSharedPreferences("SELECTEDAPPS", 0); Map selectedAppsMap = (Map) selectedAppsPreferences.getAll(); Collection selectedAppsList = selectedAppsMap.values(); for (String appName : selectedAppsList) { if (!Collector.getAppsToIncludeInScan().contains(appName)) { Collector.addAppToIncludeInScan(appName); } } Collector.addAppToExcludeFromScan("app.android.unknown"); Collector.addAppToExcludeFromScan("app.unknown"); Collector.addAppToExcludeFromScan("unknown"); //This is an App that is used as an example for the History. In the first start only this is //APP is shown in the list, then selection are possible if (!RunStore.getServiceHandler().isServiceRunning(PassiveService.class)) { activateMainView(); } else { activateReportView(); } overridePendingTransition(0, 0); } // On start button press activate second view (report) private void setButtonListener() { final FloatingActionButton startStop = findViewById(R.id.mainFAB); startStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ProgressBar progressBar = findViewById(R.id.mainProgressBar); progressBar.setVisibility(View.VISIBLE); startStopTrigger(); } }); } //Trigger switches between activity, based service running indicator private void startStopTrigger() { if (!RunStore.getServiceHandler().isServiceRunning(PassiveService.class)) { if (Const.IS_DEBUG) Log.d(Const.LOG_TAG, getResources().getString(R.string.passive_service_start)); RunStore.getServiceHandler().startPassiveService(); Intent intent = new Intent(RunStore.getContext(), MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else { if (Const.IS_DEBUG) Log.d(Const.LOG_TAG, getResources().getString(R.string.passive_service_stop)); RunStore.getServiceHandler().stopPassiveService(); Intent intent = new Intent(RunStore.getContext(), MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } } //Activate the main layout private void activateMainView() { setContentView(R.layout.activity_main); super.setToolbar(); final FloatingActionButton startStop = findViewById(R.id.mainFAB); TextView textView = (TextView) findViewById(R.id.main_text_startstop); textView.setText(R.string.main_text_stopped); setButtonListener(); getNavigationDrawerID(); } //activate the report layout private void activateReportView() { setContentView(R.layout.activity_report); super.setToolbar(); getNavigationDrawerID(); //Initiate ListView functionality swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout); reportMap = Collector.provideSimpleReports(reportEntityDao); expListView = (ExpandableListView) findViewById(R.id.list); final ExpandableReportAdapter reportAdapter = new ExpandableReportAdapter(this, new ArrayList<>(reportMap.keySet()), reportMap); expListView.setAdapter(reportAdapter); swipeRefreshLayout.setOnRefreshListener(this); //Showing Swipe Refresh animation on activity create swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(true); refreshAdapter(); } } ); expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView expandableListView, View view, final int i, final int i1, final long l) { expListView = (ExpandableListView) findViewById(R.id.list); ExpandableReportAdapter adapter = (ExpandableReportAdapter) expListView.getExpandableListAdapter(); final Report r = (Report) adapter.getChild(i, i1); if (mSharedPreferences.getBoolean(Const.IS_DETAIL_MODE, false)) { view.animate().setDuration(500).alpha((float) 0.5) .withEndAction(new Runnable() { @Override public void run() { Collector.provideDetail(r.uid, r.remoteAddHex); Intent intent = new Intent(getApplicationContext(), ReportDetailActivity.class); startActivity(intent); } }); return true; // if no detail mode and server analysis is complete, goto SSL Labs } else if (mSharedPreferences.getBoolean(Const.IS_CERTVAL, false) && Collector.hasHostName(r.remoteAdd.getHostAddress()) && Collector.hasGrade(Collector.getDnsHostName(r.remoteAdd.getHostAddress()))) { String url = Const.SSLLABS_URL + Collector.getCertHost(Collector.getDnsHostName(r.remoteAdd.getHostAddress())); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent); return false; } else { try{ view.animate().setDuration(500).alpha((float) 0.5) .withEndAction(new Runnable() { @Override public void run() { Collector.provideDetail(r.uid, r.remoteAddHex); Intent intent = new Intent(getApplicationContext(), ReportDetailActivity.class); startActivity(intent); } }); } catch (Exception e){ return false; } return false; } } }); FloatingActionButton fab = findViewById(R.id.reportFAB); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Collector.saveReports(reportEntityDao); startStopTrigger(); } }); } @Override protected int getNavigationDrawerID() { return R.id.nav_main; } @Override public void onDestroy() { super.onDestroy(); } //refresh the adapter-list public void refreshAdapter() { swipeRefreshLayout.setRefreshing(true); reportMap = Collector.provideSimpleReports(reportEntityDao); final ExpandableReportAdapter reportAdapter = new ExpandableReportAdapter(this, new ArrayList<>(reportMap.keySet()), reportMap); expListView.setAdapter(reportAdapter); //Set swipe text and icon visible, if connections are empty setSwipeInfo((reportAdapter.getGroupCount() > 0)); swipeRefreshLayout.setRefreshing(false); } //Set information to refresh view, when adapter is empty (no connections scanned yet) private void setSwipeInfo(boolean b) { final ImageView icon = (ImageView) findViewById(R.id.report_empty_icon); final TextView text = (TextView) findViewById(R.id.report_empty_text); if (b) { icon.setVisibility(View.GONE); text.setVisibility(View.GONE); } else { icon.setVisibility(View.VISIBLE); text.setVisibility(View.VISIBLE); } } //Refresh the adapter when swipe triggers @Override public void onRefresh() { refreshAdapter(); } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } //listener of the toolbar buttons @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_refresh: refreshAdapter(); break; default: break; } return super.onOptionsItemSelected(item); } //refresh menu on layout change public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); if (RunStore.getServiceHandler().isServiceRunning(PassiveService.class)) { getMenuInflater().inflate(R.menu.toolbar_menu, menu); } return super.onPrepareOptionsMenu(menu); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/ReportDetailActivity.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import androidx.drawerlayout.widget.DrawerLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import org.secuso.privacyfriendlynetmonitor.Assistant.Const; import org.secuso.privacyfriendlynetmonitor.Assistant.RunStore; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.Collector; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.Report; import org.secuso.privacyfriendlynetmonitor.R; import java.util.ArrayList; import java.util.List; /** * Report Detail Panel. List all reports of a connection, invoked by Report Panel (ReportActivity) */ public class ReportDetailActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_report_detail); RunStore.setContext(this); //Get reports from collector class ArrayList detailList = Collector.sDetailReportList; final DetailAdapter adapter = new DetailAdapter(this, R.layout.report_detail_item, detailList); final ListView listview = (ListView) findViewById(R.id.report_detail_list_view); listview.setAdapter(adapter); View view_header = getLayoutInflater().inflate(R.layout.report_list_group_header, null); listview.addHeaderView(view_header); //Ende Löschen final Report report = Collector.sDetailReport; ImageView icon_header = (ImageView) view_header.findViewById(R.id.reportGroupIcon_header); icon_header.setImageDrawable(Collector.getIcon(report.uid)); TextView label_header = (TextView) view_header.findViewById(R.id.reportGroupTitle_header); label_header.setText(Collector.getLabel(report.uid)); TextView pkg_header = (TextView) view_header.findViewById(R.id.reportGroupSubtitle_header); pkg_header.setText(Collector.getPackage(report.uid)); //Add certificate information - open link to ssl labs if (mSharedPreferences.getBoolean(Const.IS_CERTVAL, false) && Collector.hasHostName(report.remoteAdd.getHostAddress()) && Collector.hasGrade(Collector.getDnsHostName(report.remoteAdd.getHostAddress()))) { TextView ssllabs = (TextView) findViewById(R.id.report_detail_ssllabs_result); ssllabs.setVisibility(View.VISIBLE); ssllabs.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = Const.SSLLABS_URL + Collector.getCertHost(Collector.getDnsHostName(report.remoteAdd.getHostAddress())); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent); } }); } } @Override public void onDestroy() { super.onDestroy(); } //Implementation of List Adapter class DetailAdapter extends ArrayAdapter { DetailAdapter(Context context, int resource, List detailList) { super(context, resource, detailList); } //Get detail information from collector class and write to adapter views @Override public View getView(int position, View convertView, ViewGroup parent) { mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.report_detail_item, null); } //Get string array and set it to text fields String[] detail = getItem(position); TextView type = (TextView) v.findViewById(R.id.report_detail_item_type); TextView value = (TextView) v.findViewById(R.id.report_detail_item_value); if (detail[0] != null && detail[1] != null) { type.setText(detail[0]); value.setText(detail[1]); } else { type.setText(""); value.setText(""); } return v; } } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/SelectHistoryAppsActivity.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import androidx.core.view.MenuItemCompat; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.SearchView; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import org.secuso.privacyfriendlynetmonitor.Activities.Adapter.AppListRecyclerAdapter; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DBApp; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DaoSession; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntityDao; import org.secuso.privacyfriendlynetmonitor.R; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import static org.secuso.privacyfriendlynetmonitor.Assistant.RunStore.getContext; /** * Activity for the list of all installed apps with internet permission. * The list can be sorted alphabeic and after installed date. * A search function for the list is implemented. */ public class SelectHistoryAppsActivity extends AppCompatActivity { private List app_list_name; private ReportEntityDao reportEntityDao; private SharedPreferences selectedAppsPreferences; private SharedPreferences.Editor editor; private RecyclerView appListRecyclerView; private RecyclerView.Adapter appListRecyclerAdapter; private RecyclerView.LayoutManager recyclerLayoutManager; //Variables to sort alphabetic and accodring to installed date //the displayed app names are in the keys of the map, the value is the long Name private Map sortMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_history_apps); // load DB DaoSession daoSession = ((DBApp) getApplication()).getDaoSession(); reportEntityDao = daoSession.getReportEntityDao(); ActionBar ab = getSupportActionBar(); if (ab != null) { ab.setDisplayShowHomeEnabled(true); } selectedAppsPreferences = getSharedPreferences("SELECTEDAPPS", 0); editor = selectedAppsPreferences.edit(); show_APP_list(); } //method to load all the Apps in the listeview, sorted alphabetic form the start private void show_APP_list() { app_list_name = provideAppList(); appListRecyclerView = (RecyclerView) findViewById(R.id.list_selection_app_recycler); recyclerLayoutManager = new LinearLayoutManager(this); appListRecyclerView.setLayoutManager(recyclerLayoutManager); // specify an adapter appListRecyclerAdapter = new AppListRecyclerAdapter(app_list_name, this); appListRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); appListRecyclerView.setAdapter(appListRecyclerAdapter); } //method to check for internet permission // 1. returns a list with Strings --> goes into the app_list_name // 2. fills the Map sort_map private List provideAppList() { ArrayList packageNames = new ArrayList<>(); PackageManager p = this.getPackageManager(); final List packs = p.getInstalledPackages(0); List packs_permission = p.getInstalledPackages(PackageManager.GET_PERMISSIONS); //This FOR goes through every app that is installed on the device according to // --> p.getInstalledPackages(0); for (int i = 0; i < packs.size(); i++) { PackageInfo pinfo = packs.get(i); //This Var has the actual Information about an app (not the permission) PackageInfo appPermission = packs_permission.get(i); //If the App has NULL permissions then skip it if (appPermission.requestedPermissions == null) { continue; } //Check if App has Internet Permission for (String permission : appPermission.requestedPermissions) { //Checking for Internet permission if (TextUtils.equals(permission, android.Manifest.permission.INTERNET)) { sortMap.put(pinfo.applicationInfo.loadLabel(getPackageManager()).toString(), pinfo.packageName); break; } } } //Actual sorting alpabetic and convert into the String List "packageNames" Set set2 = sortMap.entrySet(); Iterator iterator2 = set2.iterator(); while (iterator2.hasNext()) { Map.Entry me2 = (Map.Entry) iterator2.next(); packageNames.add(me2.getValue().toString()); } return packageNames; } //enables the menue and provides the search method @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.applistseletion_menu, menu); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); //search method searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextChange(String searchText) { app_list_name.clear(); for (Map.Entry entry : sortMap.entrySet()) { if (entry.getKey().toLowerCase().contains(searchText.toLowerCase())) { app_list_name.add(entry.getValue().toString()); } } appListRecyclerView = (RecyclerView) findViewById(R.id.list_selection_app_recycler); recyclerLayoutManager = new LinearLayoutManager(getContext()); appListRecyclerView.setLayoutManager(recyclerLayoutManager); // specify an adapter appListRecyclerAdapter = new AppListRecyclerAdapter(app_list_name, SelectHistoryAppsActivity.this); appListRecyclerView.addItemDecoration(new DividerItemDecoration(SelectHistoryAppsActivity.this, LinearLayoutManager.VERTICAL)); appListRecyclerView.setAdapter(appListRecyclerAdapter); return false; } @Override public boolean onQueryTextSubmit(String query) { return false; } }); // MenuItem deleteItem = menu.findItem(R.id.deleteButton); // deleteItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { // @Override // public boolean onMenuItemClick(MenuItem item) { // // List appsToDelete = appAdapter.getAppsToDelete(); // Toast toast; // // List reportEntities = reportEntityDao.loadAll(); // // if (!appsToDelete.isEmpty()) { // // for (Integer i : appsToDelete) { // String appName = (String) appAdapter.getItem(i); // for (ReportEntity reportEntity : reportEntities) { // if (reportEntity.getAppName().equals(appName)) { // reportEntityDao.delete(reportEntity); // editor.remove(appName); // editor.commit(); // } // } // Collector.deleteAppFromIncludeInScan(appName); // } // // toast = Toast.makeText(getApplicationContext(), "Reports have been deleted", Toast.LENGTH_SHORT); // toast.show(); // } else { // toast = Toast.makeText(getApplicationContext(), "No reports available to delete.", Toast.LENGTH_SHORT); // toast.show(); // } // // return false; // } // }); return true; } //inspection for sort selection @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. // [See PFA Note APP] int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_sort_alphabetical_asc) { item.setChecked(true); sortAlphabetic_asc(); } else if (id == R.id.action_sort_alphabetical_desc) { item.setChecked(true); sortAlphabetic_desc(); } else if (id == R.id.action_sort_installdate_asc) { item.setChecked(true); sortInstalledDate_asc(); } else if (id == R.id.action_sort_installdate_desc) { item.setChecked(true); sortInstalledDate_desc(); } appListRecyclerView = (RecyclerView) findViewById(R.id.list_selection_app_recycler); recyclerLayoutManager = new LinearLayoutManager(getContext()); appListRecyclerView.setLayoutManager(recyclerLayoutManager); // specify an adapter appListRecyclerAdapter = new AppListRecyclerAdapter(app_list_name, SelectHistoryAppsActivity.this); appListRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); appListRecyclerView.setAdapter(appListRecyclerAdapter); return super.onOptionsItemSelected(item); } private void sortAlphabetic_asc() { app_list_name.clear(); AscComparator comp = new AscComparator(sortMap); Map newMap = new TreeMap(comp); newMap.putAll(sortMap); sortMap = newMap; for (Map.Entry entry : sortMap.entrySet()) { app_list_name.add(entry.getValue().toString()); } } private void sortAlphabetic_desc() { app_list_name.clear(); DescComparator comp = new DescComparator(sortMap); Map newMap = new TreeMap(comp); newMap.putAll(sortMap); sortMap = newMap; for (Map.Entry entry : sortMap.entrySet()) { app_list_name.add(entry.getValue().toString()); } } private void sortInstalledDate_asc() { Map> appdates = new TreeMap<>(); PackageManager packageManager = this.getPackageManager(); for (int i = 0; i < app_list_name.size(); i++) { PackageInfo packageInfo = null; try { packageInfo = packageManager.getPackageInfo(app_list_name.get(i), 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } long installTimeInMilliseconds = packageInfo.firstInstallTime; if (appdates.containsKey(installTimeInMilliseconds)) { appdates.get(installTimeInMilliseconds).add(app_list_name.get(i)); } else { ArrayList temp = new ArrayList(); temp.add(app_list_name.get(i)); appdates.put(installTimeInMilliseconds, temp); } } AscComparator comp = new AscComparator(appdates); Map> newMap = new TreeMap(comp); newMap.putAll(appdates); appdates = newMap; app_list_name.clear(); for (Long key : appdates.keySet()) { for (String s : appdates.get(key)) { app_list_name.add(s); } } } private void sortInstalledDate_desc() { Map> appdates = new TreeMap<>(); PackageManager packageManager = this.getPackageManager(); for (int i = 0; i < app_list_name.size(); i++) { PackageInfo packageInfo = null; try { packageInfo = packageManager.getPackageInfo(app_list_name.get(i), 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } long installTimeInMilliseconds = packageInfo.firstInstallTime; if (appdates.containsKey(installTimeInMilliseconds)) { appdates.get(installTimeInMilliseconds).add(app_list_name.get(i)); } else { ArrayList temp = new ArrayList(); temp.add(app_list_name.get(i)); appdates.put(installTimeInMilliseconds, temp); } } DescComparator comp = new DescComparator(appdates); Map> newMap = new TreeMap(comp); newMap.putAll(appdates); appdates = newMap; app_list_name.clear(); for (Long key : appdates.keySet()) { for (String s : appdates.get(key)) { app_list_name.add(s); } } } class AscComparator implements Comparator { Map map; public AscComparator(Map map) { this.map = map; } @Override public int compare(Object o1, Object o2) { return (o1.toString()).compareToIgnoreCase(o2.toString()); } } class DescComparator implements Comparator { Map map; public DescComparator(Map map) { this.map = map; } @Override public int compare(Object o1, Object o2) { return (o2.toString()).compareToIgnoreCase(o1.toString()); } } @Override public void onBackPressed() { /* if (appAdapter.getAppsToDelete() != null && !appAdapter.getAppsToDelete().isEmpty()) { List appsToDelete = appAdapter.getAppsToDelete(); for (int i : appsToDelete) { String appName = (String) appAdapter.getItem(i); ((RelativeLayout) userInstalledAppsView.getChildAt(i)).setBackgroundColor(Color.WHITE); } appAdapter.getAppsToDelete().clear(); } else { super.onBackPressed(); } */ super.onBackPressed(); } // private void deleteConfirmation() { // // AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle(R.string.dialogTitle); // builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // // //... // //insert unselect function // //... // // Toast.makeText(getApplicationContext(), "All Apps have been unselected.", Toast.LENGTH_SHORT).show(); // // } // }); // builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // Toast.makeText(getApplicationContext(), "Deletion canceled.", Toast.LENGTH_SHORT).show(); // } // }); // System.out.println("Building complete"); // AlertDialog dialog = builder.create(); // dialog.show(); // // } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/SettingsActivity.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.util.Log; import android.view.MenuItem; import org.secuso.privacyfriendlynetmonitor.Assistant.Const; import org.secuso.privacyfriendlynetmonitor.Assistant.RunStore; import org.secuso.privacyfriendlynetmonitor.R; /** * Activity providing app settings */ public class SettingsActivity extends BaseActivity { /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object value) { String stringValue = value.toString(); Log.d(Const.LOG_TAG, stringValue); if (preference instanceof ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. ListPreference listPreference = (ListPreference) preference; int index = listPreference.findIndexOfValue(stringValue); // Set the summary to reflect the new value. preference.setSummary( index >= 0 ? listPreference.getEntries()[index] : null); } else { // For all other preferences, set the summary to the value's // simple string representation. preference.setSummary(stringValue); } return true; } }; /** * Helper method to determine if the device has an extra-large screen. For * example, 10" tablets are extra-large. */ private static boolean isXLargeTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE; } /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * * @see #sBindPreferenceSummaryToValueListener */ private static void bindPreferenceSummaryToValue(Preference preference) { // Set the listener to watch for value changes. preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); // Trigger the listener immediately with the preference's // current value. sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getString(preference.getKey(), "")); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); RunStore.setContext(this); setContentView(R.layout.activity_settings); //setupActionBar(); overridePendingTransition(0, 0); } @Override protected int getNavigationDrawerID() { return R.id.nav_settings; } /** * This method stops fragment injection in malicious applications. * Make sure to deny any unknown fragments here. */ protected boolean isValidFragment(String fragmentName) { return PreferenceFragment.class.getName().equals(fragmentName) || GeneralPreferenceFragment.class.getName().equals(fragmentName); } /** * This fragment shows general preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class GeneralPreferenceFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); //setHasOptionsMenu(true); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. //bindPreferenceSummaryToValue(findPreference("example_text")); //bindPreferenceSummaryToValue(findPreference("example_list")); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { //getAppContext().finish(); startActivity(new Intent(getActivity(), SettingsActivity.class)); return true; } return super.onOptionsItemSelected(item); } } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/SplashActivity.java ================================================ /** * This file is part of Privacy Friendly Password Generator. * Privacy Friendly Password Generator 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 any later version. * Privacy Friendly Password Generator 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 Privacy Friendly Password Generator. If not, see . */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.content.Intent; import android.os.Build; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import org.secuso.privacyfriendlynetmonitor.Assistant.PrefManager; import org.secuso.privacyfriendlynetmonitor.R; /** * @author Karola Marky * @version 20161022 */ public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent mainIntent = null; PrefManager prefManager = new PrefManager(this); if(prefManager.isFirstTimeLaunch()) { mainIntent = new Intent(this, TutorialActivity.class); prefManager.setFirstTimeLaunch(false); } else { mainIntent = new Intent(this, MainActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } setContentView(R.layout.activity_splash); TextView compatibilityInfo = findViewById(R.id.compatibility_text); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P){ compatibilityInfo.setVisibility(View.VISIBLE); } else { compatibilityInfo.setVisibility(View.INVISIBLE); //Intent mainIntent = new Intent(SplashActivity.this, TutorialActivity.class); SplashActivity.this.startActivity(mainIntent); SplashActivity.this.finish(); } } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Activities/TutorialActivity.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Activities; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.AppCompatActivity; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import org.secuso.privacyfriendlynetmonitor.Assistant.PrefManager; import org.secuso.privacyfriendlynetmonitor.R; /** * Welcome tutorial for basic understanding of app features * Class structure taken from tutorial at http://www.androidhive.info/2016/05/android-build-intro-slider-app/ * The tutorial is accessible from the navigation drawer */ public class TutorialActivity extends AppCompatActivity { private ViewPager viewPager; private MyViewPagerAdapter myViewPagerAdapter; private LinearLayout dotsLayout; private TextView[] dots; private int[] layouts; private Button btnSkip, btnNext; private PrefManager prefManager; private static boolean tutorial_click = false; public static void setTutorial_click(boolean tutorial_click) { TutorialActivity.tutorial_click = tutorial_click; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Checking for first time launch - before calling setContentView() //prefManager = new PrefManager(this); //if (!prefManager.isFirstTimeLaunch()) { // if (tutorial_click == false) { // launchHomeScreen(); // finish(); // } //} //tutorial_click = false; // Making notification bar transparent if (Build.VERSION.SDK_INT >= 21) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } setContentView(R.layout.activity_tutorial); viewPager = findViewById(R.id.view_pager); dotsLayout = findViewById(R.id.layoutDots); btnSkip = findViewById(R.id.btn_skip); btnNext = findViewById(R.id.btn_next); // layouts of all welcome sliders // add few more layouts if you want layouts = new int[]{ R.layout.tutorial_slide1, R.layout.tutorial_slide2, R.layout.tutorial_slide3,}; // adding bottom dots addBottomDots(0); // making notification bar transparent changeStatusBarColor(); myViewPagerAdapter = new MyViewPagerAdapter(); viewPager.setAdapter(myViewPagerAdapter); viewPager.addOnPageChangeListener(viewPagerPageChangeListener); btnSkip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking for last page // if last page home screen will be launched int current = getItem(+1); if (current < layouts.length) { launchHomeScreen(); } else { launchHelp(); } } }); btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking for last page // if last page home screen will be launched int current = getItem(+1); if (current < layouts.length) { // move to next screen viewPager.setCurrentItem(current); } else { launchHomeScreen(); } } }); } private void addBottomDots(int currentPage) { dots = new TextView[layouts.length]; int[] colorsActive = getResources().getIntArray(R.array.array_dot_active); int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive); dotsLayout.removeAllViews(); for (int i = 0; i < dots.length; i++) { dots[i] = new TextView(this); dots[i].setText(Html.fromHtml("•")); dots[i].setTextSize(35); dots[i].setTextColor(colorsInactive[currentPage]); dotsLayout.addView(dots[i]); } if (dots.length > 0) dots[currentPage].setTextColor(colorsActive[currentPage]); } private int getItem(int i) { return viewPager.getCurrentItem() + i; } private void launchHomeScreen() { Intent intent = new Intent(this, MainActivity.class); //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); prefManager.setFirstTimeLaunch(false); startActivity(intent); finish(); } private void launchHelp() { Intent intent = new Intent(this, HelpActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); prefManager.setFirstTimeLaunch(false); startActivity(intent); finish(); } // viewpager change listener ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { addBottomDots(position); // changing the next button text 'NEXT' / 'GOT IT' if (position == layouts.length - 1) { // last page. make button text to GOT IT btnNext.setText(getString(R.string.okay)); //btnSkip.setVisibility(View.GONE); btnSkip.setText(getString(R.string.help_button)); } else { // still pages are left btnNext.setText(getString(R.string.next)); btnSkip.setText(getString(R.string.skip)); btnSkip.setVisibility(View.VISIBLE); } } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }; //Making notification bar transparent private void changeStatusBarColor() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); } } //View pager adapter public class MyViewPagerAdapter extends PagerAdapter { private LayoutInflater layoutInflater; public MyViewPagerAdapter() { } @Override public Object instantiateItem(ViewGroup container, int position) { layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(layouts[position], container, false); container.addView(view); return view; } @Override public int getCount() { return layouts.length; } @Override public boolean isViewFromObject(View view, Object obj) { return view == obj; } @Override public void destroyItem(ViewGroup container, int position, Object object) { View view = (View) object; container.removeView(view); } } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Assistant/AsyncCertVal.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Assistant; import android.os.AsyncTask; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.Collector; import java.util.ArrayList; import java.util.List; import java.util.Map; import de.bjoernr.ssllabs.Api; import de.bjoernr.ssllabs.ConsoleUtilities; /** * Class for performing asynchronous requests of JSON Objects via SSL-Labs API *

* Qualis SSL Labs API: https://www.ssllabs.com/projects/ssllabs-apis * Java-SSLLabs-API Björn Roland and Qualis SSL Labs: https://github.com/bjoernr-de */ public class AsyncCertVal extends AsyncTask { private Api mSSLLabsApi; public AsyncCertVal() { mSSLLabsApi = new Api(); } @Override public Void doInBackground(Void... voids) { if (Collector.sCertValList.size() > 0) { fetchHostInfo(Collector.sCertValList); } return null; } //Fetch cached information from SSL Labs using list of hostnames private void fetchHostInfo(List urls) { int count = getMaxAssessments(); JSONObject hostInfo; String host; ArrayList pendingList = new ArrayList<>(); while (count > 0 && urls.size() > 0) { host = urls.get(0); hostInfo = mSSLLabsApi.fetchHostInformationCached(host, null, false, false); // add to map if not empty Map map = null; try { map = ConsoleUtilities.jsonToMap(hostInfo); } catch (JSONException ignore) { } if (map != null && map.size() > 0) { Collector.mCertValMap.put(host, map); } //continue to resolve if request not ready if (map != null && map.size() > 0 && !Collector.analyseReady(map)) { pendingList.add(host); } urls.remove(0); count--; if (Const.IS_DEBUG) { Log.d(Const.LOG_TAG, ConsoleUtilities.mapToConsoleOutput(map)); } } // manage pending lists Collector.sCertValList.addAll(pendingList); Collector.updateCertHostHandler(); } // Get number off allowed request at the time private int getMaxAssessments() { final String max = "maxAssessments"; JSONObject hostInfo = mSSLLabsApi.fetchApiInfo(); Map map = null; try { map = ConsoleUtilities.jsonToMap(hostInfo); } catch (JSONException ignore) { } if (Const.IS_DEBUG) { Log.d(Const.LOG_TAG, ConsoleUtilities.mapToConsoleOutput(map)); } if (map.containsKey(max)) { return (Integer) map.get(max); } else { return 0; } } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Assistant/AsyncDNS.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Assistant; import android.os.AsyncTask; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.Collector; /** * Helper class, executes asynchronous DNS requests. */ public class AsyncDNS extends AsyncTask { //execute reverse hostname resolving in Collector class @Override protected String doInBackground(String... params) { Collector.resolveHosts(); return "Executed!"; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Assistant/Const.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Assistant; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Storing constant values for various usages within the app */ public interface Const { //App constants boolean IS_DEBUG = false; String LOG_TAG = "NetMonitor"; String FILE_IF_LIST = "iflist"; //SSL LABS CONSTANTS String SSLLABS_URL = "https://www.ssllabs.com/ssltest/analyze.html?d="; //Detector constants long REPORT_TTL_DEFAULT = 10000; Integer[] TLS_PORT_VALUES = new Integer[]{993, 443, 995, 995, 614, 465, 587, 22}; Set TLS_PORTS = new HashSet<>(Arrays.asList(TLS_PORT_VALUES)); Integer[] INCONCLUSIVE_PORT_VALUES = new Integer[]{25, 110, 143}; Set INCONCUSIVE_PORTS = new HashSet<>(Arrays.asList(INCONCLUSIVE_PORT_VALUES)); Integer[] UNSECURE_PORT_VALUES = new Integer[]{21, 23, 80, 109, 137, 138, 139, 161, 992}; Set UNSECURE_PORTS = new HashSet<>(Arrays.asList(UNSECURE_PORT_VALUES)); //String Builder Constants String STATUS_TLS = "Encrypted"; String STATUS_UNSECURE = "Unencrypted"; String STATUS_INCONCLUSIVE = "Inconclusive"; String STATUS_UNKNOWN = "Unknown"; //SharedPrefs identifiers String REPORT_TTL = "REPORT_TTL"; String IS_DETAIL_MODE = "IS_DETAIL_MODE"; String IS_FIRST_START = "IS_FIRST_START"; String IS_LOG = "IS_LOG"; String IS_CERTVAL = "IS_CERTVAL"; String PREF_NAME = "PREF_NAME"; String IS_HIGHLIGHTED = "IS_HIGHLIGHTED"; } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Assistant/ExecCom.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Assistant; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; /** * Handles the execution of shell commands. */ public class ExecCom extends Thread { //Execute user commands on shell static void user(String string) { if (Const.IS_DEBUG) Log.d(Const.LOG_TAG, "Executing as user: " + string); try { Process user = Runtime.getRuntime().exec(string); try { user.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } //Execute user commands and get the result. public static String userForResult(String string) { if (Const.IS_DEBUG) Log.d(Const.LOG_TAG, "Executing for result as user: " + string); String res = ""; DataOutputStream outputStream = null; InputStream response = null; try { Process user = Runtime.getRuntime().exec(string); outputStream = new DataOutputStream(user.getOutputStream()); response = user.getInputStream(); outputStream.writeBytes("exit\n"); outputStream.flush(); try { user.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } res = readFully(response); } catch (IOException e) { if (Const.IS_DEBUG) { Log.i(Const.LOG_TAG, "IO operation unsuccessful. Pipe Broken?" + string); } } finally { closeSilently(outputStream, response); } return res; } //Read the command output and return an utf8 string. public static String readFully(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length = 0; while ((length = is.read(buffer)) != -1) { baos.write(buffer, 0, length); } return baos.toString("UTF-8"); } //Closes a variety of closable objects. public static void closeSilently(Object... xs) { // Note: on Android API levels prior to 19 Socket does not implement Closeable for (Object x : xs) { if (x != null) { try { if (x instanceof Closeable) { ((Closeable) x).close(); } else { Log.d(Const.LOG_TAG, "cannot close: " + x); throw new RuntimeException("cannot close " + x); } } catch (Throwable e) { e.printStackTrace(); } } } } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Assistant/KnownPorts.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Assistant; import java.util.HashMap; /** * Assistant class to resolve well-known (reserved) ports */ public class KnownPorts { private static HashMap m; //get protocol desc based on port number public static String resolvePort(int port) { if (m.containsKey(port)) { return m.get(port); } else { return "unknown"; } } public static String CompileConnectionInfo(int remotePort, TLType type) { String info; if (isTlsPort(remotePort)) { info = Const.STATUS_TLS; } else if (isUnsecurePort(remotePort)) { info = Const.STATUS_UNSECURE; } else if (isInconclusivePort(remotePort)) { info = Const.STATUS_INCONCLUSIVE; } else { info = Const.STATUS_UNKNOWN; } return info + " (" + resolvePort(remotePort) + ", " + type + ")"; } //Test if port number is well known for TLS connection public static boolean isTlsPort(int i) { return Const.TLS_PORTS.contains(i); } //Test if port number is inconclusive (e.g. STARTTLS) public static boolean isInconclusivePort(int i) { return Const.INCONCUSIVE_PORTS.contains(i); } //Test if port number is well known for unencrypted connection public static boolean isUnsecurePort(int i) { return Const.UNSECURE_PORTS.contains(i); } //init hash map with reserved ports (1-1024) and protocol identifiers //based on: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml public static void initPortMap() { m = new HashMap<>(); m.put(1, "tcpmux"); m.put(2, "compressnet"); m.put(3, "compressnet"); m.put(5, "rje"); m.put(7, "echo"); m.put(9, "discard"); m.put(11, "systat"); m.put(13, "daytime"); m.put(17, "qotd"); m.put(18, "msp"); m.put(19, "chargen"); m.put(20, "ftp-data"); m.put(21, "ftp"); m.put(22, "ssh"); m.put(23, "telnet"); m.put(25, "smtp"); m.put(27, "nsw-fe"); m.put(29, "msg-icp"); m.put(31, "msg-auth"); m.put(33, "dsp"); m.put(37, "time"); m.put(38, "rap"); m.put(39, "rlp"); m.put(41, "graphics"); m.put(42, "name"); m.put(43, "nicname"); m.put(44, "mpm-flags"); m.put(45, "mpm"); m.put(46, "mpm-snd"); m.put(47, "ni-ftp"); m.put(48, "auditd"); m.put(49, "tacacs"); m.put(50, "re-mail-ck"); m.put(52, "xns-time"); m.put(53, "domain"); m.put(54, "xns-ch"); m.put(55, "isi-gl"); m.put(56, "xns-auth"); m.put(58, "xns-mail"); m.put(61, "ni-mail"); m.put(62, "acas"); m.put(63, "whoispp"); m.put(64, "covia"); m.put(65, "tacacs-ds"); m.put(66, "sql-net"); m.put(67, "bootps"); m.put(68, "bootpc"); m.put(69, "tftp"); m.put(70, "gopher"); m.put(71, "netrjs-1"); m.put(72, "netrjs-2"); m.put(73, "netrjs-3"); m.put(74, "netrjs-4"); m.put(76, "deos"); m.put(78, "vettcp"); m.put(79, "finger"); m.put(80, "http"); m.put(82, "xfer"); m.put(83, "mit-ml-dev"); m.put(84, "ctf"); m.put(85, "mit-ml-dev"); m.put(86, "mfcobol"); m.put(88, "kerberos"); m.put(89, "su-mit-tg"); m.put(90, "dnsix"); m.put(91, "mit-dov"); m.put(92, "npp"); m.put(93, "dcp"); m.put(94, "objcall"); m.put(95, "supdup"); m.put(96, "dixie"); m.put(97, "swift-rvf"); m.put(98, "tacnews"); m.put(99, "metagram"); m.put(101, "hostname"); m.put(102, "iso-tsap"); m.put(103, "gppitnp"); m.put(104, "acr-nema"); m.put(105, "cso"); m.put(106, "3com-tsmux"); m.put(107, "rtelnet"); m.put(108, "snagas"); m.put(109, "pop2"); m.put(110, "pop3"); m.put(111, "sunrpc"); m.put(112, "mcidas"); m.put(113, "ident"); m.put(115, "sftp"); m.put(116, "ansanotify"); m.put(117, "uucp-path"); m.put(118, "sqlserv"); m.put(119, "nntp"); m.put(120, "cfdptkt"); m.put(121, "erpc"); m.put(122, "smakynet"); m.put(123, "ntp"); m.put(124, "ansatrader"); m.put(125, "locus-map"); m.put(126, "nxedit"); m.put(127, "locus-con"); m.put(128, "gss-xlicen"); m.put(129, "pwdgen"); m.put(130, "cisco-fna"); m.put(131, "cisco-tna"); m.put(132, "cisco-sys"); m.put(133, "statsrv"); m.put(134, "ingres-net"); m.put(135, "epmap"); m.put(136, "profile"); m.put(137, "netbios-ns"); m.put(138, "netbios-dgm"); m.put(139, "netbios-ssn"); m.put(140, "emfis-data"); m.put(141, "emfis-cntl"); m.put(142, "bl-idm"); m.put(143, "imap"); m.put(144, "uma"); m.put(145, "uaac"); m.put(146, "iso-tp0"); m.put(147, "iso-ip"); m.put(148, "jargon"); m.put(149, "aed-512"); m.put(150, "sql-net"); m.put(151, "hems"); m.put(152, "bftp"); m.put(153, "sgmp"); m.put(154, "netsc-prod"); m.put(155, "netsc-dev"); m.put(156, "sqlsrv"); m.put(157, "knet-cmp"); m.put(158, "pcmail-srv"); m.put(159, "nss-routing"); m.put(160, "sgmp-traps"); m.put(161, "snmp"); m.put(162, "snmptrap"); m.put(163, "cmip-man"); m.put(164, "cmip-agent"); m.put(165, "xns-courier"); m.put(166, "s-net"); m.put(167, "namp"); m.put(168, "rsvd"); m.put(169, "send"); m.put(170, "print-srv"); m.put(171, "multiplex"); m.put(172, "cl-1"); m.put(173, "xyplex-mux"); m.put(174, "mailq"); m.put(175, "vmnet"); m.put(176, "genrad-mux"); m.put(177, "xdmcp"); m.put(178, "nextstep"); m.put(179, "bgp"); m.put(180, "ris"); m.put(181, "unify"); m.put(182, "audit"); m.put(183, "ocbinder"); m.put(184, "ocserver"); m.put(185, "remote-kis"); m.put(186, "kis"); m.put(187, "aci"); m.put(188, "mumps"); m.put(189, "qft"); m.put(190, "gacp"); m.put(191, "prospero"); m.put(192, "osu-nms"); m.put(193, "srmp"); m.put(194, "irc"); m.put(195, "dn6-nlm-aud"); m.put(196, "dn6-smm-red"); m.put(197, "dls"); m.put(198, "dls-mon"); m.put(199, "smux"); m.put(200, "src"); m.put(201, "at-rtmp"); m.put(202, "at-nbp"); m.put(203, "at-3"); m.put(204, "at-echo"); m.put(205, "at-5"); m.put(206, "at-zis"); m.put(207, "at-7"); m.put(208, "at-8"); m.put(209, "qmtp"); m.put(210, "z39-50"); m.put(211, "914c-g"); m.put(212, "anet"); m.put(213, "ipx"); m.put(214, "vmpwscs"); m.put(215, "softpc"); m.put(216, "CAIlic"); m.put(217, "dbase"); m.put(218, "mpp"); m.put(219, "uarps"); m.put(220, "imap3"); m.put(221, "fln-spx"); m.put(222, "rsh-spx"); m.put(223, "cdc"); m.put(224, "masqdialer"); m.put(242, "direct"); m.put(243, "sur-meas"); m.put(244, "inbusiness"); m.put(245, "link"); m.put(246, "dsp3270"); m.put(247, "subntbcst-tftp"); m.put(248, "bhfhs"); m.put(256, "rap"); m.put(257, "set"); m.put(259, "esro-gen"); m.put(260, "openport"); m.put(261, "nsiiops"); m.put(262, "arcisdms"); m.put(263, "hdap"); m.put(264, "bgmp"); m.put(265, "x-bone-ctl"); m.put(266, "sst"); m.put(267, "td-service"); m.put(268, "td-replica"); m.put(269, "manet"); m.put(270, "gist"); m.put(271, "pt-tls"); m.put(280, "http-mgmt"); m.put(281, "personal-link"); m.put(282, "cableport-ax"); m.put(283, "rescap"); m.put(284, "corerjd"); m.put(286, "fxp"); m.put(287, "k-block"); m.put(308, "novastorbakcup"); m.put(309, "entrusttime"); m.put(310, "bhmds"); m.put(311, "asip-webadmin"); m.put(312, "vslmp"); m.put(313, "magenta-logic"); m.put(314, "opalis-robot"); m.put(315, "dpsi"); m.put(316, "decauth"); m.put(317, "zannet"); m.put(318, "pkix-timestamp"); m.put(319, "ptp-event"); m.put(320, "ptp-general"); m.put(321, "pip"); m.put(322, "rtsps"); m.put(323, "rpki-rtr"); m.put(324, "rpki-rtr-tls"); m.put(333, "texar"); m.put(344, "pdap"); m.put(345, "pawserv"); m.put(346, "zserv"); m.put(347, "fatserv"); m.put(348, "csi-sgwp"); m.put(349, "mftp"); m.put(350, "matip-type-a"); m.put(351, "matip-type-b"); m.put(352, "dtag-ste-sb"); m.put(353, "ndsauth"); m.put(354, "bh611"); m.put(355, "datex-asn"); m.put(356, "cloanto-net-1"); m.put(357, "bhevent"); m.put(358, "shrinkwrap"); m.put(359, "nsrmp"); m.put(360, "scoi2odialog"); m.put(361, "semantix"); m.put(362, "srssend"); m.put(363, "rsvp-tunnel"); m.put(364, "aurora-cmgr"); m.put(365, "dtk"); m.put(366, "odmr"); m.put(367, "mortgageware"); m.put(368, "qbikgdp"); m.put(369, "rpc2portmap"); m.put(370, "codaauth2"); m.put(371, "clearcase"); m.put(372, "ulistproc"); m.put(373, "legent-1"); m.put(374, "legent-2"); m.put(375, "hassle"); m.put(376, "nip"); m.put(377, "tnETOS"); m.put(378, "dsETOS"); m.put(379, "is99c"); m.put(380, "is99s"); m.put(381, "hp-collector"); m.put(382, "hp-managed-node"); m.put(383, "hp-alarm-mgr"); m.put(384, "arns"); m.put(385, "ibm-app"); m.put(386, "asa"); m.put(387, "aurp"); m.put(388, "unidata-ldm"); m.put(389, "ldap"); m.put(390, "uis"); m.put(391, "synotics-relay"); m.put(392, "synotics-broker"); m.put(393, "meta5"); m.put(394, "embl-ndt"); m.put(395, "netcp"); m.put(396, "netware-ip"); m.put(397, "mptn"); m.put(398, "kryptolan"); m.put(399, "iso-tsap-c2"); m.put(400, "osb-sd"); m.put(401, "ups"); m.put(402, "genie"); m.put(403, "decap"); m.put(404, "nced"); m.put(405, "ncld"); m.put(406, "imsp"); m.put(407, "timbuktu"); m.put(408, "prm-sm"); m.put(409, "prm-nm"); m.put(410, "decladebug"); m.put(411, "rmt"); m.put(412, "synoptics-trap"); m.put(413, "smsp"); m.put(414, "infoseek"); m.put(415, "bnet"); m.put(416, "silverplatter"); m.put(417, "onmux"); m.put(418, "hyper-g"); m.put(419, "ariel1"); m.put(420, "smpte"); m.put(421, "ariel2"); m.put(422, "ariel3"); m.put(423, "opc-job-start"); m.put(424, "opc-job-track"); m.put(425, "icad-el"); m.put(426, "smartsdp"); m.put(427, "svrloc"); m.put(428, "ocs-cmu"); m.put(429, "ocs-amu"); m.put(430, "utmpsd"); m.put(431, "utmpcd"); m.put(432, "iasd"); m.put(433, "nnsp"); m.put(434, "mobileip-agent"); m.put(435, "mobilip-mn"); m.put(436, "dna-cml"); m.put(437, "comscm"); m.put(438, "dsfgw"); m.put(439, "dasp"); m.put(440, "sgcp"); m.put(441, "decvms-sysmgt"); m.put(442, "cvc-hostd"); m.put(443, "https"); m.put(444, "snpp"); m.put(445, "microsoft-ds"); m.put(446, "ddm-rdb"); m.put(447, "ddm-dfm"); m.put(448, "ddm-ssl"); m.put(449, "as-servermap"); m.put(450, "tserver"); m.put(451, "sfs-smp-net"); m.put(452, "sfs-config"); m.put(453, "creativeserver"); m.put(454, "contentserver"); m.put(455, "creativepartnr"); m.put(456, "macon-tcp"); m.put(457, "scohelp"); m.put(458, "appleqtc"); m.put(459, "ampr-rcmd"); m.put(460, "skronk"); m.put(461, "datasurfsrv"); m.put(462, "datasurfsrvsec"); m.put(463, "alpes"); m.put(464, "kpasswd"); m.put(465, "urd"); m.put(466, "digital-vrc"); m.put(467, "mylex-mapd"); m.put(468, "photuris"); m.put(469, "rcp"); m.put(470, "scx-proxy"); m.put(471, "mondex"); m.put(472, "ljk-login"); m.put(473, "hybrid-pop"); m.put(474, "tn-tl-w1"); m.put(475, "tcpnethaspsrv"); m.put(476, "tn-tl-fd1"); m.put(477, "ss7ns"); m.put(478, "spsc"); m.put(479, "iafserver"); m.put(480, "iafdbase"); m.put(481, "ph"); m.put(482, "bgs-nsi"); m.put(483, "ulpnet"); m.put(484, "integra-sme"); m.put(485, "powerburst"); m.put(486, "avian"); m.put(487, "saft"); m.put(488, "gss-http"); m.put(489, "nest-protocol"); m.put(490, "micom-pfs"); m.put(491, "go-login"); m.put(492, "ticf-1"); m.put(493, "ticf-2"); m.put(494, "pov-ray"); m.put(495, "intecourier"); m.put(496, "pim-rp-disc"); m.put(497, "retrospect"); m.put(498, "siam"); m.put(499, "iso-ill"); m.put(500, "isakmp"); m.put(501, "stmf"); m.put(502, "mbap"); m.put(503, "intrinsa"); m.put(504, "citadel"); m.put(505, "mailbox-lm"); m.put(506, "ohimsrv"); m.put(507, "crs"); m.put(508, "xvttp"); m.put(509, "snare"); m.put(510, "fcp"); m.put(511, "passgo"); m.put(512, "exec"); m.put(513, "login"); m.put(514, "shell"); m.put(515, "printer"); m.put(516, "videotex"); m.put(517, "talk"); m.put(518, "ntalk"); m.put(519, "utime"); m.put(520, "efs"); m.put(521, "ripng"); m.put(522, "ulp"); m.put(523, "ibm-db2"); m.put(524, "ncp"); m.put(525, "timed"); m.put(526, "tempo"); m.put(527, "stx"); m.put(528, "custix"); m.put(529, "irc-serv"); m.put(530, "courier"); m.put(531, "conference"); m.put(532, "netnews"); m.put(533, "netwall"); m.put(534, "windream"); m.put(535, "iiop"); m.put(536, "opalis-rdv"); m.put(537, "nmsp"); m.put(538, "gdomap"); m.put(539, "apertus-ldp"); m.put(540, "uucp"); m.put(541, "uucp-rlogin"); m.put(542, "commerce"); m.put(543, "klogin"); m.put(544, "kshell"); m.put(545, "appleqtcsrvr"); m.put(546, "dhcpv6-client"); m.put(547, "dhcpv6-server"); m.put(548, "afpovertcp"); m.put(549, "idfp"); m.put(550, "new-rwho"); m.put(551, "cybercash"); m.put(552, "devshr-nts"); m.put(553, "pirp"); m.put(554, "rtsp"); m.put(555, "dsf"); m.put(556, "remotefs"); m.put(557, "openvms-sysipc"); m.put(558, "sdnskmp"); m.put(559, "teedtap"); m.put(560, "rmonitor"); m.put(561, "monitor"); m.put(562, "chshell"); m.put(563, "nntps"); m.put(564, "9pfs"); m.put(565, "whoami"); m.put(566, "streettalk"); m.put(567, "banyan-rpc"); m.put(568, "ms-shuttle"); m.put(569, "ms-rome"); m.put(570, "meter"); m.put(571, "meter"); m.put(572, "sonar"); m.put(573, "banyan-vip"); m.put(574, "ftp-agent"); m.put(575, "vemmi"); m.put(576, "ipcd"); m.put(577, "vnas"); m.put(578, "ipdd"); m.put(579, "decbsrv"); m.put(580, "sntp-heartbeat"); m.put(581, "bdp"); m.put(582, "scc-security"); m.put(583, "philips-vc"); m.put(584, "keyserver"); m.put(586, "password-chg"); m.put(587, "submission"); m.put(588, "cal"); m.put(589, "eyelink"); m.put(590, "tns-cml"); m.put(591, "http-alt"); m.put(592, "eudora-set"); m.put(593, "http-rpc-epmap"); m.put(594, "tpip"); m.put(595, "cab-protocol"); m.put(596, "smsd"); m.put(597, "ptcnameservice"); m.put(598, "sco-websrvrmg3"); m.put(599, "acp"); m.put(600, "ipcserver"); m.put(601, "syslog-conn"); m.put(602, "xmlrpc-beep"); m.put(603, "idxp"); m.put(604, "tunnel"); m.put(605, "soap-beep"); m.put(606, "urm"); m.put(607, "nqs"); m.put(608, "sift-uft"); m.put(609, "npmp-trap"); m.put(610, "npmp-local"); m.put(611, "npmp-gui"); m.put(612, "hmmp-ind"); m.put(613, "hmmp-op"); m.put(614, "sshell"); m.put(615, "sco-inetmgr"); m.put(616, "sco-sysmgr"); m.put(617, "sco-dtmgr"); m.put(618, "dei-icda"); m.put(619, "compaq-evm"); m.put(620, "sco-websrvrmgr"); m.put(621, "escp-ip"); m.put(622, "collaborator"); m.put(623, "oob-ws-http"); m.put(624, "cryptoadmin"); m.put(625, "dec-dlm"); m.put(626, "asia"); m.put(627, "passgo-tivoli"); m.put(628, "qmqp"); m.put(629, "3com-amp3"); m.put(630, "rda"); m.put(631, "ipp"); m.put(632, "bmpp"); m.put(633, "servstat"); m.put(634, "ginad"); m.put(635, "rlzdbase"); m.put(636, "ldaps"); m.put(637, "lanserver"); m.put(638, "mcns-sec"); m.put(639, "msdp"); m.put(640, "entrust-sps"); m.put(641, "repcmd"); m.put(642, "esro-emsdp"); m.put(643, "sanity"); m.put(644, "dwr"); m.put(645, "pssc"); m.put(646, "ldp"); m.put(647, "dhcp-failover"); m.put(648, "rrp"); m.put(649, "cadview-3d"); m.put(650, "obex"); m.put(651, "ieee-mms"); m.put(652, "hello-port"); m.put(653, "repscmd"); m.put(654, "aodv"); m.put(655, "tinc"); m.put(656, "spmp"); m.put(657, "rmc"); m.put(658, "tenfold"); m.put(660, "mac-srvr-admin"); m.put(661, "hap"); m.put(662, "pftp"); m.put(663, "purenoise"); m.put(664, "oob-ws-https"); m.put(665, "sun-dr"); m.put(666, "mdqs"); m.put(667, "disclose"); m.put(668, "mecomm"); m.put(669, "meregister"); m.put(670, "vacdsm-sws"); m.put(671, "vacdsm-app"); m.put(672, "vpps-qua"); m.put(673, "cimplex"); m.put(674, "acap"); m.put(675, "dctp"); m.put(676, "vpps-via"); m.put(677, "vpp"); m.put(678, "ggf-ncp"); m.put(679, "mrm"); m.put(680, "entrust-aaas"); m.put(681, "entrust-aams"); m.put(682, "xfr"); m.put(683, "corba-iiop"); m.put(684, "corba-iiop-ssl"); m.put(685, "mdc-portmapper"); m.put(686, "hcp-wismar"); m.put(687, "asipregistry"); m.put(688, "realm-rusd"); m.put(689, "nmap"); m.put(690, "vatp"); m.put(691, "msexch-routing"); m.put(692, "hyperwave-isp"); m.put(693, "connendp"); m.put(694, "ha-cluster"); m.put(695, "ieee-mms-ssl"); m.put(696, "rushd"); m.put(697, "uuidgen"); m.put(698, "olsr"); m.put(699, "accessnetwork"); m.put(700, "epp"); m.put(701, "lmp"); m.put(702, "iris-beep"); m.put(704, "elcsd"); m.put(705, "agentx"); m.put(706, "silc"); m.put(707, "borland-dsj"); m.put(709, "entrust-kmsh"); m.put(710, "entrust-ash"); m.put(711, "cisco-tdp"); m.put(712, "tbrpf"); m.put(713, "iris-xpc"); m.put(714, "iris-xpcs"); m.put(715, "iris-lwz"); m.put(716, "pana"); m.put(729, "netviewdm1"); m.put(730, "netviewdm2"); m.put(731, "netviewdm3"); m.put(741, "netgw"); m.put(742, "netrcs"); m.put(744, "flexlm"); m.put(747, "fujitsu-dev"); m.put(748, "ris-cm"); m.put(749, "kerberos-adm"); m.put(750, "rfile"); m.put(751, "pump"); m.put(752, "qrh"); m.put(753, "rrh"); m.put(754, "tell"); m.put(758, "nlogin"); m.put(759, "con"); m.put(760, "ns"); m.put(761, "rxe"); m.put(762, "quotad"); m.put(763, "cycleserv"); m.put(764, "omserv"); m.put(765, "webster"); m.put(767, "phonebook"); m.put(769, "vid"); m.put(770, "cadlock"); m.put(771, "rtip"); m.put(772, "cycleserv2"); m.put(773, "submit"); m.put(774, "rpasswd"); m.put(775, "entomb"); m.put(776, "wpages"); m.put(777, "multiling-http"); m.put(780, "wpgs"); m.put(800, "mdbs-daemon"); m.put(801, "device"); m.put(802, "mbap-s"); m.put(810, "fcp-udp"); m.put(828, "itm-mcell-s"); m.put(829, "pkix-3-ca-ra"); m.put(830, "netconf-ssh"); m.put(831, "netconf-beep"); m.put(832, "netconfsoaphttp"); m.put(833, "netconfsoapbeep"); m.put(847, "dhcp-failover2"); m.put(848, "gdoi"); m.put(853, "domain-s"); m.put(860, "iscsi"); m.put(861, "owamp-control"); m.put(862, "twamp-control"); m.put(873, "rsync"); m.put(886, "iclcnet-locate"); m.put(887, "iclcnet-svinfo"); m.put(888, "accessbuilder"); m.put(900, "omginitialrefs"); m.put(901, "smpnameres"); m.put(902, "ideafarm-door"); m.put(903, "ideafarm-panic"); m.put(910, "kink"); m.put(911, "xact-backup"); m.put(912, "apex-mesh"); m.put(913, "apex-edge"); m.put(989, "ftps-data"); m.put(990, "ftps"); m.put(991, "nas"); m.put(992, "telnets"); m.put(993, "imaps"); m.put(995, "pop3s"); m.put(996, "vsinet"); m.put(997, "maitrd"); m.put(998, "busboy"); m.put(999, "garcon"); m.put(1000, "cadlock2"); m.put(1001, "webpush"); m.put(1010, "surf"); m.put(1021, "exp1"); m.put(1022, "exp2"); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Assistant/PrefManager.java ================================================ /** * This file is part of Privacy Friendly Password Generator. * Privacy Friendly Password Generator 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 any later version. * Privacy Friendly Password Generator 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 Privacy Friendly Password Generator. If not, see . */ package org.secuso.privacyfriendlynetmonitor.Assistant; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; /** * Class structure taken from tutorial at http://www.androidhive.info/2016/05/android-build-intro-slider-app/ * @author Karola Marky * @version 20170112 */ public class PrefManager { private static SharedPreferences pref; private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch"; public PrefManager(Context context) { pref = PreferenceManager.getDefaultSharedPreferences(context); } public static void setFirstTimeLaunch(boolean isFirstTime) { pref.edit().putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime).apply(); } public static boolean isFirstTimeLaunch() { return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Assistant/RunStore.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Assistant; import android.app.Activity; import android.content.Context; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.ServiceHandler; /** * Singleton-Like implementation which holds App-Context information and ServiceHandlers */ public class RunStore { private static Activity gContext; private static Context gAppContext; private static ServiceHandler gService; public static void setContext(Activity activity) { gContext = activity; } public static Context getContext() { if(gContext == null) return gAppContext; return gContext; } public static ServiceHandler getServiceHandler() { if (gService == null) { gService = new ServiceHandler(); } return gService; } public static void setAppContext(Context appContext) { RunStore.gAppContext = appContext; } public static Context getAppContext() { return gAppContext; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Assistant/TLType.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Assistant; /** * Enum indication transport layer protocol */ public enum TLType { tcp, tcp6, udp, udp6 } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/Assistant/ToolBox.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.Assistant; import android.app.ActivityManager; import android.content.Context; import android.util.Log; import org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.PassiveService; import java.io.File; import java.net.InetAddress; import java.net.NetworkInterface; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import java.util.Enumeration; /** * Class for all the litte helpers, used by more than one layer */ public class ToolBox { private static final char[] hexCode = "0123456789ABCDEF".toCharArray(); //Convert byte[] to HexString public static String printHexBinary(byte[] data) { StringBuilder r = new StringBuilder(data.length * 2); for (byte b : data) { r.append(hexCode[(b >> 4) & 0xF]); r.append(hexCode[(b & 0xF)]); } return r.toString(); } //Convert HexString to byte[] public static byte[] hexStringToByteArray(String s) { byte[] b = new byte[s.length() / 2]; for (int i = 0; i < b.length; i++) { int index = i * 2; int v = Integer.parseInt(s.substring(index, index + 2), 16); b[i] = (byte) v; } return b; } //Convert byte[] to wireshark import-string. public static String printExportHexString(byte[] data) { String hexString = printHexBinary(data); String export = "000000 "; for (int i = 0; i + 1 < hexString.length(); i += 2) { export += " " + hexString.substring(i, i + 2); } export += " ......"; return export; } //Returns active network interfaces public String getIfs(Context context) { //read from command: netcfg | grep UP String filePath = context.getFilesDir().getAbsolutePath() + File.separator + Const.FILE_IF_LIST; if (Const.IS_DEBUG) Log.d(Const.LOG_TAG, "Try to get active interfaces to" + filePath); ExecCom.user("rm " + filePath); ExecCom.user("netcfg | grep UP -> " + filePath); String result = ExecCom.userForResult("cat " + filePath); return result; } //Char to value private int hexToBin(char ch) { if ('0' <= ch && ch <= '9') return ch - '0'; if ('A' <= ch && ch <= 'F') return ch - 'A' + 10; if ('a' <= ch && ch <= 'f') return ch - 'a' + 10; return -1; } //Lookup local IP address public static InetAddress getLocalAddress() { try { for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress; } } } } catch (Exception e) { Log.e(Const.LOG_TAG, "Error while obtaining local address"); e.printStackTrace(); } return null; } //Test if service is active. public static boolean isAnalyzerServiceRunning() { ActivityManager manager = (ActivityManager) RunStore.getContext().getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (PassiveService.class.getName().equals(service.service.getClassName())) { return true; } } return false; } //Search for byte array in given byte array. public static int searchByteArray(byte[] input, byte[] searchedFor) { //convert byte[] to Byte[] Byte[] searchedForB = new Byte[searchedFor.length]; for (int x = 0; x < searchedFor.length; x++) { searchedForB[x] = searchedFor[x]; } int idx = -1; //search: Deque q = new ArrayDeque<>(input.length); for (int i = 0; i < input.length; i++) { if (q.size() == searchedForB.length) { //here I can check Byte[] cur = q.toArray(new Byte[]{}); if (Arrays.equals(cur, searchedForB)) { //found! idx = i - searchedForB.length; break; } else { //not found q.pop(); q.addLast(input[i]); } } else { q.addLast(input[i]); } } if (Const.IS_DEBUG && idx != -1) Log.d(Const.LOG_TAG, ToolBox.printHexBinary(searchedFor) + " found at position " + idx); return idx; } //Convert a Java long to a four byte array public static byte[] longToFourBytes(long l) { ByteBuffer bb = ByteBuffer.allocate(8); byte[] b = new byte[4]; bb.putLong(l); bb.position(4); bb.get(b); return b; } //Convert a Java int to a two byte array public static byte[] intToTwoBytes(int i) { ByteBuffer bb = ByteBuffer.allocate(4); byte[] b = new byte[2]; bb.putInt(i); bb.position(2); bb.get(b); return b; } //Convert four bytes to a Java Long public static long fourBytesToLong(byte[] b) { ByteBuffer bb = ByteBuffer.allocate(8); bb.position(4); bb.put(b); bb.position(0); return bb.getLong(); } //Convert two bytes to a Java int public static int twoBytesToInt(byte[] b) { ByteBuffer bb = ByteBuffer.allocate(4); bb.position(2); bb.put(b); bb.position(0); return bb.getInt(); } //Reverse the order in a Byte array public static byte[] reverseByteArray(byte[] b) { byte[] b0 = new byte[b.length]; int j = 0; for (int i = b.length - 1; i >= 0; i--) { b0[j] = b[i]; j++; } return b0; } //ipv6 Hex to address String calculator //e.g.: B80D01200000000067452301EFCDAB89 -> 2001:0db8:0000:0000:0123:4567:89ab:cdef public static String hexToIp6(String hexaIP) { StringBuilder result = new StringBuilder(); for (int i = 0; i < hexaIP.length(); i = i + 8) { String word = hexaIP.substring(i, i + 8); for (int j = word.length() - 1; j >= 0; j = j - 2) { result.append(word.substring(j - 1, j + 1)); result.append((j == 5) ? ":" : "");//in the middle } result.append(":"); } return result.substring(0, result.length() - 1).toString(); } //ipv4 Hex to address String calculator //e.g.: 0100A8C0 -> 192.168.0.1*/ public static String hexToIp4(String hexa) { StringBuilder result = new StringBuilder(); //reverse Little to Big for (int i = hexa.length() - 1; i >= 0; i = i - 2) { String wtf = hexa.substring(i - 1, i + 1); result.append(Integer.parseInt(wtf, 16)); result.append("."); } //remove last "."; return result.substring(0, result.length() - 1).toString(); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/ConnectionAnalysis/Collector.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.Build; import android.preference.PreferenceManager; import android.util.Log; import org.secuso.privacyfriendlynetmonitor.Assistant.AsyncCertVal; import org.secuso.privacyfriendlynetmonitor.Assistant.AsyncDNS; import org.secuso.privacyfriendlynetmonitor.Assistant.Const; import org.secuso.privacyfriendlynetmonitor.Assistant.KnownPorts; import org.secuso.privacyfriendlynetmonitor.Assistant.RunStore; import org.secuso.privacyfriendlynetmonitor.Assistant.TLType; import org.secuso.privacyfriendlynetmonitor.Assistant.ToolBox; import org.secuso.privacyfriendlynetmonitor.BuildConfig; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntity; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntityDao; import org.secuso.privacyfriendlynetmonitor.R; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import de.bjoernr.ssllabs.ConsoleUtilities; /** * Collector class collects data from the services and processes it for usage with the UI. * It handles asynchronous calls to DNS and SSL-Labs services and holds run-time caches for * compiled information. */ public class Collector { //application caches private static HashMap> sCachePackage = new HashMap<>(); private static HashMap sCacheIcon = new HashMap<>(); private static HashMap sCacheLabel = new HashMap<>(); private static HashMap sCacheDNS = new HashMap<>(); //ReportDetail information public static Boolean isCertVal = false; public static HashMap> mCertValMap = new HashMap<>(); public static List sCertValList = new ArrayList<>(); public static ArrayList sDetailReportList = new ArrayList<>(); public static Report sDetailReport; //Data processing maps private static ArrayList sReportList = new ArrayList<>(); private static HashMap> mUidReportMap = new HashMap<>(); private static HashMap> mFilteredUidReportMap = new HashMap<>(); //Apps to scan/not scan private static List appsToIncludeInScan = new ArrayList(); private static List appsToExcludeFromScan = new ArrayList(); //UID Table private static HashMap knownUIDs = new HashMap<>(); //Pushed the newest available information as deep copy. public static HashMap> provideSimpleReports(ReportEntityDao reportEntityDao) { updateReports(reportEntityDao); mFilteredUidReportMap = filterReports(); mFilteredUidReportMap = sortMapByLabels(); return mFilteredUidReportMap; } //Sort the filtered report map by app labels and app type (system/third-party) private static LinkedHashMap> sortMapByLabels() { LinkedHashMap> sortedMap = new LinkedHashMap<>(); ArrayList> reportsApp = new ArrayList<>(); ArrayList> reportsSysApp = new ArrayList<>(); //Sort in sub lists by app-type (System/User) Set keys = mFilteredUidReportMap.keySet(); for (int key : keys) { ArrayList appReports = (ArrayList) mFilteredUidReportMap.get(key); if (appReports.get(0).uid > 10000) { reportsApp.add(appReports); } else { reportsSysApp.add(appReports); } } //sort the sub list and append to liked HashMap sortListByName(reportsApp); sortListByName(reportsSysApp); reportsApp.addAll(reportsSysApp); //Add to original filter map for (int i = 0; i < reportsApp.size(); i++) { sortedMap.put(reportsApp.get(i).get(0).uid, reportsApp.get(i)); } return sortedMap; } //Do da bubble sort! private static void sortListByName(ArrayList> list) { for (int j = list.size(); j > 1; j--) { for (int i = 0; i < j - 1; i++) { if (getLabel(list.get(i).get(0).uid).compareTo(getLabel(list.get(i + 1).get(0).uid)) > 0) { ArrayList tmpList = list.get(i); list.set(i, list.get(i + 1)); list.set(i + 1, tmpList); } } } } //Generate an overview List, with only one report per remote address per app private static HashMap> filterReports() { HashMap> filteredReportsByApp = new HashMap<>(); HashSet filterMap = new HashSet<>(); String address; ArrayList list; ArrayList filteredList; for (int key : mUidReportMap.keySet()) { filteredReportsByApp.put(key, new ArrayList()); list = (ArrayList) mUidReportMap.get(key); filteredList = (ArrayList) filteredReportsByApp.get(key); filterMap.clear(); for (int i = 0; i < list.size(); i++) { address = list.get(i).remoteAdd.getHostAddress(); if (!filterMap.contains(address)) { filteredList.add(list.get(i)); filterMap.add(address); } } } return filteredReportsByApp; } //gets momentual settings from pref manager static void updateSettings() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(RunStore.getContext()); Collector.isCertVal = prefs.getBoolean(Const.IS_CERTVAL, false); } // save reports to db public static void saveReports(ReportEntityDao reportEntityDao) { // Remove duplicates appsToIncludeInScan = new ArrayList(new LinkedHashSet(appsToIncludeInScan)); appsToExcludeFromScan = new ArrayList(new LinkedHashSet(appsToExcludeFromScan)); // add reports to db if (!sReportList.isEmpty()) { for (Report report : sReportList) { ReportEntity reportEntity = new ReportEntity(); String appName = getPackage(report.uid); // check for apps to append to db if (!appsToExcludeFromScan.contains(appName)) { if (appsToIncludeInScan.contains(appName)) { if (appName != null) { reportEntity.setAppName(appName); } else { reportEntity.setAppName("Unknown"); } String userID = "" + report.uid; reportEntity.setUserID(userID); String remoteAddr = ""; if (report.type == TLType.tcp6 || report.type == TLType.udp6) { remoteAddr = report.remoteAdd.getHostAddress() + " (IPv6)"; } else { remoteAddr = report.remoteAdd.getHostAddress(); } reportEntity.setRemoteAddress(remoteAddr); String remoteHex = ToolBox.printHexBinary(report.remoteAddHex); reportEntity.setRemoteHex(remoteHex); String remoteHost = ""; if (hasHostName(report.remoteAdd.getHostAddress())) { remoteHost = getDnsHostName(report.remoteAdd.getHostAddress()); } else { remoteHost = "name not resolved"; } reportEntity.setRemoteHost(remoteHost); String localAddress = ""; if (report.type == TLType.tcp6 || report.type == TLType.udp6) { localAddress = report.localAdd.getHostAddress() + " (IPv6)"; } else { localAddress = report.localAdd.getHostAddress(); } reportEntity.setLocalAddress(localAddress); String localHex = ToolBox.printHexBinary(report.localAddHex); reportEntity.setLocalHex(localHex); String servicePort = "" + report.remotePort; reportEntity.setServicePort(servicePort); String payloadProt = "" + KnownPorts.resolvePort(report.remotePort); reportEntity.setPayloadProtocol(payloadProt); String transportProtocol = "" + report.type; reportEntity.setTransportProtocol(transportProtocol); String lastSeen = report.timestamp.toString(); reportEntity.setTimeStamp(lastSeen); String localPort = "" + report.localPort; reportEntity.setLocalPort(localPort); String connectionInfo = KnownPorts.CompileConnectionInfo(report.remotePort, report.type); reportEntity.setConnectionInfo(connectionInfo); reportEntityDao.insertOrReplace(reportEntity); } } } } } //Sequence to collect reports from detector public static void updateReports(ReportEntityDao reportEntityDao) { //update reports pull(); //process reports (passive mode) fillPackageInformation(); //resolve remote hosts (in cache or permission.INTERNET required) new AsyncDNS().execute(""); //sorting sortReportsToMap(); //Generate ssl analyze requests if (isCertVal) { fillCertRequests(); } saveReports(reportEntityDao); } //Search for resolved hostnames and add them to the resolved list private static void fillCertRequests() { Set keySet = mFilteredUidReportMap.keySet(); ArrayList list; Report r; String ip; for (int i : keySet) { list = (ArrayList) mFilteredUidReportMap.get(i); for (int j = 0; j < list.size(); j++) { r = list.get(j); //Add to certificate validation, if port 443 (TLS), resolved hostname and not yet //analyzed ip = r.remoteAdd.getHostAddress(); if (KnownPorts.isTlsPort(r.remotePort) && hasHostName(ip) && !mCertValMap.containsKey(getDnsHostName(ip)) && !sCertValList.contains(getDnsHostName(ip))) { sCertValList.add(getDnsHostName(ip)); } } } } //Sorts the reports by app package name to a HashMap private static void sortReportsToMap() { mUidReportMap = new HashMap<>(); for (int i = 0; i < sReportList.size(); i++) { Report r = sReportList.get(i); if (!mUidReportMap.containsKey(r.uid)) { mUidReportMap.put(r.uid, new ArrayList()); } mUidReportMap.get(r.uid).add(r); } } // true if default public static boolean hasGrade(String hostname) { String grade = getMetric(hostname); switch (grade) { case "RESOLVING CERTIFICATE HOSTS": return false; case "PENDING": return false; default: return true; } } //pull records from detector and make a deep copy for frontend - usage private static void pull() { ArrayList reportList = new ArrayList<>(); Set keySet = Detector.sReportMap.keySet(); for (int i : keySet) { reportList.add(Detector.sReportMap.get(i)); } sReportList = deepCopyReportList(reportList); } //Make an async reverse DNS request public static void resolveHosts() { for (int i = 0; i < sReportList.size(); i++) { Report r = sReportList.get(i); if (!hasHostName(r.remoteAdd.getHostAddress())) { try { String hostName = r.remoteAdd.getHostName(); sCacheDNS.put(r.remoteAdd.getHostAddress(), hostName); if (Const.IS_DEBUG) { Log.d("ReverseDNS", "Reverse DNS for " + r.remoteAdd.getHostAddress() + hostName); } } catch (RuntimeException e) { if (Const.IS_DEBUG) { Log.e(Const.LOG_TAG, "Attempt to resolve host name failed"); e.printStackTrace(); } } } } } //Make an async request to get host information from sslLabs static void updateCertVal() { if (sCertValList.size() > 0) { new AsyncCertVal().execute(); } } // fill reports with app data from Package Information Cache private static void fillPackageInformation() { for (int i = 0; i < sReportList.size(); i++) { Report r = sReportList.get(i); if (!sCachePackage.containsKey(r.uid)) { updatePackageCache(); } if (sCachePackage.containsKey(r.uid) && sCachePackage.get(r.uid).size() == 1) { PackageInfo pi = sCachePackage.get(r.uid).get(0); r.appName = pi.applicationInfo.name; r.packageName = pi.packageName; } else if (sCachePackage.containsKey(r.uid) && sCachePackage.get(r.uid).size() > 1) { r.appName = "UID " + r.uid; r.appName = "app.unknown"; } else { r.appName = "Unknown App"; r.appName = "app.unknown"; } } } //Make a deep copy of the report list private static ArrayList deepCopyReportList(ArrayList reportList) { ArrayList cloneList = new ArrayList<>(); try { for (int i = 0; i < reportList.size(); i++) { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(reportList.get(i)); out.flush(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(byteOut.toByteArray())); cloneList.add(Report.class.cast(in.readObject())); } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return cloneList; } //Updates the PkgInfo hash map with new entries. private static void updatePackageCache() { sCachePackage = new HashMap<>(); if (Const.IS_DEBUG) { printAllPackages(); } ArrayList infoList = (ArrayList) getPackages(RunStore.getContext()); for (PackageInfo i : infoList) { if (i != null) { if (!sCachePackage.containsKey(i.applicationInfo.uid)) { sCachePackage.put(i.applicationInfo.uid, new ArrayList()); } sCachePackage.get(i.applicationInfo.uid).add(i); } } addSysPackage(); } //Generate a system user dummy for UID 0 private static void addSysPackage() { // Add root PackageInfo root = new PackageInfo(); root.packageName = "com.android.system"; root.versionCode = BuildConfig.VERSION_CODE; root.versionName = BuildConfig.VERSION_NAME; root.applicationInfo = new ApplicationInfo(); root.applicationInfo.name = "System"; root.applicationInfo.uid = 0; root.applicationInfo.icon = 0; if (!sCachePackage.containsKey(root.applicationInfo.uid)) { sCachePackage.put(root.applicationInfo.uid, new ArrayList()); } sCachePackage.get(root.applicationInfo.uid).add(root); } //Get a list with all currently installed packages private static List getPackages(Context context) { synchronized (context.getApplicationContext()) { PackageManager pm = context.getPackageManager(); return new ArrayList<>(pm.getInstalledPackages(0)); } } //debug print: Print all reachable active processes private static void printAllPackages() { ArrayList infoList = (ArrayList) getPackages(RunStore.getContext()); for (PackageInfo i : infoList) { Log.d(Const.LOG_TAG, i.packageName + " uid_" + i.applicationInfo.uid); } } //Provides app icon for activities public static Drawable getIcon(int uid) { try { if (!sCacheIcon.containsKey(uid)) { if (sCachePackage.containsKey(uid) && sCachePackage.get(uid).size() == 1) { sCacheIcon.put(uid, sCachePackage.get(uid).get(0).applicationInfo. loadIcon(RunStore.getContext().getPackageManager())); } else { return getDefaultIcon(); } } return sCacheIcon.get(uid); } catch (NullPointerException e) { Log.e(Const.LOG_TAG, "Could not load icon of: " + sCachePackage.get(uid).get(0).packageName); return getDefaultIcon(); } } // get default icon private static Drawable getDefaultIcon() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return getIconNew(android.R.drawable.sym_def_app_icon); } else { return getIconOld(android.R.drawable.sym_def_app_icon); } } @TargetApi(Build.VERSION_CODES.GINGERBREAD) private static Drawable getIconOld(int id) { return RunStore.getContext().getResources().getDrawable(id); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private static Drawable getIconNew(int id) { return RunStore.getContext().getDrawable(id); } //Provides App names for activities public static String getLabel(int uid) { if (!sCacheLabel.containsKey(uid)) { if (sCachePackage.containsKey(uid) && sCachePackage.get(uid).size() == 1) { sCacheLabel.put(uid, (String) sCachePackage.get(uid).get(0).applicationInfo. loadLabel(RunStore.getContext().getPackageManager())); } else if (sCachePackage.containsKey(uid) && sCachePackage.get(uid).size() > 1) { return "UID " + uid; } else { return RunStore.getContext().getString(R.string.unknown_app); } } return sCacheLabel.get(uid); } //Provides full app package name public static String getPackage(int uid) { if (sCachePackage.containsKey(uid) && sCachePackage.get(uid).size() == 1) { return sCachePackage.get(uid).get(0).packageName; } else { return RunStore.getContext().getString(R.string.unknown_package); } } //Provides resolved hostname if available public static String getDnsHostName(String hostAdd) { if (sCacheDNS.containsKey(hostAdd)) { return sCacheDNS.get(hostAdd); } else { return hostAdd; } } //Test if hostname of connection is resolved public static Boolean hasHostName(String hostAdd) { return sCacheDNS.containsKey(hostAdd); } //Get linked hostname from certificate information package (SSL Labs API) public static String getCertHost(String hostname) { if (mCertValMap.containsKey(hostname)) { Map map = mCertValMap.get(hostname); if (Const.IS_DEBUG) { Log.d(Const.LOG_TAG, ConsoleUtilities.mapToConsoleOutput(map)); } if (analyseReady(map)) { if (map.containsKey("host")) { return (String) map.get("host"); } else { return hostname; } } } return hostname; } //Get grade information of an resolved SSL Labs request public static String getMetric(String hostname) { String grade; if (mCertValMap.containsKey(hostname)) { Map map = mCertValMap.get(hostname); if (Const.IS_DEBUG) { Log.d(Const.LOG_TAG, ConsoleUtilities.mapToConsoleOutput(map)); } if (analyseReady(map)) { grade = readEndpoints(map); if (grade.equals("no_grade")) { return "no_grade"; } else if (grade.equals("Certificate not valid for domain name")) { handleInvalidDomainName(map); return "RESOLVING CERTIFICATE HOSTS"; } else if (grade.equals("no_endpoints")) { return "no_endpoints"; } else { return grade; } } else { return "PENDING"; } } else { return "PENDING"; } } //Read endpoint-date from a SSL Labs request private static String readEndpoints(Map map) { final String result; if (map.containsKey("endpoints")) { ArrayList endpointsList = (ArrayList) map.get("endpoints"); HashMap endpoints = (HashMap) endpointsList.get(0); if (endpoints.containsKey("grade")) { result = (String) endpoints.get("grade"); } else if (endpoints.containsKey("statusMessage")) { result = (String) endpoints.get("statusMessage"); } else { result = "no_status"; } } else { result = "no_endpoints"; } return result; } //Handle "Certificate not valid for domain name" Error (e.g. google services) private static void handleInvalidDomainName(Map map) { if (map.containsKey("certHostnames") && map.containsKey("host")) { ArrayList certNames = (ArrayList) map.get("certHostnames"); String oldHost = (String) map.get("host"); String certHost = (String) certNames.get(0); certHost = certHost.replace("*.", ""); if (mCertValMap.containsKey(certHost) && mCertValMap.containsKey(oldHost)) { mCertValMap.put(oldHost, mCertValMap.get(certHost)); if (sCertValList.contains(oldHost)) { sCertValList.remove(oldHost); } } else { if (!sCertValList.contains(certHost)) { sCertValList.add(certHost); } } } } // Update pending hostnames for certificate validation by SSL Labs API public static void updateCertHostHandler() { Set keySet = Collector.mCertValMap.keySet(); Map map; for (String key : keySet) { map = (HashMap) Collector.mCertValMap.get(key); if (map.containsKey("host")) { String certHost = (String) map.get("host"); if (!key.equals(map.get(key)) && !Collector.analyseReady(map)) { Collector.mCertValMap.put(key, Collector.mCertValMap.get(certHost)); } } } } //Checks if ssl analysis has been completed public static boolean analyseReady(Map map) { String status = (String) map.get("status"); return status != null && status.equals("READY"); } //provide a detail report of a connection public static void provideDetail(int uid, byte[] remoteAddHex) { ArrayList filterList = filterReportsByAdd(uid, remoteAddHex); sDetailReport = filterList.get(0); buildDetailStrings(filterList); } //filter a report list so that each remote ip is unique private static ArrayList filterReportsByAdd(int uid, byte[] remoteAddHex) { List reportList = mUidReportMap.get(uid); ArrayList filterList = new ArrayList<>(); for (int i = 0; i < reportList.size(); i++) { if (Arrays.equals(reportList.get(i).remoteAddHex, remoteAddHex)) { filterList.add(reportList.get(i)); } } return filterList; } //Build report detail information for ReportDetailActivity list adapter private static void buildDetailStrings(ArrayList filterList) { ArrayList l = new ArrayList<>(); Report r = filterList.get(0); try { PackageInfo info = sCachePackage.get(r.uid).get(0); //App info l.add(new String[]{"User ID", "" + r.uid}); l.add(new String[]{"App Version", "" + info.versionName}); if (r.uid > 10000) { l.add(new String[]{"Installed On", "" + new Date(info.firstInstallTime).toString()}); } else { l.add(new String[]{"Installed On", "System App"}); } l.add(new String[]{"", ""}); //Connection info if (r.type == TLType.tcp6 || r.type == TLType.udp6) { l.add(new String[]{"Remote Address", r.remoteAdd.getHostAddress() + "\n(IPv6 translated)"}); } else { l.add(new String[]{"Remote Address", r.remoteAdd.getHostAddress()}); } l.add(new String[]{"Remote HEX", ToolBox.printHexBinary(r.remoteAddHex)}); if (hasHostName(r.remoteAdd.getHostAddress())) { l.add(new String[]{"Remote Host", getDnsHostName(r.remoteAdd.getHostAddress())}); } else { l.add(new String[]{"Remote Host", "name not resolved"}); } if (r.type == TLType.tcp6 || r.type == TLType.udp6) { l.add(new String[]{"Local Address", r.localAdd.getHostAddress() + "\n(IPv6 translated)"}); } else { l.add(new String[]{"Local Address", r.localAdd.getHostAddress()}); } l.add(new String[]{"Local HEX", ToolBox.printHexBinary(r.localAddHex)}); l.add(new String[]{"", ""}); l.add(new String[]{"Service Port", "" + r.remotePort}); l.add(new String[]{"Payload Protocol", "" + KnownPorts.resolvePort(r.remotePort)}); l.add(new String[]{"Transport Protocol", "" + r.type}); l.add(new String[]{"Last Seen", r.timestamp.toString()}); l.add(new String[]{"", ""}); //List open sockets l.add(new String[]{"Simultaneous Connections", "" + filterList.size()}); for (int i = 0; i < filterList.size(); i++) { Report r2 = filterList.get(i); l.add(new String[]{"(" + (i + 1) + ")src port > dst port", r2.localPort + " > " + r2.remotePort}); l.add(new String[]{" last socket-state ", getTransportState(r.state)}); } l.add(new String[]{"", ""}); sDetailReportList = l; } catch (NullPointerException e) { } } //Resolves the socket state of an identified connection private static String getTransportState(byte[] state) { String status; String stateHex = ToolBox.printHexBinary(state); switch (stateHex) { case "01": status = "ESTABLISHED"; break; case "02": status = "SYN_SENT"; break; case "03": status = "SYN_RECV"; break; case "04": status = "FIN_WAIT1"; break; case "05": status = "FIN_WAIT2"; break; case "06": status = "TIME_WAIT"; break; case "07": status = "CLOSE"; break; case "08": status = "CLOSE_WAIT"; break; case "09": status = "LAST_ACK"; break; case "0A": status = "LISTEN"; break; case "0B": status = "CLOSING"; break; case "0C": status = "NEW_SYN_RECV"; break; default: status = "UNKNOWN"; break; } return status; } // get scan whitelist public static List getAppsToIncludeInScan() { return appsToIncludeInScan; } // add apps to scan whitelist public static void addAppToIncludeInScan(String appToInclude) { Collector.appsToIncludeInScan.add(appToInclude); } // delete an app from scan whitelist public static void deleteAppFromIncludeInScan(String appName) { Collector.appsToIncludeInScan.remove(appName); } // get scan blacklist public static List getAppsToExcludeFromScan() { return appsToExcludeFromScan; } // add app to scan blacklist public static void addAppToExcludeFromScan(String appToExclude) { Collector.appsToExcludeFromScan.add(appToExclude); } // delete app from scan blacklist public static void deleteAppToExcludeFromScan(String appToExclude) { Collector.appsToExcludeFromScan.remove(appToExclude); } // get known uids public static HashMap getKnownUIDs() { return knownUIDs; } // add know uids public static void addKnownUIDs(String key, String value) { Collector.knownUIDs.put(key, value); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/ConnectionAnalysis/Detector.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis; import android.content.SharedPreferences; import android.preference.PreferenceManager; import org.secuso.privacyfriendlynetmonitor.Assistant.Const; import org.secuso.privacyfriendlynetmonitor.Assistant.ExecCom; import org.secuso.privacyfriendlynetmonitor.Assistant.RunStore; import org.secuso.privacyfriendlynetmonitor.Assistant.TLType; import org.secuso.privacyfriendlynetmonitor.Assistant.ToolBox; import java.nio.ByteBuffer; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; /** * Detects active connections on the device and identifies port-uid-pid realation. Corresponding * Apps are identified. */ class Detector { //Members //Get commands for shell readin private static final String commandTcp = "cat /proc/net/tcp"; private static final String commandTcp6 = "cat /proc/net/tcp6"; private static final String commandUdp = "cat /proc/net/udp"; private static final String commandUdp6 = "cat /proc/net/udp6"; static HashMap sReportMap = new HashMap<>(); //Update the report HashMap with currently scanned connections static void updateReportMap() { updateOrAdd(getCurrentConnections()); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(RunStore.getAppContext()); boolean isLog = prefs.getBoolean(Const.IS_LOG, false); boolean isCertVal = prefs.getBoolean(Const.IS_CERTVAL, false); if (!isLog && !isCertVal) { removeOldReports(); } } //Update existing or add new reports private static void updateOrAdd(ArrayList reportList) { for (int i = 0; i < reportList.size(); i++) { //Key = source-Port int key = reportList.get(i).localPort; if (sReportMap.containsKey(key)) { Report r = sReportMap.get(key); r.touch(); r.state = reportList.get(i).state; } else { sReportMap.put(key, reportList.get(i)); } } } //Remove timed-out connection-reports private static void removeOldReports() { Timestamp thresh = new Timestamp(System.currentTimeMillis() - Const.REPORT_TTL_DEFAULT); HashSet keySet = new HashSet<>(sReportMap.keySet()); for (int key : keySet) { if (sReportMap.get(key).timestamp.compareTo(thresh) < 0) { sReportMap.remove(key); } } } // read the current connections off the designated files private static ArrayList getCurrentConnections() { ArrayList fullReportList = new ArrayList<>(); //generate full report of all tcp/udp connections fullReportList.addAll(parseNetOutput(ExecCom.userForResult(commandTcp), TLType.tcp)); fullReportList.addAll(parseNetOutput(ExecCom.userForResult(commandTcp6), TLType.tcp6)); fullReportList.addAll(parseNetOutput(ExecCom.userForResult(commandUdp), TLType.udp)); fullReportList.addAll(parseNetOutput(ExecCom.userForResult(commandUdp6), TLType.udp6)); return fullReportList; } //Parse output from /proc/net/tcp and udp files (ip4/6) private static List parseNetOutput(String readIn, TLType type) { String[] splitLines; LinkedList reportList = new LinkedList<>(); splitLines = readIn.split("\\n"); for (int i = 1; i < splitLines.length; i++) { splitLines[i] = splitLines[i].trim(); reportList.add(initReport(splitLines[i], type)); } return reportList; } //Initiate a reports from a read in line private static Report initReport(String splitLine, TLType type) { String splitTabs[]; while (splitLine.contains(" ")) { splitLine = splitLine.replace(" ", " "); } splitTabs = splitLine.split("\\s"); if (type == TLType.tcp || type == TLType.udp) { //Init IPv4 values return initReport4(splitTabs, type); } else { //Init IPv6 values return initReport6(splitTabs, type); } } //Init parsed data to IPv4 connection report private static Report initReport4(String[] splitTabs, TLType type) { int pos; pos = 0; //Allocating buffer for 4 Bytes add and 2 bytes port each + 4 bytes UID ByteBuffer bb = ByteBuffer.allocate(17); bb.position(0); //local address String hexStr = splitTabs[1].substring(pos, pos + 8); bb.put(ToolBox.hexStringToByteArray(hexStr)); //local port pos = splitTabs[1].indexOf(":"); hexStr = splitTabs[1].substring(pos + 1, pos + 5); bb.put(ToolBox.hexStringToByteArray(hexStr)); //remote address pos = 0; hexStr = splitTabs[2].substring(pos, pos + 8); bb.put(ToolBox.hexStringToByteArray(hexStr)); //local port pos = splitTabs[2].indexOf(":"); hexStr = splitTabs[2].substring(pos + 1, pos + 5); bb.put(ToolBox.hexStringToByteArray(hexStr)); //UID bb.putInt(Integer.parseInt(splitTabs[7])); //state bb.put(ToolBox.hexStringToByteArray(splitTabs[3])); return new Report(bb, type); } //Init parsed data to IPv6 connection report private static Report initReport6(String[] splitTabs, TLType type) { int pos; pos = 0; //Allocating buffer for 16 Bytes add and 2 bytes port each + 4 bytes UID ByteBuffer bb = ByteBuffer.allocate(41); bb.position(0); //local address String hexStr = splitTabs[1].substring(pos, pos + 32); bb.put(ToolBox.hexStringToByteArray(hexStr)); //local port pos = splitTabs[1].indexOf(":"); hexStr = splitTabs[1].substring(pos + 1, pos + 5); bb.put(ToolBox.hexStringToByteArray(hexStr)); //remote address pos = 0; hexStr = splitTabs[2].substring(pos, pos + 32); bb.put(ToolBox.hexStringToByteArray(hexStr)); //local port pos = splitTabs[2].indexOf(":"); hexStr = splitTabs[2].substring(pos + 1, pos + 5); bb.put(ToolBox.hexStringToByteArray(hexStr)); //UID bb.putInt(Integer.parseInt(splitTabs[7])); //state bb.put(ToolBox.hexStringToByteArray(splitTabs[3])); return new Report(bb, type); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/ConnectionAnalysis/PassiveService.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis; import android.annotation.TargetApi; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Binder; import android.os.Build; import android.os.IBinder; import androidx.core.app.NotificationCompat; import android.util.Log; import org.secuso.privacyfriendlynetmonitor.Activities.MainActivity; import org.secuso.privacyfriendlynetmonitor.Assistant.Const; import org.secuso.privacyfriendlynetmonitor.Assistant.KnownPorts; import org.secuso.privacyfriendlynetmonitor.Assistant.RunStore; import org.secuso.privacyfriendlynetmonitor.R; import static java.lang.Thread.sleep; /** * Report Analyzer Service. Identifies active connections on the device and invokes data * gathering and report compilation procedures. */ public class PassiveService extends Service { private static final int SERVICE_IDENTIFIER = 1; public static boolean mInterrupt; private Thread mThread; private final IBinder mBinder = new AnalyzerBinder(); private Bitmap mIcon; private static final String ID = "Netmonitoring"; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(getVersionString(R.string.app_name)) .setContentText(getVersionString(R.string.bg_desc)); private String getVersionString(int id) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return getStringNew(id); } else { return getStringOld(id); } } @TargetApi(Build.VERSION_CODES.GINGERBREAD) private static String getStringNew(int id) { return RunStore.getContext().getResources().getString(id); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private static String getStringOld(int id) { return RunStore.getContext().getString(id); } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel serviceChannel = new NotificationChannel( ID, "Service Notification Channel", NotificationManager.IMPORTANCE_DEFAULT ); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(serviceChannel); } } @Override public void onCreate() { mInterrupt = false; loadNotificationBitmaps(); showAppNotification(); //init reserved-ports KnownPorts.initPortMap(); } //Icons for notification manager. Must be converted to bitmaps. private void loadNotificationBitmaps() { mIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_drawer); } public void startThread() { Log.i(Const.LOG_TAG, "PassiveService - Thread started"); // Stop the previous session by interrupting the thread. if (mThread != null) { mThread.interrupt(); } //Report analyzer working thread mThread = new Thread(new Runnable() { @Override public void run() { try { while (!mInterrupt) { //detect connections Detector.updateReportMap(); //check certificate validation state when feature is active Collector.updateSettings(); if (Collector.isCertVal) { Collector.updateCertVal(); } //sleep sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } if (mInterrupt) mThread.interrupt(); stopSelf(); } }, "AnalyzerThreadRunnable"); //start the service mThread.start(); } //Call to stop service and notification private void interrupt() { mInterrupt = true; stopSelf(); } @Override public IBinder onBind(Intent intent) { startThread(); return mBinder; } @Override public boolean onUnbind(Intent intent) { interrupt(); return super.onUnbind(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { startThread(); return Service.START_STICKY; } @Override public void onDestroy() { interrupt(); super.onDestroy(); } @Override public void onTaskRemoved(Intent rootIntent) { stopSelf(); } //Class for Binder public class AnalyzerBinder extends Binder { PassiveService getService() { return PassiveService.this; } } //Check for new notification information. Currently inactive due to insignificance /*private void checkForNotifications(){ if(Evidence.newWarnings != mNotificationCount) { mNotificationCount = Evidence.newWarnings; if (mNotificationCount > 0) { showWarningNotification(); } else { showAppNotification(); } } }*/ //BG notification. Standard Android version. private void showAppNotification() { mBuilder.setSmallIcon(R.drawable.ic_notification); mBuilder.setLargeIcon(mIcon); Intent resultIntent = new Intent(this, MainActivity.class); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(MainActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); createNotificationChannel(); mBuilder.setContentIntent(resultPendingIntent); startForeground(SERVICE_IDENTIFIER, mBuilder.build()); } //Computes the need and severity of a notification. Currently unused. private void showWarningNotification() { //Set corresponding icon //if(Evidence.getMaxSeverity() > 2){ // mBuilder.setSmallIcon(R.mipmap.icon_warn_red); // mBuilder.setLargeIcon(mWarnRed); //} else { // mBuilder.setSmallIcon(R.mipmap.icon_warn_orange); // mBuilder.setLargeIcon(mWarnOrange); //} //mBuilder.setContentText(mNotificationCount + " new warnings encountered."); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(this, MainActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(MainActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); createNotificationChannel(); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // mId allows you to update the notification later on. mNotificationManager.notify(Const.LOG_TAG, 1, mBuilder.build()); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/ConnectionAnalysis/Report.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis; import android.graphics.drawable.Drawable; import android.util.Log; import org.secuso.privacyfriendlynetmonitor.Assistant.Const; import org.secuso.privacyfriendlynetmonitor.Assistant.TLType; import org.secuso.privacyfriendlynetmonitor.Assistant.ToolBox; import java.io.Serializable; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.sql.Timestamp; import static java.lang.Math.abs; /** * Information class for acquired connection data. Full report on available information from device. */ public class Report implements Serializable { //Constructor parses HEX-data from /proc/net/*type* scan Report(ByteBuffer bb, TLType type) { touch(); this.type = type; // Fill with bytebuffer data if (type == TLType.tcp || type == TLType.udp) { initIP4(bb); } else { initIP6(bb); } //Init InetAddresses try { if (type == TLType.tcp || type == TLType.udp) { localAdd = InetAddress.getByName( ToolBox.hexToIp4(ToolBox.printHexBinary(localAddHex))); remoteAdd = InetAddress.getByName( ToolBox.hexToIp4(ToolBox.printHexBinary(remoteAddHex))); } else { localAdd = InetAddress.getByName( ToolBox.hexToIp6(ToolBox.printHexBinary(localAddHex))); remoteAdd = InetAddress.getByName( ToolBox.hexToIp6(ToolBox.printHexBinary(remoteAddHex))); } } catch (UnknownHostException e) { e.printStackTrace(); } if (Const.IS_DEBUG) { Log.d(Const.LOG_TAG, "Report (" + type + "):" + localAdd.getHostAddress() + ":" + localPort + " " + remoteAdd.getHostAddress() + ":" + remotePort + " - UID: " + uid); } } //Members public TLType type; public Timestamp timestamp; public byte[] localAddHex; public InetAddress localAdd; public int localPort; public byte[] state; public byte[] remoteAddHex; public InetAddress remoteAdd; public int remotePort; public int pid; public int uid; public Drawable icon; public String appName; public String packageName; //Set current timestamp public void touch() { timestamp = new Timestamp(System.currentTimeMillis()); } // ----------------------- // Init Methods // ----------------------- //Fill report with Ip4 - tcp/udp connection data from bytebuffer readin private void initIP4(ByteBuffer bb) { bb.position(0); byte[] b = new byte[2]; localAddHex = new byte[4]; bb.get(localAddHex); bb.get(b); localPort = ToolBox.twoBytesToInt(b); remoteAddHex = new byte[4]; bb.get(remoteAddHex); bb.get(b); remotePort = ToolBox.twoBytesToInt(b); uid = abs(bb.getInt()); state = new byte[1]; bb.get(state); } //Fill report with Ip6 - tcp/udp connection data from bytebuffer readin private void initIP6(ByteBuffer bb) { bb.position(0); byte[] b = new byte[2]; localAddHex = new byte[16]; bb.get(localAddHex); bb.get(b); localPort = ToolBox.twoBytesToInt(b); remoteAddHex = new byte[16]; bb.get(remoteAddHex); bb.get(b); remotePort = ToolBox.twoBytesToInt(b); uid = abs((bb.getInt())); state = new byte[1]; bb.get(state); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/ConnectionAnalysis/ServiceHandler.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis; import android.app.ActivityManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.widget.Toast; import org.secuso.privacyfriendlynetmonitor.Assistant.RunStore; import org.secuso.privacyfriendlynetmonitor.R; /** * This class handles commands and access to the services of the app * Currently Handles Services: Passive Service */ public class ServiceHandler { private PassiveService mPassiveService; private boolean mIsBound; //Get information of running services public boolean isServiceRunning(Class serviceClass) { ActivityManager manager = (ActivityManager) RunStore.getAppContext().getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } private ServiceConnection mPassiveServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. mPassiveService = ((PassiveService.AnalyzerBinder) service).getService(); Toast.makeText(RunStore.getContext(), R.string.passive_service_start, Toast.LENGTH_SHORT).show(); } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mPassiveService = null; Toast.makeText(RunStore.getContext(), R.string.passive_service_stop, Toast.LENGTH_SHORT).show(); } }; //start the service manually public void startPassiveService() { // Establish a connection with the service. Intent intent = new Intent(RunStore.getAppContext(), PassiveService.class); RunStore.getContext().startService(intent); } //stop the passive service public void stopPassiveService() { if (isServiceRunning(PassiveService.class)) { RunStore.getContext().stopService(new Intent(RunStore.getAppContext(), PassiveService.class)); } } //Bind the passive service to the assigned context public void bindPassiveService(Context context) { Intent intent = new Intent(RunStore.getAppContext(), PassiveService.class); context.bindService(intent, mPassiveServiceConnection, Context.BIND_AUTO_CREATE); mIsBound = true; } //Unbind the passive service to app context public void unbindPassiveService(Context context) { if (mIsBound) { context.unbindService(mPassiveServiceConnection); mIsBound = false; } } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/DatabaseUtil/DBApp.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.DatabaseUtil; import android.app.Application; import android.content.SharedPreferences; import android.os.AsyncTask; import org.greenrobot.greendao.database.Database; import org.secuso.privacyfriendlynetmonitor.Assistant.RunStore; import java.util.Map; /** * Created by m4rc0 on 12.11.2017. * DB class to store all apps and track the connections of the app. Implemented with greenDao. */ public class DBApp extends Application { public static final boolean ENCRYPTED = false; private static DaoSession daoSession; private static DBApp mContext; private static final String dbVersion = "1"; private static SharedPreferences selectedAppsPreferences; private static SharedPreferences.Editor editor; @Override public void onCreate() { super.onCreate(); mContext = this; new DBAppAsyncTask().execute(""); RunStore.setAppContext(getApplicationContext()); selectedAppsPreferences = getSharedPreferences("DBINFO", 0); editor = selectedAppsPreferences.edit(); } public DaoSession getDaoSession() { return daoSession; } static class DBAppAsyncTask extends AsyncTask { @Override protected Object doInBackground(Object[] objects) { System.out.println("Starting Database Async Task"); DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(mContext, ENCRYPTED ? "reports-db-encrypted" : "reports-db"); Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb(); Map map = selectedAppsPreferences.getAll(); if (!map.isEmpty() && map.get("Version") != null && !map.get("Version").equals("")) { if (!map.get("Version").equals(dbVersion) && Integer.parseInt((String) map.get("Version")) < Integer.parseInt(dbVersion)) { helper.onUpgrade(db, Integer.parseInt((String) map.get("Version")), Integer.parseInt(dbVersion)); editor.putString("Version", dbVersion); editor.commit(); } } else { helper.onUpgrade(db, 0, Integer.parseInt(dbVersion)); editor.putString("Version", dbVersion); editor.commit(); } daoSession = new DaoMaster(db).newSession(); return ""; } } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/DatabaseUtil/GenerateReportEntities.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.DatabaseUtil; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Set; /** * Created by m4rc0 on 13.01.2018. * Class to generate dummy test values for the database. Can be started with the following call: * GenerateReportEntities.generateReportEntities(this, reportEntityDao); * e.g. in MainActivity.onCreate() */ public class GenerateReportEntities { public static void generateReportEntities(Context context, ReportEntityDao reportEntityDao) { System.out.println("Start with entity generation"); List appNames = new ArrayList<>(); List reportEntities = new ArrayList<>(); appNames.add("com.android.chrome"); appNames.add("com.android.vending"); appNames.add("com.google.android.youtube"); SharedPreferences selectedAppsPreferences = context.getSharedPreferences("SELECTEDAPPS", 0); SharedPreferences.Editor editor = selectedAppsPreferences.edit(); PackageManager packageManager = context.getPackageManager(); Set set = selectedAppsPreferences.getAll().keySet(); for (String appName : appNames) { if (!selectedAppsPreferences.contains(appName)) { editor.putString(appName, appName); editor.commit(); } } int count = 1; long before = System.currentTimeMillis(); for (int i = 0; i < 1; i++) { for (int year = 2018; year <= 2018; year++) { System.out.println("New year: " + year); for (int month = 1; month <= 1; month++) { System.out.println("New Month: " + month); for (int day = 1; day <= 30; day++) { System.out.println("New Day: " + day); for (int hour = 0; hour < 24; hour++) { for (String appName : appNames) { ReportEntity reportEntity = new ReportEntity(); PackageInfo packageInfo = null; try { packageInfo = packageManager.getPackageInfo(appName, 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } reportEntity.setUserID((new String()).valueOf(packageInfo.applicationInfo.uid)); reportEntity.setAppName(appName); reportEntity.setRemoteAddress(getRandomString()); reportEntity.setRemoteHex(getRandomString()); reportEntity.setRemoteHost(getRandomString()); reportEntity.setLocalAddress(getRandomString()); reportEntity.setLocalHex(getRandomString()); reportEntity.setServicePort(getRandomString()); reportEntity.setPayloadProtocol(getRandomString()); reportEntity.setTransportProtocol(getRandomString()); reportEntity.setLocalPort(getRandomString()); double random = Math.random(); if (random < 0.5) { reportEntity.setConnectionInfo("Encrypted()"); } else { reportEntity.setConnectionInfo("Unencrypted()"); } String monthString = ""; if (month < 10) { monthString = "0" + (new String()).valueOf(month); } else { monthString = (new String()).valueOf(month); } String dayString = ""; if (day < 10) { dayString = "0" + (new String()).valueOf(day); } else { dayString = (new String()).valueOf(day); } String hourString = ""; if (hour < 10) { hourString = "0" + (new String()).valueOf(hour); } else { hourString = (new String()).valueOf(hour); } String date = (new String()).valueOf(year) + "-" + monthString + "-" + dayString + " " + hourString + ":04:20.420"; reportEntity.setTimeStamp(date); reportEntityDao.insertOrReplace(reportEntity); count++; } } } } } } long after = System.currentTimeMillis(); System.out.println("Generation needed " + (after - before) / 1000 + " seconds, for the generation of " + (count - 1) + " reports"); } private static String getRandomString() { String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; StringBuilder stringBuilder = new StringBuilder(); Random rnd = new Random(); while (stringBuilder.length() < 18) { int index = (int) (rnd.nextFloat() * SALTCHARS.length()); stringBuilder.append(SALTCHARS.charAt(index)); } String randomString = stringBuilder.toString(); return randomString; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/DatabaseUtil/ReportEntity.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.DatabaseUtil; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Generated; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Index; import org.greenrobot.greendao.annotation.NotNull; /** * Created by m4rc0 on 08.11.2017. * Report entity to safe in database. Similar to regular report. Implemented with greenDao. */ @Entity( nameInDb = "REPORTS", indexes = { @Index(value = "id DESC", unique = true) }) public class ReportEntity { @Id(autoincrement = true) private Long id; @NotNull private String appName; @NotNull private String userID; @NotNull private String timeStamp; @NotNull private String remoteAddress; @NotNull private String remoteHex; @NotNull private String remoteHost; @NotNull private String localAddress; @NotNull private String localHex; @NotNull private String servicePort; @NotNull private String payloadProtocol; @NotNull private String transportProtocol; @NotNull private String localPort; @NotNull private String connectionInfo; @Generated(hash = 15093572) public ReportEntity(Long id, @NotNull String appName, @NotNull String userID, @NotNull String timeStamp, @NotNull String remoteAddress, @NotNull String remoteHex, @NotNull String remoteHost, @NotNull String localAddress, @NotNull String localHex, @NotNull String servicePort, @NotNull String payloadProtocol, @NotNull String transportProtocol, @NotNull String localPort, @NotNull String connectionInfo) { this.id = id; this.appName = appName; this.userID = userID; this.timeStamp = timeStamp; this.remoteAddress = remoteAddress; this.remoteHex = remoteHex; this.remoteHost = remoteHost; this.localAddress = localAddress; this.localHex = localHex; this.servicePort = servicePort; this.payloadProtocol = payloadProtocol; this.transportProtocol = transportProtocol; this.localPort = localPort; this.connectionInfo = connectionInfo; } @Generated(hash = 683167796) public ReportEntity() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getAppName() { return this.appName; } public void setAppName(String appName) { this.appName = appName; } public String getUserID() { return this.userID; } public void setUserID(String userID) { this.userID = userID; } public String getTimeStamp() { return this.timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } public String getRemoteAddress() { return this.remoteAddress; } public void setRemoteAddress(String remoteAddress) { this.remoteAddress = remoteAddress; } public String getRemoteHex() { return this.remoteHex; } public void setRemoteHex(String remoteHex) { this.remoteHex = remoteHex; } public String getRemoteHost() { return this.remoteHost; } public void setRemoteHost(String remoteHost) { this.remoteHost = remoteHost; } public String getLocalAddress() { return this.localAddress; } public void setLocalAddress(String localAddress) { this.localAddress = localAddress; } public String getLocalHex() { return this.localHex; } public void setLocalHex(String localHex) { this.localHex = localHex; } public String getServicePort() { return this.servicePort; } public void setServicePort(String servicePort) { this.servicePort = servicePort; } public String getPayloadProtocol() { return this.payloadProtocol; } public void setPayloadProtocol(String payloadProtocol) { this.payloadProtocol = payloadProtocol; } public String getTransportProtocol() { return this.transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } public String getLocalPort() { return this.localPort; } public void setLocalPort(String localPort) { this.localPort = localPort; } public String getConnectionInfo() { return this.connectionInfo; } public void setConnectionInfo(String connectionInfo) { this.connectionInfo = connectionInfo; } @Override public String toString() { return "ReportEntity{" + "id=" + id + ", appName='" + appName + '\'' + ", userID='" + userID + '\'' + ", timeStamp='" + timeStamp + '\'' + ", remoteAddress='" + remoteAddress + '\'' + ", remoteHex='" + remoteHex + '\'' + ", remoteHost='" + remoteHost + '\'' + ", localAddress='" + localAddress + '\'' + ", localHex='" + localHex + '\'' + ", servicePort='" + servicePort + '\'' + ", payloadProtocol='" + payloadProtocol + '\'' + ", transportProtocol='" + transportProtocol + '\'' + ", localPort='" + localPort + '\'' + ", connectionInfo='" + connectionInfo + '\'' + '}'; } public String toStringWithoutTimestamp() { return "" + id + appName + userID + remoteAddress + remoteHex + remoteHost + localAddress + localHex + servicePort + payloadProtocol + transportProtocol + localPort + connectionInfo; } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/fragment/Fragment_day.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.fragment; import android.content.pm.PackageManager; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.components.Description; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import org.secuso.privacyfriendlynetmonitor.Activities.Adapter.FragmentDayListAdapter; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DBApp; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DaoSession; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntity; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntityDao; import org.secuso.privacyfriendlynetmonitor.R; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by tobias on 04.01.18. * https://github.com/PhilJay/MPAndroidChart/wiki/Setting-Data * Fragment which represent one day. */ public class Fragment_day extends Fragment { // ReportEntity Table and ReportEntities List private static ReportEntityDao reportEntityDao; private static List reportEntities; private static List filtered_Entities = new ArrayList<>(); private static List entitiesString = new ArrayList<>(); private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); final View view = inflater.inflate(R.layout.fragment_charts, container, false); ScrollView scrollview = view.findViewById(R.id.scrollViewChart); scrollview.setSmoothScrollingEnabled(true); //Fill Icon, AppGroupTitle, AppName PackageManager packageManager = getActivity().getPackageManager(); TextView tx_appName = view.findViewById(R.id.historyGroupSubtitle); final String appName = getArguments().getString("AppName"); tx_appName.setText(appName); try { ImageView appIcon = (ImageView) view.findViewById(R.id.historyGroupIcon); String appGroupTitle = (String) packageManager.getApplicationLabel( packageManager.getApplicationInfo(appName, PackageManager.GET_META_DATA)); TextView tx_appGroupTitle = view.findViewById(R.id.historyGroupTitle); tx_appGroupTitle.setText(appGroupTitle); appIcon.setImageDrawable(packageManager.getApplicationIcon(appName)); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } //END Fill Icon, AppGroupTitle, AppName //Build the Barchart final BarChart chart = (BarChart) view.findViewById(R.id.chart); loadFilteredList(appName); //method to get all connection from the app "appName" fillChart(view, chart); //method to fill the chart with the filteredList fillRecyclerList(view, filtered_Entities); //method to show all connection //Listener for Value Selection chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { @Override public void onValueSelected(Entry e, Highlight h) { //Handling the current time in Hour SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date currentTime = null; try { currentTime = dateFormat.parse(dateFormat.format(new Date())); } catch (ParseException ex) { ex.printStackTrace(); } //End current time handling int currentHour = currentTime.getHours(); int shift = 23 - currentHour; //the shift that is needed to get the correct connections //extra cacheList to only show the reports to the selected value in the chart List cacheList = new ArrayList(); if (e.getY() != 0) { for (ReportEntity cacheEntity : filtered_Entities) { int cacheEntityHour = (getEntityHour(cacheEntity) + shift) % 24; if (cacheEntityHour == e.getX()) { if (h.getStackIndex() == 0 && cacheEntity.getConnectionInfo().contains("Unknown")) { cacheList.add(cacheEntity); } if (h.getStackIndex() == 1 && cacheEntity.getConnectionInfo().contains("Encrypted")) { cacheList.add(cacheEntity); } if (h.getStackIndex() == 2 && cacheEntity.getConnectionInfo().contains("Unencrypted")) { cacheList.add(cacheEntity); } } } fillRecyclerList(view, cacheList); //method to show conn. according to the value } } @Override public void onNothingSelected() { fillRecyclerList(view, filtered_Entities); } }); return view; } private void fillChart(View view, BarChart chart) { //Handling the current time in Hour SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date currentTime = null; try { currentTime = dateFormat.parse(dateFormat.format(new Date())); } catch (ParseException e) { e.printStackTrace(); } int currentHour = currentTime.getHours(); //Putting reportEntitites into a array for chart List entry = new ArrayList(); int[] last24hours_encrypted = new int[24]; int[] last24hours_unencrypted = new int[24]; int[] last24hours_unknown = new int[24]; for (ReportEntity reportEntity : filtered_Entities) { int hourEntity = getEntityHour(reportEntity); if (hourEntity == 24) { hourEntity = 0; } //Increase the field of the array of the entityHour if (reportEntity.getConnectionInfo().contains("Encrypted")) { last24hours_encrypted[hourEntity] = last24hours_encrypted[hourEntity] + 1; } else if (reportEntity.getConnectionInfo().contains("Unencrypted")) { last24hours_unencrypted[hourEntity] = last24hours_unencrypted[hourEntity] + 1; } else if (reportEntity.getConnectionInfo().contains("Unknown")) { last24hours_unknown[hourEntity] = last24hours_unknown[hourEntity] + 1; } } //adding data to chart int slide = 23 - currentHour; int[] cache24hours_encrypted = new int[24]; int[] cache24hours_unencrypted = new int[24]; int[] cache24hours_unknown = new int[24]; for (int i = 0; i < last24hours_encrypted.length; i++) { int xValueCache = (i + slide) % 24; cache24hours_encrypted[xValueCache] = last24hours_encrypted[i]; cache24hours_unencrypted[xValueCache] = last24hours_unencrypted[i]; cache24hours_unknown[xValueCache] = last24hours_unknown[i]; } //extra "for-loop" beause the chart has to be filled from "0" to...value for (int i = 0; i < cache24hours_encrypted.length; i++) { entry.add(new BarEntry(i, new float[]{cache24hours_unknown[i], cache24hours_encrypted[i], cache24hours_unencrypted[i]})); } BarDataSet barset = new BarDataSet(entry, Fragment_day.this.getResources().getString(R.string.hours)); barset.setStackLabels(new String[]{Fragment_day.this.getResources().getString(R.string.unknown), Fragment_day.this.getResources().getString(R.string.encrypted), Fragment_day.this.getResources().getString(R.string.unencrypted)}); barset.setColors(new int[]{ContextCompat.getColor(getContext(), R.color.text_dark), ContextCompat.getColor(getContext(), R.color.green), ContextCompat.getColor(getContext(), R.color.red)}); //X Achse Formatter-------------------------------------------------------- // the labels that should be drawn on the XAxis final String[] hours = new String[last24hours_encrypted.length]; for (int i = 0; i < hours.length; i++) { if (i == hours.length - 1) { hours[i] = currentHour + Fragment_day.this.getResources().getString(R.string.oclock); } else { hours[i] = "- " + Integer.toString(23 - i) + Fragment_day.this.getResources().getString(R.string.hr); } } IAxisValueFormatter formatter = new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return hours[(int) value]; } }; XAxis xAxis = chart.getXAxis(); xAxis.setGranularity(1f); // minimum axis-step (interval) is 1 xAxis.setValueFormatter(formatter); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //Y Achse Formatter---------------------------------------------------------- YAxis yAxis_left = chart.getAxisLeft(); yAxis_left.setAxisMinimum(0f); YAxis yAxis_right = chart.getAxisRight(); yAxis_right.setAxisMinimum(0f); BarData barData = new BarData(barset); barData.setBarWidth(0.5f); chart.setData(barData); chart.setFitBars(true); //Sets the desc label at the bottom to " " Description description = new Description(); description.setText(""); chart.setDescription(description); chart.invalidate(); } private void loadFilteredList(String appName) { filtered_Entities.clear(); entitiesString.clear(); // load DB DaoSession daoSession = ((DBApp) getActivity().getApplication()).getDaoSession(); reportEntityDao = daoSession.getReportEntityDao(); reportEntities = reportEntityDao.loadAll(); //END load DB boolean isIncluded = false; //variable to check if conn. is already included for (ReportEntity reportEntity : reportEntities) { //Only entities from the AppName if (reportEntity.getAppName().equals(appName)) { String stringWithoutTimeStamp = reportEntity.toStringWithoutTimestamp(); //search if it is included allready for (String s : entitiesString) { if (s.equals(stringWithoutTimeStamp)) { isIncluded = true; } } //if it is NOT included do.... if (isIncluded == false) { //Only entities 24 hours ago SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); try { Date currentTime = dateFormat.parse(dateFormat.format(new Date())); Calendar cal = Calendar.getInstance(); cal.setTime(currentTime); cal.add(Calendar.DATE, -1); //This is the date one day ago == 24 hours ago Date dateBefore1Days = cal.getTime(); String string_date = reportEntity.getTimeStamp(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // sdf.parse(string_date) --> this is the Entity date if (!sdf.parse(string_date).after(dateBefore1Days)) { } else { filtered_Entities.add(reportEntity); // add only that report from that app and 24hours ago entitiesString.add(stringWithoutTimeStamp); } } catch (ParseException e) { e.printStackTrace(); } } isIncluded = false; //reset to false } } } private void fillRecyclerList(View view, List reportEntityList) { mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view); mRecyclerView.setFocusable(false); mRecyclerView.setNestedScrollingEnabled(false); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(getContext()); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new FragmentDayListAdapter(reportEntityList, getContext()); mRecyclerView.setAdapter(mAdapter); } private int getEntityHour(ReportEntity reportEntity) { String string_timestamp = reportEntity.getTimeStamp(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date entity_date = null; try { entity_date = sdf.parse(string_timestamp); } catch (ParseException e) { e.printStackTrace(); } return entity_date.getHours(); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/fragment/Fragment_month.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.fragment; import android.content.pm.PackageManager; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.components.Description; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import org.secuso.privacyfriendlynetmonitor.Activities.Adapter.FragmentDayListAdapter; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DBApp; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DaoSession; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntity; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntityDao; import org.secuso.privacyfriendlynetmonitor.R; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by tobias on 04.01.18. * Fragment which represent one month. */ public class Fragment_month extends Fragment { // ReportEntity Table and ReportEntities List private static ReportEntityDao reportEntityDao; private static List reportEntities; private static List filtered_Entities = new ArrayList<>(); private static List entitiesString = new ArrayList<>(); private static Date dateBefore1month = null; private static Date currentDate = null; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); final View view = inflater.inflate(R.layout.fragment_charts, container, false); //Fill Icon, AppGroupTitle, AppName PackageManager packageManager = getActivity().getPackageManager(); TextView tx_appName = view.findViewById(R.id.historyGroupSubtitle); final String appName = getArguments().getString("AppName"); tx_appName.setText(appName); try { ImageView appIcon = (ImageView) view.findViewById(R.id.historyGroupIcon); String appGroupTitle = (String) packageManager.getApplicationLabel( packageManager.getApplicationInfo(appName, PackageManager.GET_META_DATA)); TextView tx_appGroupTitle = view.findViewById(R.id.historyGroupTitle); tx_appGroupTitle.setText(appGroupTitle); appIcon.setImageDrawable(packageManager.getApplicationIcon(appName)); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } //END Fill Icon, AppGroupTitle, AppName //calc dateBefore1week SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); try { currentDate = dateFormat.parse(dateFormat.format(new Date())); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(currentDate); cal.add(Calendar.DATE, -29); //This is the date 7 days ago == 1 month dateBefore1month = cal.getTime(); //Build the Barchart final BarChart chart = (BarChart) view.findViewById(R.id.chart); loadFilteredList(appName); //method to get all connection from the app "appName" fillChart(view, chart); //method to fill the chart with the filteredList fillRecyclerList(view, filtered_Entities); //method to show all connection //Listener for Value Selection chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { @Override public void onValueSelected(Entry e, Highlight h) { //extra cacheList to only show the reports to the selected value in the chart List cacheList = new ArrayList(); if (e.getY() != 0) { for (ReportEntity cacheEntity : filtered_Entities) { int daysBetween = getDaysBetween(dateBefore1month, getEntityDate(cacheEntity)); if (daysBetween == e.getX()) { if (h.getStackIndex() == 0 && cacheEntity.getConnectionInfo().contains("Unknown")) { cacheList.add(cacheEntity); } if (h.getStackIndex() == 1 && cacheEntity.getConnectionInfo().contains("Encrypted")) { cacheList.add(cacheEntity); } if (h.getStackIndex() == 2 && cacheEntity.getConnectionInfo().contains("Unencrypted")) { cacheList.add(cacheEntity); } } } fillRecyclerList(view, cacheList); //method to show conn. according to the value } } @Override public void onNothingSelected() { fillRecyclerList(view, filtered_Entities); } }); return view; } private void fillChart(View view, BarChart chart) { int currentDay = currentDate.getDate(); //Putting reportEntitites into a array for chart List entry = new ArrayList(); int[] lastMonth_encrypted = new int[30]; int[] lastMonth_unencrypted = new int[30]; int[] lastMonth_unknown = new int[30]; for (ReportEntity reportEntity : filtered_Entities) { int daysBetween = getDaysBetween(dateBefore1month, getEntityDate(reportEntity)); //Increase the field of the array of the entityDay if (reportEntity.getConnectionInfo().contains("Encrypted")) { lastMonth_encrypted[daysBetween] = lastMonth_encrypted[daysBetween] + 1; } else if (reportEntity.getConnectionInfo().contains("Unencrypted")) { lastMonth_unencrypted[daysBetween] = lastMonth_unencrypted[daysBetween] + 1; } else if (reportEntity.getConnectionInfo().contains("Unknown")) { lastMonth_unknown[daysBetween] = lastMonth_unknown[daysBetween] + 1; } } //adding data to chart for (int i = 0; i < lastMonth_encrypted.length; i++) { entry.add(new BarEntry(i, new float[]{lastMonth_unknown[i], lastMonth_encrypted[i], lastMonth_unencrypted[i]})); } BarDataSet barset = new BarDataSet(entry, Fragment_month.this.getResources().getString(R.string.days)); barset.setStackLabels(new String[]{Fragment_month.this.getResources().getString(R.string.unknown), Fragment_month.this.getResources().getString(R.string.encrypted), Fragment_month.this.getResources().getString(R.string.unencrypted)}); barset.setColors(new int[]{ContextCompat.getColor(getContext(), R.color.text_dark), ContextCompat.getColor(getContext(), R.color.green), ContextCompat.getColor(getContext(), R.color.red)}); //X Achse Formatter-------------------------------------------------------- // the labels that should be drawn on the XAxis final String[] days = new String[lastMonth_encrypted.length]; for (int i = 0; i < days.length; i++) { if (i == days.length - 1) { days[i] = currentDay + " ."; } else { days[i] = "- " + Integer.toString(29 - i) + Fragment_month.this.getResources().getString(R.string.d); } } IAxisValueFormatter formatter = new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return days[(int) value]; } }; XAxis xAxis = chart.getXAxis(); xAxis.setGranularity(1f); // minimum axis-step (interval) is 1 xAxis.setValueFormatter(formatter); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //Y Achse Formatter---------------------------------------------------------- YAxis yAxis_left = chart.getAxisLeft(); yAxis_left.setAxisMinimum(0f); YAxis yAxis_right = chart.getAxisRight(); yAxis_right.setAxisMinimum(0f); BarData barData = new BarData(barset); barData.setBarWidth(0.5f); chart.setData(barData); chart.setFitBars(true); //Sets the desc label at the bottom to " " Description description = new Description(); description.setText(""); chart.setDescription(description); chart.invalidate(); } private void loadFilteredList(String appName) { filtered_Entities.clear(); entitiesString.clear(); // load DB DaoSession daoSession = ((DBApp) getActivity().getApplication()).getDaoSession(); reportEntityDao = daoSession.getReportEntityDao(); reportEntities = reportEntityDao.loadAll(); //END load DB boolean isIncluded = false; //variable to check if conn. is already included for (ReportEntity reportEntity : reportEntities) { //Only entities from the AppName if (reportEntity.getAppName().equals(appName)) { String stringWithoutTimeStamp = reportEntity.toStringWithoutTimestamp(); //search if it is included allready for (String s : entitiesString) { if (s.equals(stringWithoutTimeStamp)) { isIncluded = true; } } //if it is NOT included do.... if (isIncluded == false) { //Only entities 24 hours ago String string_date = reportEntity.getTimeStamp(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // sdf.parse(string_date) --> this is the Entity date try { if (!sdf.parse(string_date).after(dateBefore1month)) { } else { filtered_Entities.add(reportEntity); // add only that report from that app and 24hours ago entitiesString.add(stringWithoutTimeStamp); } } catch (ParseException e) { e.printStackTrace(); } } isIncluded = false; //reset to false } } } private void fillRecyclerList(View view, List reportEntityList) { mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view); mRecyclerView.setFocusable(false); mRecyclerView.setNestedScrollingEnabled(false); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(getContext()); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new FragmentDayListAdapter(reportEntityList, getContext()); mRecyclerView.setAdapter(mAdapter); } private Date getEntityDate(ReportEntity reportEntity) { String string_timestamp = reportEntity.getTimeStamp(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date entity_date = null; try { entity_date = sdf.parse(string_timestamp); } catch (ParseException e) { e.printStackTrace(); } return entity_date; } //https://www.java-forum.org/thema/datum-differenz-in-tagen-berechen.41934/ static final long ONE_HOUR = 60 * 60 * 1000L; public int getDaysBetween(Date d1, Date d2) { return (int) ((d2.getTime() - d1.getTime() + ONE_HOUR) / (ONE_HOUR * 24)); } } ================================================ FILE: app/src/main/java/org/secuso/privacyfriendlynetmonitor/fragment/Fragment_week.java ================================================ /* Privacy Friendly Net Monitor (Net Monitor) - Copyright (2015 - 2017) Felix Tsala Schiller ################################################################### This file is part of Net Monitor. Net Monitor 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. Net Monitor 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 Net Monitor. If not, see . Diese Datei ist Teil von Net Monitor. Net Monitor ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. Net Monitor wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe . ################################################################### This app has been created in affiliation with SecUSo-Department of Technische Universität Darmstadt. The design is based on the Privacy Friendly Example App template by Karola Marky, Christopher Beckmann and Markus Hau (https://github.com/SecUSo/privacy-friendly-app-example). Privacy Friendly Net Monitor is based on TLSMetric by Felix Tsala Schiller https://bitbucket.org/schillef/tlsmetric/overview. */ package org.secuso.privacyfriendlynetmonitor.fragment; import android.content.pm.PackageManager; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.components.Description; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import org.secuso.privacyfriendlynetmonitor.Activities.Adapter.FragmentDayListAdapter; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DBApp; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.DaoSession; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntity; import org.secuso.privacyfriendlynetmonitor.DatabaseUtil.ReportEntityDao; import org.secuso.privacyfriendlynetmonitor.R; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by tobias on 04.01.18. * Fragment which represent one week. */ public class Fragment_week extends Fragment { // ReportEntity Table and ReportEntities List private static ReportEntityDao reportEntityDao; private static List reportEntities; private static List filtered_Entities = new ArrayList<>(); private static List entitiesString = new ArrayList<>(); private static Date dateBefore1week = null; private static Date currentDate = null; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); final View view = inflater.inflate(R.layout.fragment_charts, container, false); //Fill Icon, AppGroupTitle, AppName PackageManager packageManager = getActivity().getPackageManager(); TextView tx_appName = view.findViewById(R.id.historyGroupSubtitle); final String appName = getArguments().getString("AppName"); tx_appName.setText(appName); try { ImageView appIcon = (ImageView) view.findViewById(R.id.historyGroupIcon); String appGroupTitle = (String) packageManager.getApplicationLabel( packageManager.getApplicationInfo(appName, PackageManager.GET_META_DATA)); TextView tx_appGroupTitle = view.findViewById(R.id.historyGroupTitle); tx_appGroupTitle.setText(appGroupTitle); appIcon.setImageDrawable(packageManager.getApplicationIcon(appName)); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } //END Fill Icon, AppGroupTitle, AppName //calc dateBefore1week SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); try { currentDate = dateFormat.parse(dateFormat.format(new Date())); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(currentDate); cal.add(Calendar.DATE, -6); //This is the date 7 days ago == 1 week dateBefore1week = cal.getTime(); //Build the Barchart final BarChart chart = (BarChart) view.findViewById(R.id.chart); loadFilteredList(appName); //method to get all connection from the app "appName" fillChart(view, chart); //method to fill the chart with the filteredList fillRecyclerList(view, filtered_Entities); //method to show all connection //Listener for Value Selection chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { @Override public void onValueSelected(Entry e, Highlight h) { //Handling the current time in Hour int currentDay = currentDate.getDate(); int shift = currentDay - 6; //the shift that is needed to get the correct connections //extra cacheList to only show the reports to the selected value in the chart List cacheList = new ArrayList(); if (e.getY() != 0) { for (ReportEntity cacheEntity : filtered_Entities) { int daysBetween = getDaysBetween(dateBefore1week, getEntityDate(cacheEntity)); if (daysBetween == e.getX()) { if (h.getStackIndex() == 0 && cacheEntity.getConnectionInfo().contains("Unknown")) { cacheList.add(cacheEntity); } if (h.getStackIndex() == 1 && cacheEntity.getConnectionInfo().contains("Encrypted")) { cacheList.add(cacheEntity); } if (h.getStackIndex() == 2 && cacheEntity.getConnectionInfo().contains("Unencrypted")) { cacheList.add(cacheEntity); } } } fillRecyclerList(view, cacheList); //method to show conn. according to the value } } @Override public void onNothingSelected() { fillRecyclerList(view, filtered_Entities); } }); return view; } private void fillChart(View view, BarChart chart) { int currentDay = currentDate.getDate(); //Putting reportEntitites into a array for chart List entry = new ArrayList(); int[] lastWeek_encrypted = new int[7]; int[] lastWeek_unencrypted = new int[7]; int[] lastWeek_unknown = new int[7]; for (ReportEntity reportEntity : filtered_Entities) { int daysBetween = getDaysBetween(dateBefore1week, getEntityDate(reportEntity)); //Increase the field of the array of the entityDay if (reportEntity.getConnectionInfo().contains("Encrypted")) { lastWeek_encrypted[daysBetween] = lastWeek_encrypted[daysBetween] + 1; } else if (reportEntity.getConnectionInfo().contains("Unencrypted")) { lastWeek_unencrypted[daysBetween] = lastWeek_unencrypted[daysBetween] + 1; } else if (reportEntity.getConnectionInfo().contains("Unknown")) { lastWeek_unknown[daysBetween] = lastWeek_unknown[daysBetween] + 1; } } //adding data to chart for (int i = 0; i < lastWeek_encrypted.length; i++) { entry.add(new BarEntry(i, new float[]{lastWeek_unknown[i], lastWeek_encrypted[i], lastWeek_unencrypted[i]})); } BarDataSet barset = new BarDataSet(entry, Fragment_week.this.getResources().getString(R.string.days)); barset.setStackLabels(new String[]{Fragment_week.this.getResources().getString(R.string.unknown), Fragment_week.this.getResources().getString(R.string.encrypted), Fragment_week.this.getResources().getString(R.string.unencrypted)}); barset.setColors(new int[]{ContextCompat.getColor(getContext(), R.color.text_dark), ContextCompat.getColor(getContext(), R.color.green), ContextCompat.getColor(getContext(), R.color.red)}); //X Achse Formatter-------------------------------------------------------- // the labels that should be drawn on the XAxis final String[] days = new String[lastWeek_encrypted.length]; for (int i = 0; i < days.length; i++) { if (i == days.length - 1) { days[i] = currentDay + " ."; } else { days[i] = "- " + Integer.toString(6 - i) + Fragment_week.this.getResources().getString(R.string.d); } } IAxisValueFormatter formatter = new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return days[(int) value]; } }; XAxis xAxis = chart.getXAxis(); xAxis.setGranularity(1f); // minimum axis-step (interval) is 1 xAxis.setValueFormatter(formatter); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //Y Achse Formatter---------------------------------------------------------- YAxis yAxis_left = chart.getAxisLeft(); yAxis_left.setAxisMinimum(0f); YAxis yAxis_right = chart.getAxisRight(); yAxis_right.setAxisMinimum(0f); BarData barData = new BarData(barset); barData.setBarWidth(0.5f); chart.setData(barData); chart.setFitBars(true); //Sets the desc label at the bottom to " " Description description = new Description(); description.setText(""); chart.setDescription(description); chart.invalidate(); } private void loadFilteredList(String appName) { filtered_Entities.clear(); entitiesString.clear(); // load DB DaoSession daoSession = ((DBApp) getActivity().getApplication()).getDaoSession(); reportEntityDao = daoSession.getReportEntityDao(); reportEntities = reportEntityDao.loadAll(); //END load DB boolean isIncluded = false; //variable to check if conn. is already included for (ReportEntity reportEntity : reportEntities) { //Only entities from the AppName if (reportEntity.getAppName().equals(appName)) { String stringWithoutTimeStamp = reportEntity.toStringWithoutTimestamp(); //search if it is included allready for (String s : entitiesString) { if (s.equals(stringWithoutTimeStamp)) { isIncluded = true; } } //if it is NOT included do.... if (isIncluded == false) { //Only entities 24 hours ago String string_date = reportEntity.getTimeStamp(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // sdf.parse(string_date) --> this is the Entity date try { if (!sdf.parse(string_date).after(dateBefore1week)) { } else { filtered_Entities.add(reportEntity); // add only that report from that app and 24hours ago entitiesString.add(stringWithoutTimeStamp); } } catch (ParseException e) { e.printStackTrace(); } } isIncluded = false; //reset to false } } } private void fillRecyclerList(View view, List reportEntityList) { mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view); mRecyclerView.setFocusable(false); mRecyclerView.setNestedScrollingEnabled(false); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(getContext()); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new FragmentDayListAdapter(reportEntityList, getContext()); mRecyclerView.setAdapter(mAdapter); } private Date getEntityDate(ReportEntity reportEntity) { String string_timestamp = reportEntity.getTimeStamp(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date entity_date = null; try { entity_date = sdf.parse(string_timestamp); } catch (ParseException e) { e.printStackTrace(); } return entity_date; } //https://www.java-forum.org/thema/datum-differenz-in-tagen-berechen.41934/ static final long ONE_HOUR = 60 * 60 * 1000L; public int getDaysBetween(Date d1, Date d2) { return (int) ((d2.getTime() - d1.getTime() + ONE_HOUR) / (ONE_HOUR * 24)); } } ================================================ FILE: app/src/main/res/drawable/background_border.xml ================================================ ================================================ FILE: app/src/main/res/drawable/button_fullwidth.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_clear.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_delete.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_help.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_history.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_menu_info.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_play_arrow.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_refresh.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_search_white_24dp.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_settings.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_sort_white_24dp.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_stop.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_tutorial.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_tutorial_inverted.xml ================================================ ================================================ FILE: app/src/main/res/drawable/splash_screen.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_about.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_help.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_help_content.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_history.xml ================================================