惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
宝玉的分享
宝玉的分享
酷 壳 – CoolShell
酷 壳 – CoolShell
T
The Exploit Database - CXSecurity.com
Help Net Security
Help Net Security
腾讯CDC
Project Zero
Project Zero
C
CXSECURITY Database RSS Feed - CXSecurity.com
IT之家
IT之家
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tailwind CSS Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
LINUX DO - 最新话题
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Threatpost
N
News | PayPal Newsroom
C
Cybersecurity and Infrastructure Security Agency CISA
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
SegmentFault 最新的问题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
P
Proofpoint News Feed
A
Arctic Wolf
B
Blog RSS Feed
Forbes - Security
Forbes - Security
P
Privacy & Cybersecurity Law Blog
Attack and Defense Labs
Attack and Defense Labs
V2EX - 技术
V2EX - 技术
P
Proofpoint News Feed
I
Intezer
Application and Cybersecurity Blog
Application and Cybersecurity Blog
阮一峰的网络日志
阮一峰的网络日志
aimingoo的专栏
aimingoo的专栏
T
Tenable Blog
MyScale Blog
MyScale Blog
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
WordPress大学
WordPress大学
W
WeLiveSecurity
D
DataBreaches.Net
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
GRAHAM CLULEY
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
罗磊的独立博客
The Last Watchdog
The Last Watchdog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
Vulnerabilities – Threatpost
美团技术团队
Microsoft Security Blog
Microsoft Security Blog

Stonecharioteer on Tech

I Traced My Traffic Through a Home Tailscale Exit Node What Was I Reading Last? In Three Not-So-Easy Pieces Dogfooding Is Hard Code blocks in your books, finally GoForGo v0.9.0 Merrilin - We built an app to read books I use a Macbook now Data Structures & Algorithms - Preparing for Interviews Using a local DNS namespace for local service discovery Direction KOllector - Publishing KOReader Highlights gbt: branches touched in the last 24 hours A Soiree into Symbols in Ruby Some Smalltalk about Ruby Loops Ruby Blocks Returning from Ruby Blocks, Procs and Lambdas My Linux Laptop Finally Works: How Claude Helped Me Fix Years of Annoyances TIL: Watchexec - Modern File Watching for Development Workflows A Less Busy Mind GoForGo - Learn Go through live examples Migrating My Old Blog to Hugo with Claude The Qtile Window Manager: A Python-Powered Tiling Experience Read the RFCs that Built the Internet Py-x-Protobuf - Or How I Learned to Stop Worrying and Love Protocol Buffers Python Reverse a List New Beginnings Leaving ChainSafe Systems Screen Lock for Cinnamon Desktop using Zenity and Terminal Commands Crews Not Teams A System for Getting Better at LeetCode So Far So Rust Retrying HTTP Requests with Rust A Primer on Control Charts Learning Rust Explicit is Better than Implicit: Rust for Pythonistas Using Custom Delimiters in Jinja Templates TIL: Creating Fixed Length Iterables in Python Documentation Without Assumption Vagrant Python - A Reflection in 2022 Learning Golang No, A Virtual Machine Is Not Enough: Why Developers Need Native Linux Empathy in Tech For Those Who Came in Late A Weekend With PostgreSQL TIL: Gooey and Python Fire for Quick GUIs and CLIs TIL: 2ality - Dr. Axel Rauschmayer's JavaScript Blog TIL: MassDNS - High-Performance Bulk DNS Lookups TIL: Matomo Analytics, Google Tech Writing, Memory Programming, and NES TV Signals TIL: MontyDB - MongoDB Implemented in Python Returning to the Craft of Programming TIL: CPUFetch, OneFetch, and Learn CSS TIL: DNS Performance Testing and Pi-hole with Unbound TIL: Eli Bendersky's Blog, Awesome By Example, NoCoDB, and Martin Kleppmann TIL: CRDTs, Extreme HTTP Performance, and BYTEPATH Game TIL: AutoInvent, ASGI, Python Packaging, RAPIDS GPU Computing, and FlaskCon TIL: MangaDesk - Terminal Client for MangaDex TIL: McFly - Smart Shell History Search TIL: Siege Load Testing and Awesome FastAPI Resources TIL: Ventoy Bootable USB and Justniffer Network Analysis TIL: CLI Code Review, Git Split Diffs, and Internal Combustion Engine TIL: Benford's Law, Web Security Headers, Event Sourcing, and Mozilla Security Guidelines How to Write Documentation - The README.md File The Importance of Documentation TIL: NNgroup UX Research, SponsorBlock, and Labella Python Library TIL: The Little Book of Rust Macros and Rust Performance Book TIL: Git-Bug Distributed Issue Tracker and Omni Kubernetes Monitoring TIL: Zellij - Modern Terminal Multiplexer TIL: How Discord Handles 2.5 Million Concurrent Voice Users TIL: Volumio - The Audiophile Music Player TIL: Areopagitica - Milton's Defense of Free Speech TIL: Fast Node Manager, Zoxide Smart CD, Technical Writing, PyO3, and Qubes OS TIL: Slurm Workload Manager for HPC Clusters TIL: Data Visualization Guide and Oso Authorization Academy TIL: CORS Deep Dive, Piku Tiny PaaS, Rust Strings, and Deno Standard Library TIL: Raspberry Pi OS Development, Vim Beginner Guide, Password Management, and QueryBook TIL: uBlock Origin Performance Optimization on Firefox TIL: Breaking PostgreSQL at Scale and LeetCode Problem Patterns TIL: Awesome Tmux Resources for Terminal Multiplexing TIL: Grit - A Multitree-Based Personal Task Manager TIL: Lens 4.2 Kubernetes IDE, Shell Scripting Guide, and Dark HTTP Server Do The Job You Hate So You Won't Hate The Job You Love TIL: Innernet VPN Solution and NoteCalc Calculator App TIL: Argo CD for GitOps and Lens Kubernetes IDE TIL: Modern Rust CLI Tools - System Monitoring, HTTP Requests, and DNS TIL: tz - A Time Zone Helper Tool TIL: Distributed Systems Education, Fallacies, and Self-Hosted Internet Archiving TIL: Real-Time Voice Cloning Technology TIL: ChartMuseum for Helm, AMD's Corporate Journey, and Kubernetes Pod Scaling TIL: Docker and Kubernetes Tools - Whaler, Descheduler, and Dive TIL: Post-Mortem Collection, Terminal Plotting, and Technical Twitter TIL: Dark Mode Toggle Web Component by Google Chrome Labs TIL: Python eval(), exec(), and compile() Functions TIL: Camelot PDF Tables, PostgreSQL Row Level Security, Zerodha Varsity, and Write Yourself a Git TIL: fuser Command for Process and File Investigation TIL: i Hate Regex - The Ultimate Regex Cheat Sheet TIL: Dolt - Git for Data and Database Version Control TIL: x86 Assembly Programming and SafeEyes Break Reminder TIL: Comprehensive Distributed Systems Reading List TIL: Cosmopolitan C Library, Distributed Systems Book, High Performance Browser Networking, and Rust Roguelike Tutorial
TIL: HTTP Status Code Reference, Security Headers, and Python Security Tools
2020-11-06 · via Stonecharioteer on Tech

