Java ssl debug all

How to enable SSL debugging in Java JVM? Example

Dealing with SSL issues in Java web applications is no fun, especially when you have no debug or troubleshooting logs and all you see is an ugly ‘Page Cannot be displayed error message in your browser. Thankfully you can easily enable SSL to debug on your Application to start seeing verbose logs that will clearly show what happens during the SSL handshake process.

You can enable SSL debugging logs in your Application Server JVM config by adding the following JVM command line parameter and restart the Application Server:

Note that since it is a Java System Property ( used by JSSE – Java Secure Sockets Extension), it will work on any JEE ApplicationServer such as WebSphere, WebLogic, Jboss, Tomcat, etc.

This is also one of the reasons why every Java developer should know more about various JVM parameters, here is a handy list of the most useful JVM options for Java developers.

How to enable SSL debug logging in IBM WebSphere?

Depending on your WAS version, adding the above parameter is typically done by navigating to WAS Admin Console > Servers > Application Servers > YourServer > Process Management > Java Virtual Machine > Generic JVM arguments

The verbose logs will usually go to SystemOut.log

Note: If you are unable to update System Property via the java command line above for whatever reason, try OS level network packet monitoring tool first. Now, what exactly are they? If you are running on Unix/Linux, try ‘snoop/tcpdump’ . On windows, you are in luck – use Microsoft Network Monitor, a very powerful tool. You can also try Wireshark (ethereal) on Windows.

That’s all about how to enable SSL debugging in Java. This is one of the 10 essential JVM options I have suggested for the production Java system. You don’t appreciate the value of such a parameter until you have faced the situation and realized the gravity of the problem and how much this tiny, little, and slightly unknown JVM option can help you.

This is another reason, why I suggest you get yourself familiar with different JVM options now and then. A good understanding of JVM internals and JVM options is essential for any experienced Java programmer.

You can improve your knowledge by joining one of these best Java JVM internal courses for senior Java developers or reading any good book on Java profiling and performance like Java Performance The Definitive Guide by Scott Oaks.

Читайте также:  Python variable name convention

You can also see the most up-to-date Java Performance Companion by Charlie Hunt, which covers Java 8 enhancements and G1 garbage collector as well. Both are great books to make yourself familiar with tools, processes, and internal Java virtual machines.

How to enable SSL debugging in Java JVM?

All the best with your learning about Java and JVM options.

Other Java SSL Articles and Tutorials you may like

Thanks for reading this article so far. if you find this example useful please share it with your friends or colleagues.

Источник

ITech notes

При разработке и настройке защищённых ssl / tls соединений полезен режим отладки. В java для получения такой отладочной информации поможет параметр javax . net . debug . Далее в посте подробнее о возможностях и результатах.

Есть в java библиотека под названием JSSE — » Java Secure Socket Extension «, она же «Расширение java для безопасных сокетов», реализующая протоколы SSL и TLS для обеспечения безопасных соединений. Когда-то давно она была отдельной библиотекой, а с версии jdk 1 . 4 вошла в стандартный дистрибутив. Имено JSSE и содержит возможность трассировки своих операций в поток вывода, что будет полезным при отладке и поиске различных проблем (например, с ошибками рукопожатия или передачи данных, с низкой производительностью и пр.).

N . B . Несмотря на то, что JSSE уже много лет, и все эти годы возможность отладки в ней присутствует, в документации говорится, что эта возможность не является официально поддерживаемой функцией — » the debug utility is not an officially supported feature of JSSE «.

Какие же значения может принимать этот параметр? Для начала — значение, которое отобразит список доступных опций: -Djavax . net . debug = help . Старт приложения (проверено на jdk 1 . 6 . 0 u29 ) даёт следующий результат:

ERROR [STDERR] all turn on all debugging
ERROR [STDERR] ssl turn on ssl debugging

ERROR [STDERR] The following can be used with ssl:
ERROR [STDERR] record enable per-record tracing
ERROR [STDERR] handshake print each handshake message
ERROR [STDERR] keygen print key generation data
ERROR [STDERR] session print session activity
ERROR [STDERR] defaultctx print default SSL initialization
ERROR [STDERR] sslctx print SSLContext tracing
ERROR [STDERR] sessioncache print session cache tracing
ERROR [STDERR] keymanager print key manager tracing
ERROR [STDERR] trustmanager print trust manager tracing
ERROR [STDERR] pluggability print pluggability tracing

Читайте также:  Vs code html css плагины

