teleren/devto huggingface dataset:
Everything about Malware
Tags: malware, cybersecurity, malicious, software
Published: 2024-01-21 17:19:49

**Malware,** short for malicious software, is a type of software that is designed to harm computer systems, networks, or devices. Malware can be used to steal sensitive information, damage data, or take control of a system. Let's dive into the complex world of malware:
 
**Types of Malware:**

✅ **Viruses:** Self-replicating programs that infect files and spread like a biological virus. Think of them as digital zombies, turning healthy files into their clones.
✅ **Worms:** Network-based malware that replicates and spreads across devices without needing a host file. Imagine them as digital worms burrowing through connected systems.
✅ **Trojan horses:** Disguised programs that appear harmless but deliver hidden payloads like spyware or data stealers. Picture them as digital wolves in sheep's clothing.
✅ **Spyware:** Hidden programs that monitor user activity and steal sensitive information like passwords or financial data. They're the digital peeping Toms of the online world.
✅ **Ransomware:** Malware that encrypts your files, demanding payment to unlock them. It's like a digital kidnapper holding your data hostage.
✅ **Adware:** Unwanted software that bombards you with advertisements, often intrusive and in-your-face. They're the digital spammers of the software world.
 
**How Malware Spreads:**
 
✅ **Clicking malicious links:** Phishing emails and infected websites are major culprits. Imagine them as digital bait traps.
✅ **Downloading infected files:** Pirated software, cracks, and suspicious attachments can be Trojan horses in disguise. Picture them as poisoned candy.
✅ **Exploiting software vulnerabilities:** Unpatched systems are sitting ducks for malware that takes advantage of security weaknesses. Think of them as unlocked doors inviting digital thieves.
 
**Impacts of Malware:**
 
✅ **Data loss and theft:** Personal information, financial data, and business secrets can be compromised.
System damage and corruption: Files can be corrupted, deleted, or locked, rendering systems unusable.
✅ **Performance degradation:** Malware can hog resources, slowing down your computer and making it sluggish.
✅ **Financial losses:** Ransomware attacks, data breaches, and system downtime can cost businesses and individuals dearly.

**Protecting Yourself from Malware:**

✅ **Use anti-virus and anti-malware software:** These programs act as digital bodyguards, detecting and blocking threats.
✅ **Keep your software updated:** Patching vulnerabilities closes the doors for malware to sneak in.
✅ **Be wary of suspicious links and attachments:** Don't click on things you don't trust.
✅ **Download software from reliable sources:** Avoid cracked software and dubious websites.
✅ **Back up your data regularly:** Having a backup can save you in case of a ransomware attack.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cfkcv6y998wwuw0jozpv.png)
What is Security Breach?
Tags: securitybreach, cybersecurity, security
Published: 2024-01-21 17:15:36

Any attack that results in someone gaining unauthorized access to devices, services, or networks is considered a **security breach**. Imagine a security breach as similar to a break-in where an intruder (attacker) successfully breaks into a building (a device, application, or network).

Security breaches come in different forms, including the following:

✅ **Social engineering attacks**

It is common to think about security breaches as exploiting some flaw or vulnerability in a technology service or piece of equipment. Likewise, you might believe that security breaches only happen because of vulnerabilities in technology. But that’s not the case. Attackers can use social engineering attacks to exploit or manipulate users into granting them unauthorized access to a system.

In social engineering, impersonation attacks happen when an unauthorized user (the attacker), aims to gain the trust of an authorized user by posing as a person of authority to access a system from some nefarious activity. For example, a cybercriminal might pretend to be a support engineer to trick a user into revealing their password to access an organization’s systems.

✅ **Browser attacks**

Whether on a desktop, laptop, or phone, browsers are an important access tool for the internet. Security vulnerabilities in a browser can have a significant impact because of their pervasiveness. For example, suppose a user is working on an important project with a looming deadline. They want to figure out how to solve a particular problem for their project. They find a website that they believe will provide a solution.

The website asks the user to make some changes to their browser settings so they can install an add-on. The user follows the instructions on the website. Unknown to them, the browser is now compromised. This is a browser modifier attack, one of many different types used by cybercriminals. An attacker can now use the browser to steal information, monitor user behavior, or compromise a device.

