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