ERROR [STDERR] handshake debugging can be widened with:
ERROR [STDERR] data hex dump of each handshake message
ERROR [STDERR] verbose verbose handshake message printing

ERROR [STDERR] record debugging can be widened with:
ERROR [STDERR] plaintext hex dump of record plaintext
ERROR [STDERR] packet print raw SSL/TLS packets

N . B . Если запустить с -Djavax . net . debug = help программу, которая вообще не использует ни одного класса из тех, действия которых утилита призвана логировать, то список опций не будет отображён. Т.е. если написать класс типа классического Hello world и при старте задать ему описываемый параметр, то результата не будет. А вот если в класс добавить, например, инициализацию SSLContext или что-то подобное из JSSE — будет.

Думаю, переводить и пояснять каждую из опций нет смысла. В целом, требования следующие. Параметр должен содержать значение all или ssl — любое из двух. При значении » ssl » логируется подробная информация по всему процессу установления соединения, проверки сертификатов, шифрованию, обмену и пр. При значении » all » к этому добавляются (насколько я могу судить) ещё и дампы — побайтное логирование всей передаваемой информации. У меня для jboss + slf4j + log4j наблюдается ещё такая фишка, как логирование каждого байта на отдельной строке, т.е. если шифрованное сообщение занимает, скажем, 200 байт, лог займёт более 200 новых строк. В итоге при » all » лог быстро разрастается до просто невообразимых размеров. Для сравнения, при обработке одного и того же сообщения между теми же сервером и клиентом с теми же сертификатами размер лога » ssl » составляет ~1490 строк, а » all » ~17900!

Разобраться в таком логе сложно, т.к. он содержит весьма специфичную информацию, для понимания которой желательно иметь как минимум представление о ssl / tls . Если таковое имеется либо есть потребность всё-таки разобраться, то весьма поможет в этом нелёгком деле статья Debugging SSL/TLS Connections, в которой на примере описывается последовательность обмена данными и то, как эта последовательность соотносится с данными лога. Честно, советую хотя бы раз попробовать разобраться — доставляет!

Если для локализации проблем требуется логировать не всё подряд, а конкретные действия и сообщения, то за » ssl » могут следовать уточняющие опции. Можно использовать одну или несколько опций. Разделители между опциями необязательны (т.е. можно и в одно слово писать), хотя для чтения удобно их разделять чем-нибудь, например, запятыми или двоеточиями (естественно, пробелами нельзя). Порядок опций не важен. Примеры:

Источник

Читайте также:  Java символ конца файла

Limit Java SSL Debug Logging

Limit Java SSL Debug Logging

  1. Java SSL Debug and Its Importance
  2. Limit Java SSL Debug Logging

Today, we will learn about Java SSL debug, its importance, various utilities and how to use one or multiple in a single command.

Java SSL Debug and Its Importance

Handling SSL (Secure Socket Layer) in Java web applications is not fun, particularly when you get an ugly page saying Page Cannot Be Displayed in your browser without troubleshooting or debugging logs.

These situations increase the importance of SSL that we can easily enable to debug our applications and start seeing verbose logs. These logs will guide us (the developers) about this error.

There are various debug utilities that we can use. The following is the one to enable all SSL debugging logs in our application server JVM (Java Virtual Machine).

Don’t forget to restart your application server after adding the following JVM command line parameter.

The problem is that the above command will turn on all the SSL debugging which may not be required in some scenarios.

So, how can we limit Java SSL debug logging? Let’s learn it below.

Limit Java SSL Debug Logging

Using the -Djavax.net.debug=ssl command will log a tremendous amount of logging and details for each SSL event on a server. How can we limit it as per our project requirements?

To resolve it, we need to specify a debug specifier (also known as a flag) separated by a colon ( : ) for which we need SSL to debug logging. For instance, we can log about handshake as follows.

-Djavax.net.debug=ssl:handshake 

Remember that we must specify the javax.net.debug property value, whether it is ssl or all , followed by a debug specifier (optional).

We can also use multiple debug specifiers and don’t have to have a separator in these options (debug specifiers), although having a separator ( : or , ) will increase readability. See the following example to understand clearly.

-Djavax.net.debug=ssl:handshake, record, session 

The above command can also use a colon ( : ) as a separator between multiple debug specifiers. Remember, it does not matter what separator we use; the order of debug specifiers is also not important.

You can use any of them as per your needs and project requirements.

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

Related Article — Java SSL

Источник

Оцените статью