✅ **Password attacks**

**A password attack** is when someone attempts to use authentication for a password-protected account to gain unauthorized access to a device or system. Attackers often use software to speed up the process of cracking and guessing passwords. For example, suppose an attacker has somehow discovered someone's username for their work account.

The attacker then tries a vast number of possible password combinations to access the user’s account. The password only has to be correct once for the attacker to get access. This is known as a brute force attack and is one of many ways in which a cybercriminal can use password attacks.
Safe guarding Sensitive Data in ASP.NET Core with Secret Manager
Tags: dotnet, dotnetcore, aspnet, secutiry
Published: 2024-01-21 17:00:19

**Introduction:**
In the realm of ASP.NET Core development, the need to manage sensitive data, such as application secrets, is paramount. To address this concern, the Secret Manager tool provides a secure and convenient solution, enabling developers to store and access sensitive information during the development phase without compromising security. In this article, we will delve into the workings of the Secret Manager tool, its setup, and how to seamlessly integrate it into your ASP.NET Core projects.

**Understanding the Secret Manager Tool:**
The Secret Manager tool operates by concealing the intricate details of where and how sensitive values are stored, allowing developers to utilize its capabilities without delving into implementation specifics. These app secrets, which should never be included in source control, are stored in a JSON file located in the local machine's user profile folder.

**Windows File System Path:**

```
%APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json

```
**Enabling Secret Storage:**
To enable the Secret Manager tool, the dotnet user-secrets init command is utilized, Or Click-Right on your project in Visual Studio and select Manage User Secrets Item.

```
dotnet user-secrets init
```

This command adds a UserSecretsId element within the project file's PropertyGroup. The UserSecretsId is a unique identifier associated with the project, and it is used to link secrets to the specific project.

**Sample Project File (XML):**
```
<PropertyGroup>
  <TargetFramework>netcoreapp3.1</TargetFramework>
  <UserSecretsId>79a3edd0-2092-40a2-a04d-dcb46d5ca9ed</UserSecretsId>
</PropertyGroup>

```
**Setting a Secret:**
Once the Secret Manager is initialized, secrets can be defined and associated with the project's UserSecretsId. For example, using the .NET CLI:

```
dotnet user-secrets set "ConnectionStrings:ApplicationDbContext" "..."

```

**Accessing a Secret**
To access a secret within your ASP.NET Core project, follow these steps:

- Register the User Secrets Configuration Source
The User Secrets Configuration Provider registers the necessary configuration source with the .NET Configuration API.

- Read the Secret via the Configuration API
Utilize the Configuration API to retrieve the secret securely within your application.

**Conclusion**
The Secret Manager tool in ASP.NET Core provides a robust solution for managing sensitive information during the development phase. By seamlessly integrating with the .NET Configuration API, it ensures a secure and organized approach to handling app secrets. As developers, embracing tools like Secret Manager not only enhances security but also streamlines the development process by separating sensitive data from version-controlled source code.
Tips for safer dependency management in JavaScript environments
Tags: node, packagejson, dependecymanagment, npm
Published: 2024-01-21 16:56:57


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lg64youncuy41gksf37m.jpeg)

Just about anyone who worked on the JavaScript ecosystem has faced annoying issues due to version mismatch , dependencies updates etc. , I want to share a few small tips that helped me mitigate some of the issues.

## Tip #1 [save-exact](https://docs.npmjs.com/cli/v9/using-npm/config#save-exact)

`npm install <package-name> --save-exact`

This will install the package exact version instead of default range.

`"dependencies": {
    "axios": "1.6.5"
}`

Due note that `package-lock.json` will still contain ranges. One way to mitigate this is to manually edit the file, a simple `regex` will enforce exact versions on the dependencies too.

