]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/ViewSslCertificateDialog.java
a24dedd1021a15da9fb07508f12fbdcd9920ea00
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / ViewSslCertificateDialog.java
1 /*
2  * Copyright © 2016-2019 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
6  * Privacy Browser is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Privacy Browser is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package com.stoutner.privacybrowser.dialogs;
21
22 import android.annotation.SuppressLint;
23 import android.app.AlertDialog;
24 import android.app.Dialog;
25 import android.content.SharedPreferences;
26 import android.graphics.drawable.BitmapDrawable;
27 import android.graphics.drawable.Drawable;
28 import android.net.Uri;
29 import android.net.http.SslCertificate;
30 import android.os.Bundle;
31 import android.preference.PreferenceManager;
32 import android.text.SpannableStringBuilder;
33 import android.text.Spanned;
34 import android.text.style.ForegroundColorSpan;
35 import android.view.LayoutInflater;
36 import android.view.View;
37 import android.view.WindowManager;
38 import android.widget.TextView;
39
40 import androidx.annotation.NonNull;
41 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
42
43 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
44 import com.stoutner.privacybrowser.R;
45 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
46 import com.stoutner.privacybrowser.views.NestedScrollWebView;
47
48 import java.text.DateFormat;
49 import java.util.Calendar;
50 import java.util.Date;
51
52 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
53 @SuppressLint("InflateParams")
54 public class ViewSslCertificateDialog extends DialogFragment {
55     public static ViewSslCertificateDialog displayDialog(long webViewFragmentId) {
56         // Create an arguments bundle.
57         Bundle argumentsBundle = new Bundle();
58
59         // Store the WebView fragment ID in the bundle.
60         argumentsBundle.putLong("webview_fragment_id", webViewFragmentId);
61
62         // Create a new instance of the dialog.
63         ViewSslCertificateDialog viewSslCertificateDialog = new ViewSslCertificateDialog();
64
65         // Add the bundle to the dialog.
66         viewSslCertificateDialog.setArguments(argumentsBundle);
67
68         // Return the new dialog.
69         return viewSslCertificateDialog;
70     }
71
72     @NonNull
73     public Dialog onCreateDialog(Bundle savedInstanceState) {
74         // Remove the incorrect lint warning below that the activity might be null.
75         assert getActivity() != null;
76
77         // Get the activity's layout inflater.
78         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
79
80         // Get the arguments.
81         Bundle arguments = getArguments();
82
83         // Remove the incorrect lint warning below that `getArguments().getLong()` might be null.
84         assert arguments != null;
85
86         // Get the current position of this WebView fragment.
87         int webViewPosition = MainWebViewActivity.webViewPagerAdapter.getPositionForId(arguments.getLong("webview_fragment_id"));
88
89         // Get the WebView tab fragment.
90         WebViewTabFragment webViewTabFragment = MainWebViewActivity.webViewPagerAdapter.getPageFragment(webViewPosition);
91
92         // Get the fragment view.
93         View fragmentView = webViewTabFragment.getView();
94
95         // Remove the incorrect lint warning below that the fragment view might be null.
96         assert fragmentView != null;
97
98         // Get a handle for the current WebView.
99         NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
100
101         // Use a builder to create the alert dialog.
102         AlertDialog.Builder dialogBuilder;
103
104         // Get a handle for the shared preferences.
105         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
106
107         // Get the screenshot and theme preferences.
108         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
109         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
110
111         // Set the style according to the theme.
112         if (darkTheme) {
113             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
114         } else {
115             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
116         }
117
118         // Create a drawable version of the favorite icon.
119         Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), nestedScrollWebView.getFavoriteOrDefaultIcon());
120
121         // Set the icon.
122         dialogBuilder.setIcon(favoriteIconDrawable);
123
124         // Set a listener on the negative button.  Using `null` as the listener closes the dialog without doing anything else.
125         dialogBuilder.setNegativeButton(R.string.close, null);
126
127         // Get the SSL certificate.
128         SslCertificate sslCertificate = nestedScrollWebView.getCertificate();
129
130         // Check to see if the website is encrypted.
131         if (sslCertificate == null) {  // The website is not encrypted.
132             // Set the title.
133             dialogBuilder.setTitle(R.string.unencrypted_website);
134
135             // Set the Layout.  The parent view is `null` because it will be assigned by `AlertDialog`.
136             dialogBuilder.setView(layoutInflater.inflate(R.layout.unencrypted_website, null));
137
138             // Create an alert dialog from the alert dialog builder.
139             final AlertDialog alertDialog = dialogBuilder.create();
140
141             // Disable screenshots if not allowed.
142             if (!allowScreenshots) {
143                 // Remove the warning below that `getWindow()` might be null.
144                 assert alertDialog.getWindow() != null;
145
146                 // Disable screenshots.
147                 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
148             }
149
150             // `onCreateDialog` requires the return of an `AlertDialog`.
151             return alertDialog;
152
153         } else {  // Display the SSL certificate information
154             // Set the title.
155             dialogBuilder.setTitle(R.string.ssl_certificate);
156
157             // Set the layout.  The parent view is `null` because it will be assigned by `AlertDialog`.
158             dialogBuilder.setView(layoutInflater.inflate(R.layout.view_ssl_certificate, null));
159
160             // Create an alert dialog from the builder.
161             final AlertDialog alertDialog = dialogBuilder.create();
162
163             // Disable screenshots if not allowed.
164             if (!allowScreenshots) {
165                 // Remove the warning below that `getWindow()` might be null.
166                 assert alertDialog.getWindow() != null;
167
168                 // Disable screenshots.
169                 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
170             }
171
172             // The alert dialog must be shown before items in the layout can be modified.
173             alertDialog.show();
174
175             // Get handles for the text views.
176             TextView domainTextView = alertDialog.findViewById(R.id.domain);
177             TextView ipAddressesTextView = alertDialog.findViewById(R.id.ip_addresses);
178             TextView issuedToCNameTextView = alertDialog.findViewById(R.id.issued_to_cname);
179             TextView issuedToONameTextView = alertDialog.findViewById(R.id.issued_to_oname);
180             TextView issuedToUNameTextView = alertDialog.findViewById(R.id.issued_to_uname);
181             TextView issuedByCNameTextView = alertDialog.findViewById(R.id.issued_by_cname);
182             TextView issuedByONameTextView = alertDialog.findViewById(R.id.issued_by_oname);
183             TextView issuedByUNameTextView = alertDialog.findViewById(R.id.issued_by_uname);
184             TextView startDateTextView = alertDialog.findViewById(R.id.start_date);
185             TextView endDateTextView = alertDialog.findViewById(R.id.end_date);
186
187             // Setup the labels.
188             String domainLabel = getString(R.string.domain_label) + "  ";
189             String ipAddressesLabel = getString(R.string.ip_addresses) + "  ";
190             String cNameLabel = getString(R.string.common_name) + "  ";
191             String oNameLabel = getString(R.string.organization) + "  ";
192             String uNameLabel = getString(R.string.organizational_unit) + "  ";
193             String startDateLabel = getString(R.string.start_date) + "  ";
194             String endDateLabel = getString(R.string.end_date) + "  ";
195
196             // Convert the formatted URL string to a URI.
197             Uri uri = Uri.parse(nestedScrollWebView.getUrl());
198
199             // Extract the domain name from the URI.
200             String domainString = uri.getHost();
201
202             // Get the strings from the SSL certificate.
203             String issuedToCName = sslCertificate.getIssuedTo().getCName();
204             String issuedToOName = sslCertificate.getIssuedTo().getOName();
205             String issuedToUName = sslCertificate.getIssuedTo().getUName();
206             String issuedByCName = sslCertificate.getIssuedBy().getCName();
207             String issuedByOName = sslCertificate.getIssuedBy().getOName();
208             String issuedByUName = sslCertificate.getIssuedBy().getUName();
209             Date startDate = sslCertificate.getValidNotBeforeDate();
210             Date endDate = sslCertificate.getValidNotAfterDate();
211
212             // Create spannable string builders for each text view that needs multiple colors of text.
213             SpannableStringBuilder domainStringBuilder = new SpannableStringBuilder(domainLabel + domainString);
214             SpannableStringBuilder ipAddressesStringBuilder = new SpannableStringBuilder(ipAddressesLabel + nestedScrollWebView.getCurrentIpAddresses());
215             SpannableStringBuilder issuedToCNameStringBuilder = new SpannableStringBuilder(cNameLabel + issuedToCName);
216             SpannableStringBuilder issuedToONameStringBuilder = new SpannableStringBuilder(oNameLabel + issuedToOName);
217             SpannableStringBuilder issuedToUNameStringBuilder = new SpannableStringBuilder(uNameLabel + issuedToUName);
218             SpannableStringBuilder issuedByCNameStringBuilder = new SpannableStringBuilder(cNameLabel + issuedByCName);
219             SpannableStringBuilder issuedByONameStringBuilder = new SpannableStringBuilder(oNameLabel + issuedByOName);
220             SpannableStringBuilder issuedByUNameStringBuilder = new SpannableStringBuilder(uNameLabel + issuedByUName);
221             SpannableStringBuilder startDateStringBuilder = new SpannableStringBuilder(startDateLabel + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(startDate));
222             SpannableStringBuilder endDateStringBuilder = new SpannableStringBuilder(endDateLabel + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(endDate));
223
224             // Create a red foreground color span.  The deprecated `getColor` must be used until the minimum API >= 23.
225             @SuppressWarnings("deprecation") ForegroundColorSpan redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
226
227             // Create a blue foreground color span.
228             ForegroundColorSpan blueColorSpan;
229
230             // Set the blue color span according to the theme.  The deprecated `getColor()` must be used until the minimum API >= 23.
231             if (darkTheme) {
232                 //noinspection deprecation
233                 blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_400));
234             } else {
235                 //noinspection deprecation
236                 blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_700));
237             }
238
239             // Remove the incorrect lint error that `.equals` might produce a NullPointerException.
240             assert domainString != null;
241
242             // Formet the domain string and issued to CName colors.
243             if (domainString.equals(issuedToCName)) {  // `domainString` and `issuedToCName` match.
244                 // Set the strings to be blue.
245                 domainStringBuilder.setSpan(blueColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
246                 issuedToCNameStringBuilder.setSpan(blueColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
247             } else if(issuedToCName.startsWith("*.")){  // `issuedToCName` begins with a wildcard.
248                 // Remove the initial `*.`.
249                 String baseCertificateDomain = issuedToCName.substring(2);
250
251                 // Setup a copy of `domainString` to test subdomains.
252                 String domainStringSubdomain = domainString;
253
254                 // Initialize `domainNamesMatch`.
255                 boolean domainNamesMatch = false;
256
257                 // Check all the subdomains in `domainStringSubdomain` against `baseCertificateDomain`.
258                 while (!domainNamesMatch && domainStringSubdomain.contains(".")) {  // Stop checking if we know that `domainNamesMatch` is `true` or if we run out of  `.`.
259                     // Test the `domainStringSubdomain` against `baseCertificateDomain`.
260                     if (domainStringSubdomain.equals(baseCertificateDomain)) {
261                         domainNamesMatch = true;
262                     }
263
264                     // Strip out the lowest subdomain of `certificateCommonNameSubdomain`.
265                     domainStringSubdomain = domainStringSubdomain.substring(domainStringSubdomain.indexOf(".") + 1);
266                 }
267
268                 // Format the domain and issued to Common Name according to `domainNamesMatch`.
269                 if (domainNamesMatch) {  // `domainString` is a subdomain of the wildcard `issuedToCNameString`.
270                     // Set the strings to be blue.
271                     domainStringBuilder.setSpan(blueColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
272                     issuedToCNameStringBuilder.setSpan(blueColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
273                 } else {  // `domainString` is not a subdomain of the wildcard `issuedToCNameString`.
274                     // Set the string to be red.
275                     domainStringBuilder.setSpan(redColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
276                     issuedToCNameStringBuilder.setSpan(redColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
277                 }
278             } else {  // The strings do not match and `issuedToCNameString` does not begin with a wildcard.
279                 // Set the strings to be red.
280                 domainStringBuilder.setSpan(redColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
281                 issuedToCNameStringBuilder.setSpan(redColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
282             }
283
284             // Set the IP addresses, issued to, and issued by spans to display the certificate information in blue.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
285             ipAddressesStringBuilder.setSpan(blueColorSpan, ipAddressesLabel.length(), ipAddressesStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
286             issuedToONameStringBuilder.setSpan(blueColorSpan, oNameLabel.length(), issuedToONameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
287             issuedToUNameStringBuilder.setSpan(blueColorSpan, uNameLabel.length(), issuedToUNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
288             issuedByCNameStringBuilder.setSpan(blueColorSpan, cNameLabel.length(), issuedByCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
289             issuedByONameStringBuilder.setSpan(blueColorSpan, oNameLabel.length(), issuedByONameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
290             issuedByUNameStringBuilder.setSpan(blueColorSpan, uNameLabel.length(), issuedByUNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
291
292             // Get the current date.
293             Date currentDate = Calendar.getInstance().getTime();
294
295             //  Format the start date color.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
296             if (startDate.after(currentDate)) {  // The certificate start date is in the future.
297                 startDateStringBuilder.setSpan(redColorSpan, startDateLabel.length(), startDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
298             } else {  // The certificate start date is in the past.
299                 startDateStringBuilder.setSpan(blueColorSpan, startDateLabel.length(), startDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
300             }
301
302             // Format the end date color.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
303             if (endDate.before(currentDate)) {  // The certificate end date is in the past.
304                 endDateStringBuilder.setSpan(redColorSpan, endDateLabel.length(), endDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
305             } else {  // The certificate end date is in the future.
306                 endDateStringBuilder.setSpan(blueColorSpan, endDateLabel.length(), endDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
307             }
308
309             // Display the strings.
310             domainTextView.setText(domainStringBuilder);
311             ipAddressesTextView.setText(ipAddressesStringBuilder);
312             issuedToCNameTextView.setText(issuedToCNameStringBuilder);
313             issuedToONameTextView.setText(issuedToONameStringBuilder);
314             issuedToUNameTextView.setText(issuedToUNameStringBuilder);
315             issuedByCNameTextView.setText(issuedByCNameStringBuilder);
316             issuedByONameTextView.setText(issuedByONameStringBuilder);
317             issuedByUNameTextView.setText(issuedByUNameStringBuilder);
318             startDateTextView.setText(startDateStringBuilder);
319             endDateTextView.setText(endDateStringBuilder);
320
321             // `onCreateDialog` requires the return of an alert dialog.
322             return alertDialog;
323         }
324     }
325 }