# Improper Locking (CWE-667) The product does not properly acquire or release a lock on a resource, leading to unexpected resource state or behaviors. - Prevalence: Medium 1 language covered - Impact: High 1 high-severity rules - Prevention: Documented 1 fix examples **OWASP:** Insecure Design (A04:2021-Insecure Design) - #4 ## Description Improper locking can lead to race conditions, deadlocks, or resource leaks. When locks are not properly managed, concurrent operations may corrupt shared data or cause the application to hang. ## Prevention ### Key Practices - Use of sync ### Go Use defer for Unlock, avoid defer in loops, use pointer receivers with mutex ## Warning Signs - [HIGH] Improper mutex usage can cause: - Deadlocks (Lock without Unlock, recursive locking) - Race conditions (copying mutex br ## Consequences - DoS - Modify Application Data - Execute Unauthorized Code ## Mitigations - Use established synchronization primitives correctly - Always release locks in finally blocks or use RAII patterns - Avoid nested locks where possible ## Detection - Total rules: 1 - Languages: go ## Rules by Language ### Go (1 rules) - **Mutex Misuse** [HIGH]: Improper use of sync.Mutex or sync.RWMutex can cause deadlocks, data races, or performance issues. Common issues include missing Unlock, defer in loops, and copying mutex values. - Remediation: 1. Always use defer to unlock: ```go mu.Lock() defer mu.Unlock() // critical section ``` 2. In loops, unlock manually or extract to separate function: ```go // Option 1: Manual unlock for _, item := range items { mu.Lock() process(item) mu.Unlock() } // Option 2: Extract to function for _, item := range items { processLocked(item) // defer works here } ``` 3. Always use pointer receivers for methods that lock: ```go func (s *Server) Handle() { // *Server, not Server s.mu.Lock() defer s.mu.Unlock() } ``` 4. Never call another locking method while holding lock: ```go // BAD func (s *Server) A() { s.mu.Lock() s.B() // Deadlock if B() also locks s.mu.Unlock() } // GOOD - use internal unlocked version func (s *Server) A() { s.mu.Lock() defer s.mu.Unlock() s.bLocked() } func (s *Server) bLocked() { /* no lock here */ } ```