Saturday, 4 May 2024

PlantUML: mix html and creole

You can mix creole and html togther.

mixHtmlCreole.txt

@startuml

skinparam NoteFontSize 8

scale 1.5

Client -> Server: Send message


note left of Client 
Client is responsible to send **Messages**
over <color:#FF0000><b><i>https protocol</i></b></color>
end note

@enduml

 Above snippet generate below diagram.



 

Previous                                                    Next                                                    Home

PlantUML: Creole headings

Example

= Extra Large heading
== Large heading
=== Medium heading
==== Small heading

heading.txt

@startuml

scale 1.5

Client -> Server: Send message


note left of Client 
= Extra Large heading
== Large heading
=== Medium heading
==== Small heading
end note

@enduml

Above snippet generate below diagram.




 

Previous                                                    Next                                                    Home

PlantUML: Creole horizontal lines

Following snippets draw horizontal lines.

----
====
____
....

 

horizontalLines.txt

@startuml

skinparam NoteFontSize 8

scale 1.5

Client -> Server: Send message


note left of Client 
----
Line1
====
Line 2
____
Line 3
....
Line4
end note

@enduml

Above snippet generate below diagram.


 

Previous                                                    Next                                                    Home

Identify users using device fingerprinting

 

Device fingerprinting

Device fingerprinting is a method used to identify and track devices based on their unique characteristics like operating system, screen resolutions, fonts, installed plugins, etc., When we combine these data points together, they will create an unique fingerprint for the device.

 

How device fingerprint helps?

Device fingerprinting plays a vital role in various areas.

 

1. Security:

Device fingerprinting serves to assist in the detection and prevention of fraudulent activities.

 

Example 1: if an individual attempts to access your bank account from an unfamiliar device, the bank could utilize device fingerprinting to assess its authenticity.

 

Example 2: an e-commerce platform may leverage device fingerprinting to flag suspicious transactions, such as attempted credit card fraud.

 

2. Targeted Advertising:

This is a common occurrence you're likely to encounter frequently. Advertisers utilize device fingerprinting to track user behaviour across various websites, and construct a detailed profiles of their interests. This enables them to deliver targeted ads that are more relevant to you.

 

3. Content Personalization:

Websites and applications use device fingerprinting to identify what content user likes, and to identify what content is relevant to you. For instance, a news website might utilize device fingerprinting to present news articles more aligned with your interests, using the data such as your location or browsing history.

 

4. Rights Management:

Device fingerprinting serves to enforce digital rights management (DRM) restrictions. For instance, a streaming service could utilize device fingerprinting to deter users from sharing their accounts.

 

Imagine you're subscribed to a streaming service like Netflix, which employs DRM to regulate content access. To discourage account sharing, the service imposes certain limitations.

 

Upon logging in to Netflix on your device (whether it's a laptop, phone, etc.), a unique identifier is generated for your device. This fingerprint is crafted from various specifics concerning your device's hardware and software, such as the operating system, browser version, installed fonts, screen resolution, and more. Netflix retains data regarding the devices you've logged in from, typically allowing a specific number of devices to be linked to your account. When attempting to access Netflix from a new device, the service compares its fingerprint to the authorized ones. If a match is found, signifying login from a registered device, Netflix grants access. However, if the fingerprint fails to match any authorized devices, Netflix may restrict access or prompt you to verify your identity. This precautionary measure prevents unauthorized use of your account on unregistered devices.

 

Let's build a simple device fingerprint program in JavaScript and Java.

 

We can use following system characterstics to calculate device fingerprint.

 

1. User-Agent Header: This header string identifies the web browser and its version information.  Whenever you visit a website, this information is typically sent automatically.

 

2. Screen Resolution: The width and height of your screen in pixels.

 

3. Color Depth: The number of bits used to represent colors on your display.  For instance, a higher color depth means your device can display a wider range of colors.

 

4. Installed Fonts: A list of fonts available on your device.  This can be unique depending on what fonts you have installed besides the default ones.

 

5. Timezone: The user's time zone setting.

 

6. System Language: The user's preferred language setting on their device.

 

7. WebGL Information: Details about the device's graphics card and its capabilities, obtained through the WebGL API.  This can reveal information about the graphics vendor, renderer, and available extensions.

 

8. Hardware Vendors: Information about the device's hardware manufacturers, like the graphics card vendor or motherboard manufacturer, can sometimes be gleaned.

 

deviceFingerPrint.html 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Device Fingerprint</title>
<style>
    body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 20px;
    }
    h1 {
        margin-bottom: 20px;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 20px;
    }
    th, td {
        padding: 10px;
        text-align: left;
        border-bottom: 1px solid #ddd;
    }
    th {
        background-color: #f2f2f2;
    }
    .digital-signature {
        margin-top: 20px;
        font-size: 18px;
    }
</style>
<script>
window.onload = function() {
    var fingerprintData = {
        "User-Agent": navigator.userAgent,
        "Screen Resolution": screen.width + "x" + screen.height,
        "Color Depth": screen.colorDepth,
        "Installed Fonts": getInstalledFonts(),
        "Timezone": getTimezone(),
        "System Language": navigator.language,
        "WebGL Information": getWebGLInfo(),
        "Hardware Vendors": getHardwareVendors()
    };

    displayFingerprintData(fingerprintData);
};