Today’s learning focused on web security fundamentals, from HTTP status codes to security headers and Python security tooling.

HTTP Status Codes Cheatsheet provides a comprehensive quick reference for all HTTP response codes.

Status Code Categories:

1xx Informational:

1
2
3
100 Continue          - Server received headers, client should send body
101 Switching Protocols - Server switching to protocol in Upgrade header
102 Processing        - Server received request, still processing (WebDAV)

2xx Success:

1
2
3
4
5
200 OK                - Request successful
201 Created           - Resource successfully created
202 Accepted          - Request accepted for processing (async)
204 No Content        - Success, but no content to return
206 Partial Content   - Range request successful

3xx Redirection:

1
2
3
4
5
301 Moved Permanently - Resource permanently moved to new URL
302 Found             - Resource temporarily at different URL
304 Not Modified      - Resource not modified since last request
307 Temporary Redirect - Same as 302, but method must not change
308 Permanent Redirect - Same as 301, but method must not change

4xx Client Errors:

1
2
3
4
5
6
7
400 Bad Request       - Malformed request syntax
401 Unauthorized      - Authentication required
403 Forbidden         - Server understood, but refuses to authorize
404 Not Found         - Resource not found
409 Conflict          - Request conflicts with current state
422 Unprocessable Entity - Syntax correct, but semantically incorrect
429 Too Many Requests - Rate limiting triggered

5xx Server Errors:

1
2
3
4
500 Internal Server Error - Generic server error
502 Bad Gateway          - Invalid response from upstream server
503 Service Unavailable  - Server temporarily unavailable
504 Gateway Timeout      - Upstream server timeout

OWASP Secure Headers provides comprehensive guidance on implementing security-focused HTTP headers.

Content Security Policy (CSP):

