]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/ViewSslCertificateDialog.java
c236d3a86e78061a3a581ab2e012fd269de48afd
[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.Activity;
24 import android.app.AlertDialog;
25 import android.app.Dialog;
26 import android.app.DialogFragment;
27 import android.graphics.drawable.BitmapDrawable;
28 import android.graphics.drawable.Drawable;
29 import android.net.Uri;
30 import android.net.http.SslCertificate;
31 import android.os.AsyncTask;
32 import android.os.Bundle;
33 import android.text.SpannableStringBuilder;
34 import android.text.Spanned;
35 import android.text.style.ForegroundColorSpan;
36 import android.view.LayoutInflater;
37 import android.view.WindowManager;
38 import android.widget.TextView;
39
40 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
41 import com.stoutner.privacybrowser.R;
42
43 import java.lang.ref.WeakReference;
44 import java.net.InetAddress;
45 import java.net.UnknownHostException;
46 import java.text.DateFormat;
47 import java.util.Calendar;
48 import java.util.Date;
49
50 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
51 @SuppressLint("InflateParams")
52 public class ViewSslCertificateDialog extends DialogFragment {
53     public Dialog onCreateDialog(Bundle savedInstanceState) {
54         // Get the activity's layout inflater.
55         LayoutInflater layoutInflater   = getActivity().getLayoutInflater();
56
57         // Create a drawable version of the favorite icon.
58         Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), MainWebViewActivity.favoriteIconBitmap);
59
60         // Use a builder to create the alert dialog.
61         AlertDialog.Builder dialogBuilder;
62
63         // Set the style according to the theme.
64         if (MainWebViewActivity.darkTheme) {
65             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
66         } else {
67             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
68         }
69
70         // Set the icon.
71         dialogBuilder.setIcon(favoriteIconDrawable);
72
73         // Set a listener on the negative button.  Using `null` as the listener closes the dialog without doing anything else.
74         dialogBuilder.setNegativeButton(R.string.close, null);
75
76         // Check to see if the website is encrypted.
77         if (MainWebViewActivity.sslCertificate == null) {  // The website is not encrypted.
78             // Set the title.
79             dialogBuilder.setTitle(R.string.unencrypted_website);
80
81             // Set the Layout.  The parent view is `null` because it will be assigned by `AlertDialog`.
82             dialogBuilder.setView(layoutInflater.inflate(R.layout.unencrypted_website, null));
83
84             // Create an alert dialog from the alert dialog builder.
85             final AlertDialog alertDialog = dialogBuilder.create();
86
87             // Disable screenshots if not allowed.
88             if (!MainWebViewActivity.allowScreenshots) {
89                 // Remove the warning below that `getWindow()` might be null.
90                 assert alertDialog.getWindow() != null;
91
92                 // Disable screenshots.
93                 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
94             }
95
96             // `onCreateDialog` requires the return of an `AlertDialog`.
97             return alertDialog;
98
99         } else {  // Display the SSL certificate information
100             // Set the title.
101             dialogBuilder.setTitle(R.string.ssl_certificate);
102
103             // Set the layout.  The parent view is `null` because it will be assigned by `AlertDialog`.
104             dialogBuilder.setView(layoutInflater.inflate(R.layout.view_ssl_certificate, null));
105
106             // Create an alert dialog from the builder.
107             final AlertDialog alertDialog = dialogBuilder.create();
108
109             // Disable screenshots if not allowed.
110             if (!MainWebViewActivity.allowScreenshots) {
111                 // Remove the warning below that `getWindow()` might be null.
112                 assert alertDialog.getWindow() != null;
113
114                 // Disable screenshots.
115                 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
116             }
117
118             // The alert dialog must be shown before items in the layout can be modified.
119             alertDialog.show();
120
121             // Get handles for the text views.
122             TextView domainTextView = alertDialog.findViewById(R.id.domain);
123             TextView ipAddressesTextView = alertDialog.findViewById(R.id.ip_addresses);
124             TextView issuedToCNameTextView = alertDialog.findViewById(R.id.issued_to_cname);
125             TextView issuedToONameTextView = alertDialog.findViewById(R.id.issued_to_oname);
126             TextView issuedToUNameTextView = alertDialog.findViewById(R.id.issued_to_uname);
127             TextView issuedByCNameTextView = alertDialog.findViewById(R.id.issued_by_cname);
128             TextView issuedByONameTextView = alertDialog.findViewById(R.id.issued_by_oname);
129             TextView issuedByUNameTextView = alertDialog.findViewById(R.id.issued_by_uname);
130             TextView startDateTextView = alertDialog.findViewById(R.id.start_date);
131             TextView endDateTextView = alertDialog.findViewById(R.id.end_date);
132
133             // Setup the labels.
134             String domainLabel = getString(R.string.domain_label) + "  ";
135             String cNameLabel = getString(R.string.common_name) + "  ";
136             String oNameLabel = getString(R.string.organization) + "  ";
137             String uNameLabel = getString(R.string.organizational_unit) + "  ";
138             String startDateLabel = getString(R.string.start_date) + "  ";
139             String endDateLabel = getString(R.string.end_date) + "  ";
140
141             // Convert the formatted URL string to a URI.
142             Uri uri = Uri.parse(MainWebViewActivity.formattedUrlString);
143
144             // Extract the domain name from the URI.
145             String domainString = uri.getHost();
146
147             // Get the IP addresses.
148             new GetIpAddresses(getActivity(), alertDialog).execute(domainString);
149
150             // Get the SSL certificate.
151             SslCertificate sslCertificate = MainWebViewActivity.sslCertificate;
152
153             // Get the strings from the SSL certificate.
154             String issuedToCName = sslCertificate.getIssuedTo().getCName();
155             String issuedToOName = sslCertificate.getIssuedTo().getOName();
156             String issuedToUName = sslCertificate.getIssuedTo().getUName();
157             String issuedByCName = sslCertificate.getIssuedBy().getCName();
158             String issuedByOName = sslCertificate.getIssuedBy().getOName();
159             String issuedByUName = sslCertificate.getIssuedBy().getUName();
160             Date startDate = sslCertificate.getValidNotBeforeDate();
161             Date endDate = sslCertificate.getValidNotAfterDate();
162
163             // Create spannable string builders for each text view that needs multiple colors of text.
164             SpannableStringBuilder domainStringBuilder = new SpannableStringBuilder(domainLabel + domainString);
165             SpannableStringBuilder issuedToCNameStringBuilder = new SpannableStringBuilder(cNameLabel + issuedToCName);
166             SpannableStringBuilder issuedToONameStringBuilder = new SpannableStringBuilder(oNameLabel + issuedToOName);
167             SpannableStringBuilder issuedToUNameStringBuilder = new SpannableStringBuilder(uNameLabel + issuedToUName);
168             SpannableStringBuilder issuedByCNameStringBuilder = new SpannableStringBuilder(cNameLabel + issuedByCName);
169             SpannableStringBuilder issuedByONameStringBuilder = new SpannableStringBuilder(oNameLabel + issuedByOName);
170             SpannableStringBuilder issuedByUNameStringBuilder = new SpannableStringBuilder(uNameLabel + issuedByUName);
171             SpannableStringBuilder startDateStringBuilder = new SpannableStringBuilder(startDateLabel + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(startDate));
172             SpannableStringBuilder endDateStringBuilder = new SpannableStringBuilder(endDateLabel + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(endDate));
173
174             // Create a red foreground color span.  The deprecated `getColor` must be used until the minimum API >= 23.
175             @SuppressWarnings("deprecation") ForegroundColorSpan redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
176
177             // Create a blue foreground color span.
178             ForegroundColorSpan blueColorSpan;
179
180             // Set the blue color span according to the theme.  The deprecated `getColor()` must be used until the minimum API >= 23.
181             if (MainWebViewActivity.darkTheme) {
182                 //noinspection deprecation
183                 blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_400));
184             } else {
185                 //noinspection deprecation
186                 blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_700));
187             }
188
189             // Remove the incorrect lint error that `.equals` might produce a NullPointerException.
190             assert domainString != null;
191
192             // Formet the `domainString` and `issuedToCName` colors.
193             if (domainString.equals(issuedToCName)) {  // `domainString` and `issuedToCName` match.
194                 // Set the strings to be blue.
195                 domainStringBuilder.setSpan(blueColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
196                 issuedToCNameStringBuilder.setSpan(blueColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
197             } else if(issuedToCName.startsWith("*.")){  // `issuedToCName` begins with a wildcard.
198                 // Remove the initial `*.`.
199                 String baseCertificateDomain = issuedToCName.substring(2);
200
201                 // Setup a copy of `domainString` to test subdomains.
202                 String domainStringSubdomain = domainString;
203
204                 // Initialize `domainNamesMatch`.
205                 boolean domainNamesMatch = false;
206
207                 // Check all the subdomains in `domainStringSubdomain` against `baseCertificateDomain`.
208                 while (!domainNamesMatch && domainStringSubdomain.contains(".")) {  // Stop checking if we know that `domainNamesMatch` is `true` or if we run out of  `.`.
209                     // Test the `domainStringSubdomain` against `baseCertificateDomain`.
210                     if (domainStringSubdomain.equals(baseCertificateDomain)) {
211                         domainNamesMatch = true;
212                     }
213
214                     // Strip out the lowest subdomain of `certificateCommonNameSubdomain`.
215                     domainStringSubdomain = domainStringSubdomain.substring(domainStringSubdomain.indexOf(".") + 1);
216                 }
217
218                 // Format the domain and issued to Common Name according to `domainNamesMatch`.
219                 if (domainNamesMatch) {  // `domainString` is a subdomain of the wildcard `issuedToCNameString`.
220                     // Set the strings to be blue.
221                     domainStringBuilder.setSpan(blueColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
222                     issuedToCNameStringBuilder.setSpan(blueColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
223                 } else {  // `domainString` is not a subdomain of the wildcard `issuedToCNameString`.
224                     // Set the string to be red.
225                     domainStringBuilder.setSpan(redColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
226                     issuedToCNameStringBuilder.setSpan(redColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
227                 }
228             } else {  // The strings do not match and `issuedToCNameString` does not begin with a wildcard.
229                 // Set the strings to be red.
230                 domainStringBuilder.setSpan(redColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
231                 issuedToCNameStringBuilder.setSpan(redColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
232             }
233
234             // Set the issued to and issued by spans to display the certificate information in blue.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
235             issuedToONameStringBuilder.setSpan(blueColorSpan, oNameLabel.length(), issuedToONameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
236             issuedToUNameStringBuilder.setSpan(blueColorSpan, uNameLabel.length(), issuedToUNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
237             issuedByCNameStringBuilder.setSpan(blueColorSpan, cNameLabel.length(), issuedByCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
238             issuedByONameStringBuilder.setSpan(blueColorSpan, oNameLabel.length(), issuedByONameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
239             issuedByUNameStringBuilder.setSpan(blueColorSpan, uNameLabel.length(), issuedByUNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
240
241             Date currentDate = Calendar.getInstance().getTime();
242
243             //  Format the start date color.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
244             if (startDate.after(currentDate)) {  // The certificate start date is in the future.
245                 startDateStringBuilder.setSpan(redColorSpan, startDateLabel.length(), startDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
246             } else {  // The certificate start date is in the past.
247                 startDateStringBuilder.setSpan(blueColorSpan, startDateLabel.length(), startDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
248             }
249
250             // Format the end date color.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
251             if (endDate.before(currentDate)) {  // The certificate end date is in the past.
252                 endDateStringBuilder.setSpan(redColorSpan, endDateLabel.length(), endDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
253             } else {  // The certificate end date is in the future.
254                 endDateStringBuilder.setSpan(blueColorSpan, endDateLabel.length(), endDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
255             }
256
257             // Display the strings.
258             domainTextView.setText(domainStringBuilder);
259             ipAddressesTextView.setText(getString(R.string.ip_addresses));
260             issuedToCNameTextView.setText(issuedToCNameStringBuilder);
261             issuedToONameTextView.setText(issuedToONameStringBuilder);
262             issuedToUNameTextView.setText(issuedToUNameStringBuilder);
263             issuedByCNameTextView.setText(issuedByCNameStringBuilder);
264             issuedByONameTextView.setText(issuedByONameStringBuilder);
265             issuedByUNameTextView.setText(issuedByUNameStringBuilder);
266             startDateTextView.setText(startDateStringBuilder);
267             endDateTextView.setText(endDateStringBuilder);
268
269             // `onCreateDialog` requires the return of an `AlertDialog`.
270             return alertDialog;
271         }
272     }
273
274     // This must run asynchronously because it involves a network request.  `String` declares the parameters.  `Void` does not declare progress units.  `String` contains the results.
275     private static class GetIpAddresses extends AsyncTask<String, Void, SpannableStringBuilder> {
276         // The weak references are used to determine if the activity or the alert dialog have disappeared while the AsyncTask is running.
277         private WeakReference<Activity> activityWeakReference;
278         private WeakReference<AlertDialog> alertDialogWeakReference;
279
280         GetIpAddresses(Activity activity, AlertDialog alertDialog) {
281             // Populate the weak references.
282             activityWeakReference = new WeakReference<>(activity);
283             alertDialogWeakReference = new WeakReference<>(alertDialog);
284         }
285
286         @Override
287         protected SpannableStringBuilder doInBackground(String... domainName) {
288             // Get handles for the activity and the alert dialog.
289             Activity activity = activityWeakReference.get();
290             AlertDialog alertDialog = alertDialogWeakReference.get();
291
292             // Abort if the activity or the dialog is gone.
293             if ((activity == null) || (activity.isFinishing()) || (alertDialog == null)) {
294                 return new SpannableStringBuilder();
295             }
296
297             // Initialize an IP address string builder.
298             StringBuilder ipAddresses = new StringBuilder();
299
300             // Get an array with the IP addresses for the host.
301             try {
302                 // Get an array with all the IP addresses for the domain.
303                 InetAddress[] inetAddressesArray = InetAddress.getAllByName(domainName[0]);
304
305                 // Add each IP address to the string builder.
306                 for (InetAddress inetAddress : inetAddressesArray) {
307                     if (ipAddresses.length() == 0) {  // This is the first IP address.
308                         // Add the IP Address to the string builder.
309                         ipAddresses.append(inetAddress.getHostAddress());
310                     } else {  // This is not the first IP address.
311                         // Add a line break to the string builder first.
312                         ipAddresses.append("\n");
313
314                         // Add the IP address to the string builder.
315                         ipAddresses.append(inetAddress.getHostAddress());
316                     }
317                 }
318             } catch (UnknownHostException exception) {
319                 // Do nothing.
320             }
321
322             // Set the label.
323             String ipAddressesLabel = activity.getString(R.string.ip_addresses) + "  ";
324
325             // Create a spannable string builder.
326             SpannableStringBuilder ipAddressesStringBuilder = new SpannableStringBuilder(ipAddressesLabel + ipAddresses);
327
328             // Create a blue foreground color span.
329             ForegroundColorSpan blueColorSpan;
330
331             // Set the blue color span according to the theme.  The deprecated `getColor()` must be used until the minimum API >= 23.
332             if (MainWebViewActivity.darkTheme) {
333                 //noinspection deprecation
334                 blueColorSpan = new ForegroundColorSpan(activity.getResources().getColor(R.color.blue_400));
335             } else {
336                 //noinspection deprecation
337                 blueColorSpan = new ForegroundColorSpan(activity.getResources().getColor(R.color.blue_700));
338             }
339
340             // Set the string builder to display the certificate information in blue.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
341             ipAddressesStringBuilder.setSpan(blueColorSpan, ipAddressesLabel.length(), ipAddressesStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
342
343             // Return the formatted string.
344             return ipAddressesStringBuilder;
345         }
346
347         // `onPostExecute()` operates on the UI thread.
348         @Override
349         protected void onPostExecute(SpannableStringBuilder ipAddresses) {
350             // Get handles for the activity and the alert dialog.
351             Activity activity = activityWeakReference.get();
352             AlertDialog alertDialog = alertDialogWeakReference.get();
353
354             // Abort if the activity or the alert dialog is gone.
355             if ((activity == null) || (activity.isFinishing()) || (alertDialog == null)) {
356                 return;
357             }
358
359             // Get a handle for the IP addresses text view.
360             TextView ipAddressesTextView = alertDialog.findViewById(R.id.ip_addresses);
361
362             // Populate the IP addresses text view.
363             ipAddressesTextView.setText(ipAddresses);
364         }
365     }
366 }