function displayFingerprintData(data) {
    var table = document.createElement("table");
    var tbody = table.createTBody();

    for (var key in data) {
        var row = tbody.insertRow();
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        cell1.textContent = key;
        cell2.textContent = data[key];
    }

    document.body.appendChild(table);

    calculateDigitalSignature(data).then(function(digitalSignature) {
        var signatureElement = document.createElement("div");
        signatureElement.classList.add("digital-signature");
        signatureElement.textContent = "Digital Signature: " + digitalSignature;
        document.body.appendChild(signatureElement);
    });
}

function calculateDigitalSignature(data) {
    var jsonString = JSON.stringify(data);
    return sha256(jsonString);
}

function sha256(input) {
    // Use the built-in Crypto API to compute SHA-256 hash
    var buffer = new TextEncoder("utf-8").encode(input);
    return crypto.subtle.digest("SHA-256", buffer).then(function(hash) {
        return hex(hash);
    });
}

function hex(buffer) {
    var hexCodes = [];
    var view = new DataView(buffer);
    for (var i = 0; i < view.byteLength; i += 4) {
        var value = view.getUint32(i);
        var stringValue = value.toString(16);
        var padding = '00000000';
        var paddedValue = (padding + stringValue).slice(-padding.length);
        hexCodes.push(paddedValue);
    }
    return hexCodes.join("");
}

function getInstalledFonts() {
    var fonts = [];
    var fontList = document.fonts;
    fontList.forEach(function(font) {
        fonts.push(font.family);
    });
    return fonts.join(", ");
}

function getTimezone() {
    return new Date().getTimezoneOffset();
}

function getWebGLInfo() {
    var canvas = document.createElement("canvas");
    var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
    if (!gl) {
        return "WebGL not supported";
    }
    var info = {
        vendor: gl.getParameter(gl.VENDOR),
        renderer: gl.getParameter(gl.RENDERER),
        extensions: gl.getSupportedExtensions()
    };
    return JSON.stringify(info);
}

function getHardwareVendors() {
    // You may need to use additional libraries or APIs to gather hardware vendor information.
    return "Not implemented";
}
</script>
</head>
<body>
<h1>Device Fingerprint</h1>
<p>This page collects data to create a device fingerprint:</p>
</body>
</html>

 


Similar application in Java.

 

DeviceFingerprint.java

package com.sample.app;

import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

public class DeviceFingerprint {

    public static void main(String[] args) throws NoSuchAlgorithmException {
        Map<String, String> fingerprintData = new HashMap<>();
        fingerprintData.put("User-Agent", System.getProperty("http.agent"));
        fingerprintData.put("Screen Resolution", getScreenResolution());
        fingerprintData.put("Color Depth", String.valueOf(getColorDepth()));
        fingerprintData.put("Installed Fonts", getInstalledFonts());
        fingerprintData.put("Timezone", getTimezone());
        fingerprintData.put("System Language", System.getProperty("user.language"));
        fingerprintData.put("WebGL Information", "Not implemented"); // Add logic to get WebGL info
        fingerprintData.put("Hardware Vendors", "Not implemented"); // Add logic to get hardware vendors

        System.out.println("Device Fingerprint Data:");
        fingerprintData.forEach((key, value) -> System.out.println(key + ": " + value));

        String digitalSignature = calculateDigitalSignature(fingerprintData);
        System.out.println("Digital Signature: " + digitalSignature);
    }

    private static String calculateDigitalSignature(Map<String, String> data) throws NoSuchAlgorithmException {
        StringBuilder jsonString = new StringBuilder();
        jsonString.append("{");
        data.forEach((key, value) -> jsonString.append("\"").append(key).append("\":\"").append(value).append("\","));
        jsonString.deleteCharAt(jsonString.length() - 1); // Remove the last comma
        jsonString.append("}");

        return sha256(jsonString.toString());
    }

    private static String sha256(String input) throws NoSuchAlgorithmException {
    	  MessageDigest digest = MessageDigest.getInstance("SHA-256");
    	  byte[] hashbytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));
    	  return bytesToHex(hashbytes);
    	}

    	private static String bytesToHex(byte[] bytes) {
    	  StringBuilder sb = new StringBuilder();
    	  for (byte b : bytes) {
    	    sb.append(String.format("%02x", b));
    	  }
    	  return sb.toString();
    	}

    private static String getScreenResolution() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        return screenSize.width + "x" + screenSize.height;
    }

    private static int getColorDepth() {
        return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getBitDepth();
    }

    private static String getInstalledFonts() {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontNames = ge.getAvailableFontFamilyNames();
        StringBuilder fontList = new StringBuilder();
        for (String fontName : fontNames) {
            fontList.append(fontName).append(", ");
        }
        return fontList.toString();
    }

    private static String getTimezone() {
        TimeZone timeZone = TimeZone.getDefault();
        return timeZone.getDisplayName(false, TimeZone.SHORT);
    }
}

