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