Skip to content

Commit

Permalink
post cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
augchan42 committed Jun 4, 2024
1 parent 56c61ed commit 6a23dec
Show file tree
Hide file tree
Showing 3 changed files with 125 additions and 28 deletions.
94 changes: 93 additions & 1 deletion _posts/2024-05-07-Client vs Server side Auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,103 @@ While implementing social login features for [8-Bit Oracle](https://8bitoracle.a
### Google OAuth2 Social Login
For Google social login, the login flow is managed client-side. In this setup, we utilize `@supabase/ssr`'s `createBrowserClient` method to retrieve session information post-authentication.

```code
import { createBrowserClient } from "@supabase/ssr";
export function createSupabaseBrowserClient() {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
// options
);
}
```

### Magic Link Email Authentication
Conversely, for email authentication that employs a magic link, the link directs the user to an API confirm route located on the backend. This requires using `@supabase/ssr`'s `createServerClient` to retrieve session information after authentication is confirmed.
For situations where cookie values need to be set (login, registration, signout) then the component flag should be false (default).

```code
import { type NextRequest, type NextResponse } from "next/server";
import { cookies } from "next/headers";
import { deleteCookie, getCookie, setCookie } from "cookies-next";
import { createServerClient, type CookieOptions } from "@supabase/ssr";
// server component can only get cookies and not set them, hence the "component" check
export function createSupabaseServerClient(component: boolean = false) {
const cookieStore = cookies();
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
const cookieValue = cookieStore.get(name)?.value;
console.log(`Getting cookie: ${name} = ${cookieValue}`); // Log the cookie retrieval
return cookieValue;
},
set(name: string, value: string, options: CookieOptions) {
if (component) return;
console.log(`Not Setting cookie: ${name} = ${value}, options = ${JSON.stringify(options)}`); // Log the cookie setting
try {
cookieStore.set({ name, value, ...options });
console.log(`Cookie set successfully: ${name}`);
//return { success: true, message: `Cookie set successfully: ${name}` };
} catch (error) {
console.error(`Error setting cookie: ${name}`, error);
//return { success: false, message: `Error setting cookie: ${name}`, error: error };
}
},
remove(name: string, options: CookieOptions) {
if (component) return;
console.log(`Removing cookie: ${name}, options = ${JSON.stringify(options)}`); // Log the cookie removal
try {
cookieStore.delete({ name, ...options });
console.log(`Cookie removed successfully: ${name}`);
//return { success: true, message: `Cookie removed successfully: ${name}` };
} catch (error) {
console.error(`Error removing cookie: ${name}`, error);
//return { success: false, message: `Error removing cookie: ${name}`, error: error };
}
},
},
}
);
}
```

### Integrated Authentication UI
A potentially confusing aspect is that Supabase's auth-ui can display both types of logins within the same widget. Moreover, the code samples from auth-ui typically use `createClient` from `@supabase/supabase-js`, which can add to the confusion.
A potentially confusing aspect is that [Supabase's auth-ui](https://supabase.com/docs/guides/auth/auth-helpers/auth-ui) can display both types of logins within the same widget. Moreover, the code samples from auth-ui use the older `createClient` from `@supabase/supabase-js`, which adds to the confusion. The view="magic_link" and providers={['google']} are configuring the same widget.

```code
<div className="justify-center w-full max-w-xs animate-in text-foreground">
<Auth
view="magic_link"
appearance={{
theme: ThemeSupa,
style: {
button: {
borderRadius: '5px',
borderColor: 'rgb(8, 107, 177)',
},
},
variables: {
default: {
colors: {
brand: 'rgb(8, 107, 177)',
brandAccent: 'gray',
},
},
},
}}
supabaseClient={supabase}
providers={['google']}
theme="dark"
socialLayout="vertical"
redirectTo={`${siteUrl}/${locale}/beta`}
/>
</div>
```

## Further Reading and Resources
For those looking to deepen their understanding or set up their own authentication mechanisms, here are some valuable resources:
Expand Down
4 changes: 2 additions & 2 deletions _posts/2024-05-31-UI Frameworks.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ tags:
I think I've settled on [shadcn](https://ui.shadcn.com), but I'm still getting the hang of it.

### Evolution of the Project
My project started out using plain Bootstrap, then transitioned to Create-React-App (which is distinct from React), and finally to Next.js.
My project started out using plain Bootstrap, then transitioned to Create-React-App (which is distinct from React), and finally to Next.js App Router.

### UI Development Challenges
However, building an app from scratch is a ton of work, especially with all the UI widgets and components required. There's a trend now towards granular component libraries, which are geared towards copying and pasting code directly into your project, instead of npm installing an entire framework.
Expand All @@ -31,7 +31,7 @@ However, building an app from scratch is a ton of work, especially with all the
Initially, I thought this approach was great, and this is how shadcn works. Since I am always concerned about bugs in whatever open source library I use, I usually fork the project, then import stuff from my fork. This gives me full visibility into the code and allows me to fix things as needed (assuming I can do it!).

### Component Libraries
Component libraries like shadcn are geared towards copy-pasting components directly and don't require you to do an npm install (though shadcn does require npm installing underlying unstyled radix-ui components).
Component libraries like shadcn are geared towards copy-pasting components directly and don't require you to do an npm install (though shadcn does require npm installing the underlying unstyled radix-ui components).

### Challenges with This Approach
The issue, of course, is bugs, upgrades, and versioning. Once you do your copy/paste, you are effectively on your own little branch of the code not tied to anything.
Expand Down
55 changes: 30 additions & 25 deletions _posts/2024-06-03-Securing SSH.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ tags:
---

## Understanding the Issue
Despite having Fail2Ban and UFW installed, unauthorized login attempts were not being effectively blocked. The main issues were related to the order of rule processing in iptables and the management of rules. I was using a nonstandard ssh port (1000 instead of 22). And I also modified the rules to preserve bans on restart which caused the issue.
Despite having Fail2Ban and UFW installed, unauthorized login attempts were not blocked. I didnt understand the order of rule processing in iptables. I modified the rules to preserve bans on restart which started my issues (you shouldn't have these issues if you just keep the out of the box sshd rules).


The jail is implemented as iptables rules, if there are no relevant rules or rules with all 0.0.0.0, then no blocks are happening!!!!
The fail2ban jail is implemented as iptables rules, if there are no relevant rules or rules with all 0.0.0.0, then no blocks are happening!!!!
If there are any startup errors for any jails, none of the jails will work (if xrdp jail fails, then ssh won't work either)
Both ufw and fail2ban are wrappers around the underlying iptables packet filtering.
If you continue to see unknown login attempts in /var/log/auth.log, then the JAIL ISNT WORKING.
Expand All @@ -35,7 +34,7 @@ To ensure that Fail2Ban functions effectively, the `jail.local` file must be cor

#### Key Configurations:

- **Jail Definition:** Define the [sshd] section if not already present, specifying the backend to use, the log path, and the specific filter.
- **Jail Definition:** Define the [sshd] section if not already present, specifying the backend to use, the log path, and the specific filter and make sure its enabled.

```bash
[sshd]
Expand All @@ -54,7 +53,7 @@ fail2ban implements blocking rules using iptables. Check if there are any rules
```bash
sudo iptables -L -n
```
Your chain (e.g., f2b-sshd) should appear before all other rules that allow traffic, such as ufw:
Your rule chain (e.g., f2b-sshd) should appear before all other rules that allow traffic, such as ufw:

```bash
Chain INPUT (policy DROP)
Expand All @@ -78,55 +77,61 @@ DROP all -- 43.163.199.47 0.0.0.0/0
DROP all -- 119.28.115.120 0.0.0.0/0
DROP all -- 64.227.185.239 0.0.0.0/0
```
I had multiple f2b-sshd chains that weren't being cleaned up properly on fail2ban restart. I had to manually clean up the spurious rules and the f2b-sshd chains before I could get everything working.

### 3. Proper Ordering of the f2b-sshd Chain
The f2b-sshd chain needs to be evaluated before any UFW rules to ensure that banned IPs are blocked immediately.
The action to add the chain should be Insert (I) not Append (A) and it should be inserted at the top. INPUT 1 does this:
The f2b-sshd chain needs to be evaluated before any UFW rule chains to ensure that banned IPs are blocked immediately.
The action to add the chain should be Insert (I) not Append (A) and it should be inserted at the top. The 'INPUT 1' flag does this:

**Command in iptables-multiport.conf to insert the f2b-sshd chain at the top of the INPUT chain and restore bans from file when fail2ban starts:**

```bash
actionstart = <iptables> -N f2b-<name>
<iptables> -I INPUT 1 -j f2b-<name>
<iptables> -I f2b-<name> 1 -j <returntype>
cat /etc/fail2ban/persistent.bans | awk '/^fail2ban-<name>/ {print $2}' \
| while read IP; do iptables -I f2b-<name> 1 -s $IP -j <blocktype>; done
actionstart =
<iptables> -N f2b-<name> # Create a new chain named f2b-<name> in iptables
<iptables> -I INPUT 1 -j f2b-<name> # Insert the f2b-<name> chain at the top of the INPUT chain to ensure it's evaluated first
<iptables> -I f2b-<name> 1 -j <returntype> # Insert a rule at the top of the f2b-<name> chain to specify the action (e.g., RETURN)
cat /etc/fail2ban/persistent.bans | awk '/^fail2ban-<name>/ {print $2}' \ # Read the persistent bans file, extract IPs for the f2b-<name> chain
| while read IP; do iptables -I f2b-<name> 1 -s $IP -j <blocktype>; done # For each IP, insert a rule at the top of the f2b-<name> chain to block the IP

```
The definitions for the commands in the <> tags are defined in other files like iptables-common.conf.

### 4. Example actionban
**Command to ban an ip and add to persistent bans file:**
This will add a rule to the f2b-sshd chain, which is referenced in the default iptables INPUT chain.

```bash
actionban = <iptables> -I f2b-<name> 1 -s <ip> -j <blocktype>
echo "fail2ban-<name> <ip>" >> /etc/fail2ban/persistent.bans
actionban =
<iptables> -I f2b-<name> 1 -s <ip> -j <blocktype> # Insert a rule at the top of the f2b-<name> chain to block the IP specified
echo "fail2ban-<name> <ip>" >> /etc/fail2ban/persistent.bans # Append the ban information to the persistent bans file for record-keeping
```

### 5. Cleaning Up Old Rules on Fail2Ban Restart
Ensuring that all Fail2Ban rules are properly removed on restart was crucial to avoid conflicts with stale rules. All rules need to be deleted, then rules flushed, then finally the chain itself can be deleted. If any rules are still present, deleting the chain will fail! The -D command needs to find the rules that were previously added with -A. If the rules look different then they won't be deleted!
Making sure all Fail2Ban rules are properly removed on restart is crucial to avoid conflicts with stale rules. All rules need to be deleted, then rules flushed, then the rule chain itself can be deleted. If any rules are still present, deleting the chain will fail! The -D command needs to find the rules that were previously added with -A. If the rules look different then they won't be deleted!

**Commands used in `actionstop` to flush old rules:**
Notice this -D command matches the above -I command (except for the syntax to insert rule at the first line of the chain which isn't relevant.)

```bash
actionstop = <iptables> -D <chain> -j f2b-<name>
<actionflush>
<iptables> -X f2b-<name>
actionstop =
<iptables> -D <chain> -j f2b-<name> # Delete the rule that jumps to the f2b-<name> chain from the specified <chain>
<actionflush> # Execute the command to flush all rules in the f2b-<name> chain (specific command should be defined elsewhere)
<iptables> -X f2b-<name> # Delete the f2b-<name> chain from iptables
```

You can also manually run the rules individually for troubleshooting:
You can also manually run rules for troubleshooting. You will need to run the -D command multiple times to delete all rules in a rule chain manually.
```bash
iptables -D <chain> -p <protocol> -j f2b-<name>
iptables -F f2b-<name>
iptables -X f2b-<name>
iptables -D <chain> -p <protocol> -j f2b-<name> # Delete a specific rule in the <chain> that directs traffic to the f2b-<name> chain for a given <protocol>
iptables -F f2b-<name> # Flush all rules in the f2b-<name> chain, effectively removing all specific blocking rules within that chain
iptables -X f2b-<name> # Delete the f2b-<name> chain itself after flushing its rules
```
BTW, all rules must be deleted before a chain can be deleted (-X). If you see a rule chain can't be deleted, then it's probably because a rule in that chain is still there. This is probably because the -D command can't find a rule to delete (because a rule was added with different syntax).
All rules must be deleted before a chain can be deleted (-X). If you see a rule chain can't be deleted, then it's probably because a rule in that chain is still there. This is probably because the -D command can't find a rule to delete (because a rule was added with different syntax), or there are still rules left to delete.

### 6. Adjusting Rule Deletion for Non-default Actions
Matching the rule deletion commands to the specific rules added by Fail2Ban, especially when using non-default ports.
Matching the rule deletion commands to the specific rules added by Fail2Ban, especially when using non-default ports or additional/different flags.

**Command to delete the f2b-sshd chain from the default INPUT chain:**
I needed this command because the same f2b-sshd custom chain was defined multiple times in my INPUT chain due to previous issues.
I needed to run this command multiple times because the same f2b-sshd custom chain was defined several times in my INPUT chain due to previous issues.

```bash
sudo iptables -D INPUT -p tcp -j f2b-sshd
Expand Down

0 comments on commit 6a23dec

Please sign in to comment.