References

https://dataprivacylab.org/projects/identifiability/paper1.pdf

 

 

                                                  System Design Questions

Quick Overview On Single Master And Multiple Slaves In Database World

In this post, Let's talk about how a single master and multiple slaves architectures helps to achieve redundancy and high availability to the databases.

 

Master Database: The master database is the primary node in the architecture. It handles all the write operations (INSERT, UPDATE, DELETE).

 

Slave Databases: The slave databases are replicas of the master database. They copy the data from the master and keep themselves synchronized with any changes made on the master. Slave databases handle read operations (SELECT) from applications.

 

In this way, we can distribute the read traffic among multiple slave nodes and reduce the load on master node.

 


 

As you see the above diagram, Application server do not contact the master or slave databases directly. There is a proxy layer, which is responsible to route all the WRITE operations to master database and all the READ operations to SLAVE databases. You can refer https://proxysql.com/ for more details.

 

 

What happen when a master went down?

If the master database goes down, one of the slaves can be promoted to become the new master, ensuring continuous availability of the database.

 

What if a slave went down?

Since there are multiple replica slave nodes, the READ traffic is still served.

 

Overall, a single master and multiple slaves architecture provides scalability, fault tolerance, and high availability for MySQL databases, making it a popular choice for many applications

 

 

References

https://proxysql.com/

https://learn.microsoft.com/en-us/azure/azure-sql/database/service-tiers-sql-database-vcore?view=azuresql


                                                  System Design Questions

Friday, 3 May 2024

Is redundancy and fail over are same?

Failover and redundancy are related concepts in computer systems, but they are not exactly the same.

Redundancy refers to the presence of duplicate components within a system, whether in hardware (such as multiple servers) or software (such as data backups). Redundancy acts as a safety net, providing backup resources in case a primary component fails.

 

Failover, on the other hand, is the process of automatically switching to a redundant component when the primary one fails. It's the mechanism that ensures the continuity of system operations despite the failure of a primary component.

 

In essence, redundancy provides the infrastructure necessary for failover to function effectively, but failover is the specific action taken when a failure occurs.

 

Example 1: Car and a spare tyre example.

Redundancy (Spare Tire): In the context of a car, redundancy would be having a spare tire in addition to the four tires already mounted on the vehicle. This spare tire serves as a backup or duplicate component in case one of the primary tires gets punctured or fails. Redundancy ensures that there's an extra tire available to maintain the functionality of the vehicle even in the event of a tire failure.

 

Failover (Using the Spare Tire): Failover, in the context of the car scenario, would be the process of switching to the spare tire when one of the primary tires gets punctured. When a tire punctures while driving, you pull over to the side of the road and initiate the failover process by replacing the punctured tire with the spare tire. This failover action ensures that the car can continue its journey despite the tire failure, maintaining operational continuity.

 

Example 2: Primary and secondary database servers.

Let me explain it with below example, where I have two database servers (one is primary and the other is secondary).

 


Redundancy: The database system consists of two servers - a primary and a secondary. Both servers are configured to hold the same data, ensuring data integrity and availability.

 

Failover: Failover is the process of automatically switching to a redundant component when the primary one fails. In this case, when the primary database server goes down, the system detects the failure and initiates failover. The secondary server is then promoted to the primary role, taking over the responsibilities of serving database requests. This failover process should be automatic and swift to minimize downtime and ensure uninterrupted service to the application server.

 

Example 3: Internet Service Providers (ISPs)

ISPs often implement redundancy and failover mechanisms in their network infrastructure. Redundancy may involve having multiple network paths or links between routers to ensure continuous connectivity. Failover occurs when one network path or link fails, and traffic is automatically rerouted through alternate paths to maintain internet connectivity for users.

 

                                                  System Design Questions

Monday, 29 April 2024

How to select only numeric column names in Pandas?

Step 1: Select numeric column names using ‘select_dtypes’ method.

numeric_column_names = df.select_dtypes(include=['float64', 'int64']).columns

 

Step 2: Extract the numeric columns data from dataframe

numeric_data = df[numeric_column_names]

 

Find the below working application.

 

select_only_numeric_columns.py

import pandas as pd

df = pd.DataFrame(
    {
       'a': [1, 2, 3, 4],
        'b': [True, False, True, True],
        'c': [1.23, 4.5, 6.7, 8],
        'd': ['a', 'e', 'i', 'o']
    }
)

numeric_column_names = df.select_dtypes(include=['float64', 'int64']).columns
numeric_data = df[numeric_column_names]

print(f'df : \n{df}')
print(f'\nnumeric_column_names : \n{numeric_column_names}')
print(f'\nnumeric_data : \n{numeric_data}')

 

Output

df : 
   a      b     c  d
0  1   True  1.23  a
1  2  False  4.50  e
2  3   True  6.70  i
3  4   True  8.00  o

numeric_column_names : 
Index(['a', 'c'], dtype='object')

numeric_data : 
   a     c
0  1  1.23
1  2  4.50
2  3  6.70
3  4  8.00

 

 

Previous                                                 Next                                                 Home