{"id":13177,"date":"2017-09-18T15:31:34","date_gmt":"2017-09-18T13:31:34","guid":{"rendered":"https:\/\/touk.pl\/blog\/?p=13177"},"modified":"2022-08-02T15:29:15","modified_gmt":"2022-08-02T13:29:15","slug":"bypassing-kotlins-null-safety","status":"publish","type":"post","link":"https:\/\/touk.pl\/blog\/2017\/09\/18\/bypassing-kotlins-null-safety\/","title":{"rendered":"Bypassing Kotlin&#8217;s Null-Safety"},"content":{"rendered":"<p>In this short article, we will have a look at how we can bypass Kotlin\u2019s native null-safety with <em>sun.misc.Unsafe<\/em>, and see why it can be dangerous even if we are not messing up with it directly.<\/p>\n<h2 id=\"mythical-sun-misc-unsafe\">Mythical <em>sun.misc.Unsafe<\/em><\/h2>\n<p>The <em>sun.misc.Unsafe<\/em> class is an internal JVM tool for executing low-level operations like off-heap memory allocation, thread parking, <a href=\"https:\/\/en.wikipedia.org\/wiki\/Compare-and-swap\">CAS<\/a>, and much more.<\/p>\n<p>This class is like one of those scary computer game creatures that are there only to intimidate us, in theory, we can\u2019t get close because they are part of the environment, but it\u2019s often possible by exploiting glitches or holes.<\/p>\n<p>If we try to access the <em>Unsafe<\/em> instance, we encounter a private constructor and a static <em>getUnsafe()<\/em> method that raises a <em>SecurityException<\/em> practically every time we call it:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public final class Unsafe {\r\n    private static final Unsafe theUnsafe;\r\n    \/\/ ...\r\n\r\n    private Unsafe() {}\r\n\r\n    @CallerSensitive\r\n    public static Unsafe getUnsafe() {\r\n        Class var0 = Reflection.getCallerClass();\r\n        if (!VM.isSystemDomainLoader(var0.getClassLoader())) {\r\n            throw new SecurityException(\"Unsafe\");\r\n        } else {\r\n            return theUnsafe;\r\n        }\r\n    }\r\n}<\/pre>\n<p>\u00a0<\/p>\n<p>So, in theory, it\u2019s guarded by a strong encapsulation, and an exception being thrown on every <em>getUnsafe()<\/em> call\u2026 but we do have the Reflection mechanism, and we can easily bypass those:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">private fun getUnsafe(): Unsafe {\r\n    return Unsafe::class.java.getDeclaredField(\"theUnsafe\")\r\n            .apply { isAccessible = true }\r\n            .let { it.get(null) as Unsafe }\r\n}<\/pre>\n<h3 id=\"mighty-unsafe-allocateinstance\">Mighty <em>Unsafe.allocateInstance()<\/em><\/h3>\n<p>This method <strong>allocates an empty instance of a given class directly on the heap ignoring field initialization and constructors.<\/strong><\/p>\n<p>And this allows us, indeed, to effectively bypass Kotlin\u2019s safety checks:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-288 size-full\" src=\"http:\/\/4comprehension.com\/wp-content\/uploads\/2017\/09\/Screen-Shot-2017-09-05-at-22.20.50.png\" alt=\"\" width=\"1618\" height=\"312\" \/><\/p>\n<p>A cool thing to do on Friday\u2019s evening, but what about just not using <em>Unsafe<\/em> and staying (null)safe?<\/p>\n<h2 id=\"problem-unsafe-in-external-libraries\">Problem: <em>Unsafe<\/em> in External Libraries<\/h2>\n<p>The problem is that most Java libraries were written with Java in mind, <strong>where using <em>Unsafe<\/em> for certain scenarios is slightly less unsafe than it is e.g.,\u00a0for Kotlin.<\/strong><\/p>\n<p>This is especially the case with serialization\/deserialization libraries \u2013 one of such is <a href=\"https:\/\/github.com\/google\/gson\">Google\u2019s Gson<\/a> which internally uses <em>Unsafe<\/em> for instantiating objects in certain situations \u2013 which is totally acceptable for Java.<\/p>\n<p>If we start using it in Kotlin, we indeed might end up with an undesired\u00a0behaviour observed above:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">@Test\r\nfun unsafe_2() {\r\n    val foo = Gson().fromJson(\"{}\", Foo::class.java)\r\n\r\n    assertThat(foo.nonNullable).isNull()\r\n}<\/pre>\n<p>In this case, we simply need to perform checks manually after instantiation, which is not super problematic \u2013 what\u2019s problematic is the lack of consciousness that this happens, which can cost much.<\/p>\n<p>Are you sure the library you are using is not doing that internally?<\/p>\n<p>Code snippets <a href=\"https:\/\/github.com\/pivovarit\/articles\/tree\/master\/kotlin-null-nonsafety\">can be found on GitHub.<\/a><\/p>\n<h2 id=\"key-takeaways\">Key Takeaways<\/h2>\n<ul>\n<li>Kotlin\u2019s null-safety does not go beyond objects\u2019 initialization phase and is bypassable<\/li>\n<li>External libraries that use <em>Unsafe<\/em> internally can do that too \u2013 it\u2019s important to be aware of this<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"In this short article, we will have a look at how we can bypass Kotlin\u2019s native null-safety with&hellip;\n","protected":false},"author":68,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":{"0":"post-13177","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-development-design"},"_links":{"self":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/13177","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/users\/68"}],"replies":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/comments?post=13177"}],"version-history":[{"count":21,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/13177\/revisions"}],"predecessor-version":[{"id":14879,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/13177\/revisions\/14879"}],"wp:attachment":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/media?parent=13177"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/categories?post=13177"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/tags?post=13177"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}