(if some dependencies requirements can't be fulfilled with strict nested versions, you can iterate until you find a set of matching versions and make them static)

For example running the code below in `vim` editor.

`%s/: "\^/: "/g`

You can set it as the default behavior by running.

`npm config set save-exact=true`

Which will set `save-exact=true` in your `.npmrc`.

## Tip #2 avoid named releases

One way to help synchronize multiple developers working on the same repository is using `nvm` (or similar) with the appropriate `rc` file such as `.nvmrc`.

`nvm` supports named versions which might look nicer on a first look but generates various issues, since these versions aren't static.

Causing issues with compatibility with various dependencies , and other random issues such as running `nvm use` but it no longer finds the version, since it was updated and you need to reinstall it locally.

It's even more problematic once you take into account `CI/CD` since they reinstall the environment from scratch each time and it will probably differ from local developers environment that haven't yet update to the latests named version update.

Hence I highly recommend using a version number and simply change it as needed, knowingly.


## Tip #3 use [engines](https://docs.npmjs.com/cli/v10/configuring-npm/package-json#engines)

Basically an expansion on #2 , explicitly name the `node` / `npm` version (strict, not a range!) to avoid more unexpected and unwanted surprises.

## Tip #4 use [engine-strict](https://docs.npmjs.com/cli/v9/using-npm/config#engine-strict)

Avoid installing potential packages that might cause issues.

It's better to resolve an issue early on, with little overhead at the start than fixing it later when it's a critical part of your system.
Reducing egress costs for dummies (R2 vs S3)
Tags: cloudflare, aws, r2, s3
Published: 2024-01-21 16:41:33


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20p4rc0wcwq8j1it6x8n.jpeg)