1
2
3
4
5
6
7
Content-Security-Policy: default-src 'self';
                        script-src 'self' 'unsafe-inline' cdnjs.cloudflare.com;
                        style-src 'self' 'unsafe-inline' fonts.googleapis.com;
                        font-src 'self' fonts.gstatic.com;
                        img-src 'self' data: https:;
                        connect-src 'self' api.example.com;
                        frame-ancestors 'none';

HTTP Strict Transport Security (HSTS):

1
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

X-Frame-Options and Frame Ancestors:

1
2
3
X-Frame-Options: DENY
# or for CSP
Content-Security-Policy: frame-ancestors 'none';

Content Type Options:

1
X-Content-Type-Options: nosniff

Referrer Policy:

1
Referrer-Policy: strict-origin-when-cross-origin

Permissions Policy (formerly Feature Policy):

1
Permissions-Policy: geolocation=(), microphone=(), camera=()
1
2
3
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin

Implementation Examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const express = require("express");
const helmet = require("helmet");

const app = express();

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "'unsafe-inline'", "cdnjs.cloudflare.com"],
        styleSrc: ["'self'", "'unsafe-inline'", "fonts.googleapis.com"],
        fontSrc: ["'self'", "fonts.gstatic.com"],
        imgSrc: ["'self'", "data:", "https:"],
        connectSrc: ["'self'", "api.example.com"],
        frameAncestors: ["'none'"],
      },
    },
    hsts: {
      maxAge: 31536000,
      includeSubDomains: true,
      preload: true,
    },
  }),
);
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# settings.py
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
X_FRAME_OPTIONS = 'DENY'

CSP_DEFAULT_SRC = ("'self'",)
CSP_SCRIPT_SRC = ("'self'", "'unsafe-inline'", "cdnjs.cloudflare.com")
CSP_STYLE_SRC = ("'self'", "'unsafe-inline'", "fonts.googleapis.com")

hsecscan is a Python tool for analyzing HTTP security headers:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Installation
pip install hsecscan

# Basic usage
hsecscan https://example.com

# Custom analysis
from hsecscan import scan_headers

def analyze_security_headers(url):
    results = scan_headers(url)

    security_score = 0
    recommendations = []

    # Check for essential headers
    essential_headers = [
        'strict-transport-security',
        'content-security-policy',
        'x-content-type-options',
        'x-frame-options'
    ]

    for header in essential_headers:
        if header in results['headers']:
            security_score += 25
        else:
            recommendations.append(f"Missing {header}")

    return {
        'score': security_score,
        'recommendations': recommendations,
        'headers': results['headers']
    }

secure.py provides easy security header management:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from secure import Secure

# Basic configuration
secure_headers = Secure()

# Custom configuration
secure_headers = Secure(
    csp=ContentSecurityPolicy(
        default_src="'self'",
        script_src=["'self'", "cdnjs.cloudflare.com"],
        style_src=["'self'", "'unsafe-inline'"]
    ),
    hsts=StrictTransportSecurity(
        max_age=31536000,
        include_subdomains=True,
        preload=True
    ),
    referrer=ReferrerPolicy.strict_origin_when_cross_origin,
    permissions=PermissionsPolicy(
        geolocation="none",
        microphone="none",
        camera="none"
    )
)

# Flask integration
from flask import Flask

app = Flask(__name__)

@app.after_request
def set_security_headers(response):
    secure_headers.framework.flask(response)
    return response

# Django middleware
class SecurityHeadersMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        secure_headers.framework.django(response)
        return response

Secure by Design Principles

Secure by Design book emphasizes building security into software architecture from the beginning:

Core Principles:

Defense in Depth:

  • Multiple security layers
  • Fail-safe defaults
  • Principle of least privilege
  • Input validation at every boundary

Secure Architecture Patterns:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# Domain-driven security model
class SecureUser:
    def __init__(self, user_id, permissions):
        self._user_id = self._validate_user_id(user_id)
        self._permissions = self._validate_permissions(permissions)

    @staticmethod
    def _validate_user_id(user_id):
        if not isinstance(user_id, str) or len(user_id) < 3:
            raise ValueError("Invalid user ID")
        return user_id

    def can_access(self, resource):
        return resource.required_permission in self._permissions

    def sanitized_id(self):
        # Never expose internal IDs directly
        return hashlib.sha256(self._user_id.encode()).hexdigest()[:8]

System Administration Tools:

Process Investigation:

1
2
3
4
5
6
7
8
9
# Find process ID by name pattern
pidof nginx
pidof -x python3

# Multiple processes
pidof -x "python.*myapp"

# Single process only
pidof -s httpd

These tools and principles provide a comprehensive foundation for implementing and maintaining web application security, from basic HTTP understanding to advanced security header configuration and automated security analysis.