trailofbits.go.sync-mutex-value-copied.sync-mutex-value-copied

profile photo of trailofbitstrailofbits
Author
232
Download Count*

A sync.Mutex is copied in function $FUNC given that $T is value receiver. As a result, the struct $T may not be locked as intended

Run Locally

Run in CI

Defintion

rules:
  - id: sync-mutex-value-copied
    message: A `sync.Mutex` is copied in function `$FUNC` given that `$T` is value
      receiver.  As a result, the struct `$T` may not be locked as intended
    languages:
      - go
    severity: ERROR
    metadata:
      category: security
      cwe: "CWE-688: Function Call With Incorrect Variable or Reference as Argument"
      subcategory:
        - vuln
      confidence: HIGH
      likelihood: HIGH
      impact: LOW
      technology:
        - --no-technology--
      description: Copying of `sync.Mutex` via value receivers
      references:
        - https://go101.org/article/concurrent-common-mistakes.html
      license: AGPL-3.0 license
      vulnerability_class:
        - Other
    patterns:
      - pattern-either:
          - pattern: |
              func ($T $TYPE) $FUNC(...){
                ...
                $T.Lock()
                ...
              }
          - pattern: |
              func ($T $TYPE) $FUNC(...){
                ...
                $T.RLock()
                ...
              }
      - pattern-not: |
          func ($T2 *$TYPE2) $FUNC(...){
            ...
          }

Examples

sync-mutex-value-copied.go

// Code from https://go101.org/article/concurrent-common-mistakes.html

package main

import "sync"

type Counter struct {
	sync.Mutex
	n int64
}


// ok: sync-mutex-value-copied
func (c *Counter) ValueFine(d int64) (r int64) {
	c.Lock()
	r = c.n
	c.Unlock()
	return
}

// ruleid: sync-mutex-value-copied
func (c Counter) Value() (r int64) {
	c.Lock()
	r = c.n
	c.Unlock()
	return
}