One day I was checking [CloudFlare](http://cloudflare.com/) dashboard I noticed that one of the endpoints we were using to deliver new versions has huge bandwidth spikes.

Each new version we released was automatically downloaded by thousands of clients, resulting in terra bytes of egress costs to [S3](https://aws.amazon.com/s3/).

At the current rate this was around [3,000$/month](https://calculator.aws/#/createCalculator/S3).

Furthermore, our plan was to move to a daily release, which will make this problem even worse and jump to [~50,000$/month](https://calculator.aws/#/createCalculator/S3).

I immediately tried to think how to resolve this issue.

Since all the content we deliver on a new update is identical copies of the same new version, caching jumped into mind.

But unfortunately [CloudFront](https://aws.amazon.com/cloudfront/) costs weren't much better at around [2,500$/month](https://calculator.aws/#/createCalculator/CloudFront).

Being a big fan of [CloudFlare](http://cloudflare.com/) I knew of [R2](https://www.cloudflare.com/developer-platform/r2/) and quickly [calculated](https://www.cloudflare.com/pg-cloudflare-r2-vs-aws-s3/#htmlIdPlansMatrix) that using [R2](https://www.cloudflare.com/developer-platform/r2/) will reduce the costs to effectively  zero.

Implementing this was quite easy, simply store and serve from [R2](https://www.cloudflare.com/developer-platform/r2/) instead of [S3](https://aws.amazon.com/s3/).

Another bonus was faster download speed.
How to secure SSH server
Tags: ssh, security, root, sudo
Published: 2024-01-21 16:35:19


## Disable root login

1. Create new user `useradd -m  username`.
2. Set password `passwd username`.
3. **_Optional_**: Add user to sudoers `usermod -aG sudo username`.
4. Edit `/etc/ssh/ssh_config` or `/etc/ssh/sshd_config` and add:
```bash
# Authentication:
PermitRootLogin no
AllowUsers username
```
Might need to look for other config files being included that might override this setting (`grep -r "PermitRootLogin" /etc/ssh/`).

## Harden SSH
5. Disable empty password:
```bash
PermitEmptyPasswords no
```
6. Limit the number of authentication tries per connection:
```bash
MaxAuthTries 3
```
7. Changed to `ssh` version 2:
```bash
Include /etc/ssh/sshd_config.d/*.conf
Protocol 2
```
## Disable plain text authentication
8. Connecting with SSH key:
```bash
UsePAM no
PasswordAuthentication no
```

```bash
ssh-keygen 
```
## Restart SSH service
9. Restart `ssh` service `sudo systemctl restart ssh` or `sudo systemctl restart sshd`.

## Prevent brute force attacks
10. Install [fail2ban](https://github.com/fail2ban/fail2ban) or [sshguard](https://www.sshguard.net/) to ban IPs that fail to authenticate after a certain number of attempts.

# References
* [13 Ways to secure SSH server](https://www.makeuseof.com/improve-your-linux-server-security-with-these-hardening-steps/)
* [How To Set up SSH Keys on a Linux / Unix System](https://www.cyberciti.biz/faq/how-to-set-up-ssh-keys-on-linux-unix/)
* [sshd_config](https://linux.die.net/man/5/sshd_config)
* [ssh_config](https://linux.die.net/man/5/ssh_config)
* [ssh-keygen](https://linux.die.net/man/1/ssh-keygen)
* [useradd](https://linux.die.net/man/8/useradd)
* [passwd](https://linux.die.net/man/1/passwd)
* [usermod](https://linux.die.net/man/8/usermod)
* [fail2ban](https://github.com/fail2ban/fail2ban)
* [sshguard](https://www.sshguard.net/)
Serving static assets with Micronaut
Tags: micronaut, java
Published: 2024-02-01 10:52:50

---
title: Serving static assets with Micronaut
published: true
date: 2024-01-21 16:23:25 UTC
tags: micronaut, java
canonical_url: https://glaforge.dev/posts/2024/01/21/serving-static-assets-with-micronaut/
---

My go-to framework when developing Java apps or microservices is [Micronaut](https://micronaut.io). For the apps that should have a web frontend, I rarely use [Micronaut Views](https://micronaut-projects.github.io/micronaut-views/latest/guide/) and its templating support. Instead, I prefer to just **serve static assets** from my resource folder, and have some JavaScript framework (usually [Vue.js](https://vuejs.org/)) to populate my HTML content (often using [Shoelace](https://shoelace.style/) for its nice Web Components). However, the [static asset documentation](https://docs.micronaut.io/latest/guide/#staticResources)is a bit light on explanations. So, since I always forget how to configure Micronaut to serve static assets, I thought that would be useful to document this here.

In `/src/main/resources/application.properties`, I’m adding the following:

```
micronaut.router.static-resources.default.paths=classpath:public
micronaut.router.static-resources.default.mapping=/**
micronaut.router.static-resources.default.enabled=true

micronaut.server.cors.enabled=true

```

- The first line says that my resources will live in `src/main/resources/public/`.
- The second line means the pattern will match recursively for sub-directories as well.
- The `enabled` flag is to activate static serviing (not strictly needed as it’s supposed to be enabled by default).
- I also enabled CORS (cross-origin resource sharing).

Then in `src/main/resources/public/`, I’ll have my `index.html` file, my `css` and `js` folders.
Dependency Inversion Principle (DIP)
Tags: oop, solidprinciples, dependencyinversion, dip
Published: 2024-01-21 16:13:26

**What is the Dependency Inversion Principle?**

> The Dependency Inversion Principle (DIP) is one of the five SOLID principles that states:
> - High-level modules should not depend on low-level modules.
Both should depend on abstractions.
> - Abstractions should not depend on details. Details should depend on abstractions.

Let’s break this down by examples.

In this example: 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cusaqr6twtnfr5but6uo.png)

- **High-level Module(or Class)**: Class that executes an action with a tool.
- **Low-level Module (or Class)**: The tool that is needed to execute the action.
- **Abstraction**: Represents an interface that connects the two Classes.
- **Details**: How the tool works.

---

Another example **Vehicle** and **Engine**:

Without **DIP**:

- The `Vehicle` class directly instantiates a specific `Engine` class (e.g., `PetrolEngine`).

- The `Vehicle` depends on concrete details of `PetrolEngine`.

With **DIP**:

1. Introduce an abstraction:
   - Create an interface Engine with methods like `start()` 
     and `stop()`.

2. Refactor `Vehicle`:
   -  `Vehicle` depend on the `Engine` interface instead of a 
       concrete `Engine` class.
   - Inject a concrete `Engine` implementation (e.g., 
     `PetrolEngine` or `ElectricEngine`) at runtime.

Benefits:

- **Enhanced flexibility**: Change engine types without modifying `Vehicle` code.

- **Easier testing**: Mock Engine for testing `Vehicle` in isolation.

> This principle says a Class should not be fused with the tool it uses to execute an action. Rather, it should be fused to the interface that will allow the tool to connect to the Class.

> It also says that both the Class and the interface should not know how the tool works. However, the tool needs to meet the specifications of the interface.
NodeJS Scalability Quick Guide
Published: 2024-01-21 16:06:23

## NodeJS Basics and API Requests:
In the dynamic world of web development, efficiently managing API requests is key to a robust and adaptable app. Whether you're new to handling requests or looking to optimize for scalability, this guide simplifies NodeJS scalability.

## Understanding NodeJS Basics and API Requests
Dive into NodeJS known for speed and scalability. Explore its event-driven, non-blocking I/O model, essential for managing asynchronous tasks, including various requests.

## Types of API Requests

1. GET Request :

- Used to retrieve data.
- Example using Express framework:

```
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello, GET request!'));
app.listen(3000, () => console.log('Server listening'));

```

2. POST Request:

- Used to submit data.
- Example with Express and body-parser middleware:

```
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.post('/submit-data', (req, res) => {
  const requestData = req.body;
  res.send(`Data received: ${JSON.stringify(requestData)}`);
});
app.listen(3000, () => console.log('Server listening'));

```

3. PUT and PATCH Request : 

- Used to update resources.
- Example with Express:

```
// PUT Request
app.put('/update-resource/:id', (req, res) => {
  const resourceId = req.params.id;
  const updatedData = req.body;
  res.send(`Resource ${resourceId} updated with data: ${JSON.stringify(updatedData)}`);
});

// PATCH Request
app.patch('/partial-update/:id', (req, res) => {
  const resourceId = req.params.id;
  const partialData = req.body;
  res.send(`Partial update applied to resource ${resourceId} with data: ${JSON.stringify(partialData)}`);
});

```

4. DELETE Request :

- Used to remove resources.

```
app.delete('/delete-resource/:id', (req, res) => {
  const resourceId = req.params.id;
  res.send(`Resource ${resourceId} deleted`);
});

```

## Optimizing for High Performance

- **Use Asynchronous Operations:** Enable simultaneous execution of tasks.
- **Implement Caching:** Store frequently used data to reduce database queries.
- **Optimize Database Queries:** Organize queries for efficient data retrieval.
- **Load Balancing:** Distribute requests across servers to prevent overload.
- **Horizontal Scaling:** Add more servers to handle increased demand

## Conclusion
Optimize your NodeJS application for efficiency, speed and scalability. Asynchronous operations and smart strategies like caching, optimized queries, load balancing and horizontal scaling ensure smooth handling of growing user demands.

## Main Focus when Optimizing NodeJS:
Leverage asynchronous operations to maintain responsiveness under multiple concurrent requests and using async/await or promises.

## Role of Caching:
Caching stores frequently accessed data, reducing the need for resource-intensive database queries and enhances performance by quickly retrieving data.
Part 2 - Create an instance of EC2 and connect with SSH
Tags: aws, cloud
Published: 2024-01-21 16:02:47

Hi!

Create an instance of EC2 (Amazon Elastic Compute Cloud) allows execute instances of virtual machines, on the AWS infrastructure.

Some features of EC2 are Scalability, personalized configuration, Security, and pay-by-use.

Create an instance of EC2 (Amazon Elastic Compute Cloud) allows execute instances of virtual machines, on the AWS infrastructure.

Some features of EC2 are Scalability, personalized configuration, Security, and pay-by-use.

 

- **Create an EC2 and connect with SSH**
    1. Go to the EC2 service.
    2. On the left menu, click on Instances.
    3. Add a new name to the instance
    4. Let Amazon Linux, everything that has the free tier label.
    5. Create a key pair.
    6. Add a name
    7. and let the RSA and .pem options be selected.
    8. Click on the Create key pair button.
    9. Save in a secure place on your laptop or PC.

![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/colwnzc5rkdxftg22dwu.png)

 - **Create a security group:**
    1. Allow SSH traffic from
    2. Click Lunch instance.
    3. Check the instances.
    4. Click on the connect button.
    5. Select the SSH client tab
    6. Follow the steps.
**Note**: if you are in Windows, use the git bash terminal if the connection with another terminal shows an unprotected private key file! message.

![2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6fzri97voe0ar58gnpx3.png)

After connect:

![3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/btp5hyhf5qxvaufnpgkl.png)

- **Check the instances:**
    1. If you want to check the instances from your CLI, type
```bash
aws ec2 describe-instances
```

 - **Delete the instance:**
    1. Go to your instance
    2. Choose Instance State
    3. Select Terminate Instance

See you next time!