Repository: pion/dtls
Pull request #293 (2020-09-17 03:21:17)

Update CI configs to v0.4.7
Update lint scripts and CI configs.

codecov[bot]: # [Codecov](https://codecov.io/gh/pion/dtls/pull/293?src=pr&el=h1) Report
> Merging [#293](https://codecov.io/gh/pion/dtls/pull/293?src=pr&el=desc) into [master](https://codecov.io/gh/pion/dtls/commit/789798433596e4dd92451b66984dddb2f8a9f165?el=desc) will **increase** coverage by `0.21%`.
> The diff coverage is `n/a`.

[![Impacted file tree graph](https://codecov.io/gh/pion/dtls/pull/293/graphs/tree.svg?width=650&height=150&src=pr&token=bcCB2jB88I)](https://codecov.io/gh/pion/dtls/pull/293?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master     #293      +/-   ##
==========================================
+ Coverage   72.73%   72.95%   +0.21%     
==========================================
  Files          73       72       -1     
  Lines        3884     3882       -2     
==========================================
+ Hits         2825     2832       +7     
+ Misses        791      783       -8     
+ Partials      268      267       -1     
```

| Flag | Coverage Δ | |
|---|---|---|
| #go | `72.95% <ø> (+0.18%)` | :arrow_up: |
| #wasm | `?` | |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.

| [Impacted Files](https://codecov.io/gh/pion/dtls/pull/293?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [errors\_noerrno.go](https://codecov.io/gh/pion/dtls/pull/293/diff?src=pr&el=tree#diff-ZXJyb3JzX25vZXJybm8uZ28=) | | |
| [conn.go](https://codecov.io/gh/pion/dtls/pull/293/diff?src=pr&el=tree#diff-Y29ubi5nbw==) | `83.00% <0.00%> (+0.54%)` | :arrow_up: |
| [internal/net/dpipe/dpipe.go](https://codecov.io/gh/pion/dtls/pull/293/diff?src=pr&el=tree#diff-aW50ZXJuYWwvbmV0L2RwaXBlL2RwaXBlLmdv) | `95.29% <0.00%> (+2.35%)` | :arrow_up: |
| [crypto\_gcm.go](https://codecov.io/gh/pion/dtls/pull/293/diff?src=pr&el=tree#diff-Y3J5cHRvX2djbS5nbw==) | `69.23% <0.00%> (+3.84%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/pion/dtls/pull/293?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/pion/dtls/pull/293?src=pr&el=footer). Last update [7897984...18ec198](https://codecov.io/gh/pion/dtls/pull/293?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).

scorpionknifes: I'm taking this one.

Patch:
diff --git a/.golangci.yml b/.golangci.yml
index 570f17b..4213697 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -3,6 +3,80 @@ linters-settings:
     check-shadowing: true
   misspell:
     locale: US
+  exhaustive:
+    default-signifies-exhaustive: true
+
+linters:
+  enable:
+    - asciicheck       # Simple linter to check that your code does not contain non-ASCII identifiers
+    - bodyclose        # checks whether HTTP response body is closed successfully
+    - deadcode         # Finds unused code
+    - depguard         # Go linter that checks if package imports are in a list of acceptable packages
+    - dogsled          # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
+    - dupl             # Tool for code clone detection
+    - errcheck         # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
+    - exhaustive       # check exhaustiveness of enum switch statements
+    - exportloopref    # checks for pointers to enclosing loop variables
+    - gci              # Gci control golang package import order and make it always deterministic.
+    - gochecknoglobals # Checks that no globals are present in Go code
+    - gochecknoinits   # Checks that no init functions are present in Go code
+    - gocognit         # Computes and checks the cognitive complexity of functions
+    - goconst          # Finds repeated strings that could be replaced by a constant
+    - gocritic         # The most opinionated Go source code linter
+    - godox            # Tool for detection of FIXME, TODO and other comment keywords
+    - goerr113         # Golang linter to check the errors handling expressions
+    - gofmt            # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
+    - gofumpt          # Gofumpt checks whether code was gofumpt-ed.
+    - goheader         # Checks is file header matches to pattern
+    - goimports        # Goimports does everything that gofmt does. Additionally it checks unused imports
+    - golint           # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes
+    - gomodguard       # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
+    - goprintffuncname # Checks that printf-like functions are named with `f` at the end
+    - gosec            # Inspects source code for security problems
+    - gosimple         # Linter for Go source code that specializes in simplifying a code
+    - govet            # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
+    - ineffassign      # Detects when assignments to existing variables are not used
+    - misspell         # Finds commonly misspelled English words in comments
+    - nakedret         # Finds naked returns in functions greater than a specified function length
+    - noctx            # noctx finds sending http request without context.Context
+    - scopelint        # Scopelint checks for unpinned variables in go programs
+    - staticcheck      # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
+    - structcheck      # Finds unused struct fields
+    - stylecheck       # Stylecheck is a replacement for golint
+    - typecheck        # Like the front-end of a Go compiler, parses and type-checks Go code
+    - unconvert        # Remove unnecessary type conversions
+    - unparam          # Reports unused function parameters
+    - unused           # Checks Go code for unused constants, variables, functions and types
+    - varcheck         # Finds unused global variables and constants
+    - whitespace       # Tool for detection of leading and trailing whitespace
+  disable:
+    - funlen           # Tool for detection of long functions
+    - gocyclo          # Computes and checks the cyclomatic complexity of functions
+    - godot            # Check if comments end in a period
+    - gomnd            # An analyzer to detect magic numbers.
+    - lll              # Reports long lines
+    - maligned         # Tool to detect Go structs that would take less memory if their fields were sorted
+    - nestif           # Reports deeply nested if statements
+    - nlreturn         # nlreturn checks for a new line before return and branch statements to increase code clarity
+    - nolintlint       # Reports ill-formed or insufficient nolint directives
+    - prealloc         # Finds slice declarations that could potentially be preallocated
+    - rowserrcheck     # checks whether Err of rows is checked successfully
+    - sqlclosecheck    # Checks that sql.Rows and sql.Stmt are closed.
+    - testpackage      # linter that makes you use a separate _test package
+    - wsl              # Whitespace Linter - Forces you to use empty lines!
+
+issues:
+  exclude-rules:
+    # Allow complex tests, better to be self contained
+    - path: _test\.go
+      linters:
+        - gocognit
+
+    # Allow complex main function in examples
+    - path: examples
+      text: "of func `main` is high"
+      linters:
+        - gocognit
 
 run:
   skip-dirs-use-default: false
diff --git a/README.md b/README.md
index d3c7d58..84c4c09 100644
--- a/README.md
+++ b/README.md
@@ -143,6 +143,7 @@ Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contribu
 * [bjdgyc](https://github.com/bjdgyc)
 * [Jeffrey Stoke (Jeff Ctor)](https://github.com/jeffreystoke) - *Fragmentbuffer Fix*
 * [Frank Olbricht](https://github.com/folbricht)
+* [ZHENK](https://github.com/scorpionknifes)
 
 ### License
 MIT License - see [LICENSE](LICENSE) for full text
diff --git a/cipher_suite.go b/cipher_suite.go
index c89df11..073d2ba 100644
--- a/cipher_suite.go
+++ b/cipher_suite.go
@@ -12,25 +12,23 @@ type CipherSuiteID uint16
 // Supported Cipher Suites
 const (
 	// AES-128-CCM
-	TLS_ECDHE_ECDSA_WITH_AES_128_CCM   CipherSuiteID = 0xc0ac
-	TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 CipherSuiteID = 0xc0ae
+	TLS_ECDHE_ECDSA_WITH_AES_128_CCM   CipherSuiteID = 0xc0ac //nolint:golint,stylecheck
+	TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 CipherSuiteID = 0xc0ae //nolint:golint,stylecheck
 
 	// AES-128-GCM-SHA256
-	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 CipherSuiteID = 0xc02b
-	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256   CipherSuiteID = 0xc02f
+	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 CipherSuiteID = 0xc02b //nolint:golint,stylecheck
+	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256   CipherSuiteID = 0xc02f //nolint:golint,stylecheck
 
 	// AES-256-CBC-SHA
-	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA CipherSuiteID = 0xc00a
-	TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA   CipherSuiteID = 0xc014
+	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA CipherSuiteID = 0xc00a //nolint:golint,stylecheck
+	TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA   CipherSuiteID = 0xc014 //nolint:golint,stylecheck
 
-	TLS_PSK_WITH_AES_128_CCM        CipherSuiteID = 0xc0a4
-	TLS_PSK_WITH_AES_128_CCM_8      CipherSuiteID = 0xc0a8
-	TLS_PSK_WITH_AES_128_GCM_SHA256 CipherSuiteID = 0x00a8
+	TLS_PSK_WITH_AES_128_CCM        CipherSuiteID = 0xc0a4 //nolint:golint,stylecheck
+	TLS_PSK_WITH_AES_128_CCM_8      CipherSuiteID = 0xc0a8 //nolint:golint,stylecheck
+	TLS_PSK_WITH_AES_128_GCM_SHA256 CipherSuiteID = 0x00a8 //nolint:golint,stylecheck
 )
 
-var (
-	_ = allCipherSuites() // Necessary until this function isn't only used by Go 1.14
-)
+var _ = allCipherSuites() // Necessary until this function isn't only used by Go 1.14
 
 func (c CipherSuiteID) String() string {
 	switch c {
diff --git a/cipher_suite_aes_128_ccm.go b/cipher_suite_aes_128_ccm.go
index cdff9b7..4f7c8ce 100644
--- a/cipher_suite_aes_128_ccm.go
+++ b/cipher_suite_aes_128_ccm.go
@@ -3,6 +3,7 @@ package dtls
 import (
 	"crypto/sha256"
 	"errors"
+	"fmt"
 	"hash"
 	"sync/atomic"
 )
@@ -71,10 +72,12 @@ func (c *cipherSuiteAes128Ccm) init(masterSecret, clientRandom, serverRandom []b
 	return err
 }
 
+var errCipherSuiteNotInit = errors.New("CipherSuite has not been initialized")
+
 func (c *cipherSuiteAes128Ccm) encrypt(pkt *recordLayer, raw []byte) ([]byte, error) {
 	ccm := c.ccm.Load()
 	if ccm == nil { // !c.isInitialized()
-		return nil, errors.New("CipherSuite has not been initialized, unable to encrypt")
+		return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit)
 	}
 
 	return ccm.(*cryptoCCM).encrypt(pkt, raw)
@@ -83,7 +86,7 @@ func (c *cipherSuiteAes128Ccm) encrypt(pkt *recordLayer, raw []byte) ([]byte, er
 func (c *cipherSuiteAes128Ccm) decrypt(raw []byte) ([]byte, error) {
 	ccm := c.ccm.Load()
 	if ccm == nil { // !c.isInitialized()
-		return nil, errors.New("CipherSuite has not been initialized, unable to decrypt ")
+		return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit)
 	}
 
 	return ccm.(*cryptoCCM).decrypt(raw)
diff --git a/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_gcm_sha256.go b/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_gcm_sha256.go
index d4ffd7e..d974f14 100644
--- a/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_gcm_sha256.go
+++ b/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_gcm_sha256.go
@@ -2,7 +2,7 @@ package dtls
 
 import (
 	"crypto/sha256"
-	"errors"
+	"fmt"
 	"hash"
 	"sync/atomic"
 )
@@ -61,7 +61,7 @@ func (c *cipherSuiteTLSEcdheEcdsaWithAes128GcmSha256) init(masterSecret, clientR
 func (c *cipherSuiteTLSEcdheEcdsaWithAes128GcmSha256) encrypt(pkt *recordLayer, raw []byte) ([]byte, error) {
 	gcm := c.gcm.Load()
 	if gcm == nil { // !c.isInitialized()
-		return nil, errors.New("CipherSuite has not been initialized, unable to encrypt")
+		return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit)
 	}
 
 	return gcm.(*cryptoGCM).encrypt(pkt, raw)
@@ -70,7 +70,7 @@ func (c *cipherSuiteTLSEcdheEcdsaWithAes128GcmSha256) encrypt(pkt *recordLayer,
 func (c *cipherSuiteTLSEcdheEcdsaWithAes128GcmSha256) decrypt(raw []byte) ([]byte, error) {
 	gcm := c.gcm.Load()
 	if gcm == nil { // !c.isInitialized()
-		return nil, errors.New("CipherSuite has not been initialized, unable to decrypt ")
+		return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit)
 	}
 
 	return gcm.(*cryptoGCM).decrypt(raw)
diff --git a/cipher_suite_tls_ecdhe_ecdsa_with_aes_256_cbc_sha.go b/cipher_suite_tls_ecdhe_ecdsa_with_aes_256_cbc_sha.go
index 25f2942..56543a5 100644
--- a/cipher_suite_tls_ecdhe_ecdsa_with_aes_256_cbc_sha.go
+++ b/cipher_suite_tls_ecdhe_ecdsa_with_aes_256_cbc_sha.go
@@ -2,7 +2,7 @@ package dtls
 
 import (
 	"crypto/sha256"
-	"errors"
+	"fmt"
 	"hash"
 	"sync/atomic"
 )
@@ -67,7 +67,7 @@ func (c *cipherSuiteTLSEcdheEcdsaWithAes256CbcSha) init(masterSecret, clientRand
 func (c *cipherSuiteTLSEcdheEcdsaWithAes256CbcSha) encrypt(pkt *recordLayer, raw []byte) ([]byte, error) {
 	cbc := c.cbc.Load()
 	if cbc == nil { // !c.isInitialized()
-		return nil, errors.New("CipherSuite has not been initialized, unable to encrypt")
+		return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit)
 	}
 
 	return cbc.(*cryptoCBC).encrypt(pkt, raw)
@@ -76,7 +76,7 @@ func (c *cipherSuiteTLSEcdheEcdsaWithAes256CbcSha) encrypt(pkt *recordLayer, raw
 func (c *cipherSuiteTLSEcdheEcdsaWithAes256CbcSha) decrypt(raw []byte) ([]byte, error) {
 	cbc := c.cbc.Load()
 	if cbc == nil { // !c.isInitialized()
-		return nil, errors.New("CipherSuite has not been initialized, unable to decrypt ")
+		return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit)
 	}
 
 	return cbc.(*cryptoCBC).decrypt(raw)
diff --git a/client_certificate_type.go b/client_certificate_type.go
index 8eb3526..78f6968 100644
--- a/client_certificate_type.go
+++ b/client_certificate_type.go
@@ -8,7 +8,9 @@ const (
 	clientCertificateTypeECDSASign clientCertificateType = 64
 )
 
-var clientCertificateTypes = map[clientCertificateType]bool{
-	clientCertificateTypeRSASign:   true,
-	clientCertificateTypeECDSASign: true,
+func clientCertificateTypes() map[clientCertificateType]bool {
+	return map[clientCertificateType]bool{
+		clientCertificateTypeRSASign:   true,
+		clientCertificateTypeECDSASign: true,
+	}
 }
diff --git a/compression_method.go b/compression_method.go
index 15d7aec..4727386 100644
--- a/compression_method.go
+++ b/compression_method.go
@@ -10,12 +10,16 @@ type compressionMethod struct {
 	id compressionMethodID
 }
 
-var compressionMethods = map[compressionMethodID]*compressionMethod{
-	compressionMethodNull: {id: compressionMethodNull},
+func compressionMethods() map[compressionMethodID]*compressionMethod {
+	return map[compressionMethodID]*compressionMethod{
+		compressionMethodNull: {id: compressionMethodNull},
+	}
 }
 
-var defaultCompressionMethods = []*compressionMethod{
-	compressionMethods[compressionMethodNull],
+func defaultCompressionMethods() []*compressionMethod {
+	return []*compressionMethod{
+		compressionMethods()[compressionMethodNull],
+	}
 }
 
 func decodeCompressionMethods(buf []byte) ([]*compressionMethod, error) {
@@ -29,7 +33,7 @@ func decodeCompressionMethods(buf []byte) ([]*compressionMethod, error) {
 			return nil, errBufferTooSmall
 		}
 		id := compressionMethodID(buf[i+1])
-		if compressionMethod, ok := compressionMethods[id]; ok {
+		if compressionMethod, ok := compressionMethods()[id]; ok {
 			c = append(c, compressionMethod)
 		}
 	}
diff --git a/conn.go b/conn.go
index 2a8e0cc..3205bbd 100644
--- a/conn.go
+++ b/conn.go
@@ -26,11 +26,18 @@ const (
 	defaultReplayProtectionWindow = 64
 )
 
-var invalidKeyingLabels = map[string]bool{
-	"client finished": true,
-	"server finished": true,
-	"master secret":   true,
-	"key expansion":   true,
+var (
+	errApplicationDataEpochZero = errors.New("ApplicationData with epoch of 0")
+	errUnhandledContextType     = errors.New("unhandled contentType")
+)
+
+func invalidKeyingLabels() map[string]bool {
+	return map[string]bool{
+		"client finished": true,
+		"server finished": true,
+		"master secret":   true,
+		"key expansion":   true,
+	}
 }
 
 // Conn represents a DTLS connection
@@ -537,7 +544,7 @@ func (c *Conn) fragmentHandshake(h *handshake) ([][]byte, error) {
 	return fragmentedHandshakes, nil
 }
 
-var poolReadBuffer = sync.Pool{
+var poolReadBuffer = sync.Pool{ //nolint:gochecknoglobals
 	New: func() interface{} {
 		b := make([]byte, inboundBufferSize)
 		return &b
@@ -621,8 +628,7 @@ func (c *Conn) handleQueuedPackets(ctx context.Context) error {
 	return nil
 }
 
-func (c *Conn) handleIncomingPacket(buf []byte, enqueue bool) (bool, *alert, error) {
-	// TODO: avoid separate unmarshal
+func (c *Conn) handleIncomingPacket(buf []byte, enqueue bool) (bool, *alert, error) { //nolint:gocognit
 	h := &recordLayerHeader{}
 	if err := h.Unmarshal(buf); err != nil {
 		// Decode error must be silently discarded
@@ -733,7 +739,7 @@ func (c *Conn) handleIncomingPacket(buf []byte, enqueue bool) (bool, *alert, err
 		}
 	case *applicationData:
 		if h.epoch == 0 {
-			return false, &alert{alertLevelFatal, alertUnexpectedMessage}, fmt.Errorf("ApplicationData with epoch of 0")
+			return false, &alert{alertLevelFatal, alertUnexpectedMessage}, errApplicationDataEpochZero
 		}
 
 		markPacketAsValid()
@@ -744,7 +750,7 @@ func (c *Conn) handleIncomingPacket(buf []byte, enqueue bool) (bool, *alert, err
 		}
 
 	default:
-		return false, &alert{alertLevelFatal, alertUnexpectedMessage}, fmt.Errorf("unhandled contentType %d", content.contentType())
+		return false, &alert{alertLevelFatal, alertUnexpectedMessage}, fmt.Errorf("%w: %d", errUnhandledContextType, content.contentType())
 	}
 	return false, nil, nil
 }
@@ -780,7 +786,7 @@ func (c *Conn) isHandshakeCompletedSuccessfully() bool {
 	return boolean.bool
 }
 
-func (c *Conn) handshake(ctx context.Context, cfg *handshakeConfig, initialFlight flightVal, initialState handshakeState) error {
+func (c *Conn) handshake(ctx context.Context, cfg *handshakeConfig, initialFlight flightVal, initialState handshakeState) error { //nolint:gocognit
 	c.fsm = newHandshakeFSM(&c.state, c.handshakeCache, cfg, initialFlight)
 
 	done := make(chan struct{})
@@ -805,7 +811,7 @@ func (c *Conn) handshake(ctx context.Context, cfg *handshakeConfig, initialFligh
 	go func() {
 		defer c.handshakeLoopsFinished.Done()
 		err := c.fsm.Run(ctxHs, c, initialState)
-		if err != context.Canceled {
+		if !errors.Is(err, context.Canceled) {
 			select {
 			case firstErr <- err:
 			default:
diff --git a/crypto.go b/crypto.go
index d380a6f..c9124eb 100644
--- a/crypto.go
+++ b/crypto.go
@@ -55,7 +55,7 @@ func generateKeySignature(clientRandom, serverRandom, publicKey []byte, namedCur
 	return nil, errKeySignatureGenerateUnimplemented
 }
 
-func verifyKeySignature(message, remoteKeySignature []byte, hashAlgorithm hashAlgorithm, rawCertificates [][]byte) error {
+func verifyKeySignature(message, remoteKeySignature []byte, hashAlgorithm hashAlgorithm, rawCertificates [][]byte) error { //nolint:dupl
 	if len(rawCertificates) == 0 {
 		return errLengthMismatch
 	}
@@ -88,6 +88,8 @@ func verifyKeySignature(message, remoteKeySignature []byte, hashAlgorithm hashAl
 		case x509.SHA1WithRSA, x509.SHA256WithRSA, x509.SHA384WithRSA, x509.SHA512WithRSA:
 			hashed := hashAlgorithm.digest(message)
 			return rsa.VerifyPKCS1v15(p, hashAlgorithm.cryptoHash(), hashed, remoteKeySignature)
+		default:
+			return errKeySignatureVerifyUnimplemented
 		}
 	}
 
@@ -122,7 +124,7 @@ func generateCertificateVerify(handshakeBodies []byte, privateKey crypto.Private
 	return nil, errInvalidSignatureAlgorithm
 }
 
-func verifyCertificateVerify(handshakeBodies []byte, hashAlgorithm hashAlgorithm, remoteKeySignature []byte, rawCertificates [][]byte) error {
+func verifyCertificateVerify(handshakeBodies []byte, hashAlgorithm hashAlgorithm, remoteKeySignature []byte, rawCertificates [][]byte) error { //nolint:dupl
 	if len(rawCertificates) == 0 {
 		return errLengthMismatch
 	}
@@ -155,6 +157,8 @@ func verifyCertificateVerify(handshakeBodies []byte, hashAlgorithm hashAlgorithm
 		case x509.SHA1WithRSA, x509.SHA256WithRSA, x509.SHA384WithRSA, x509.SHA512WithRSA:
 			hash := hashAlgorithm.digest(handshakeBodies)
 			return rsa.VerifyPKCS1v15(p, hashAlgorithm.cryptoHash(), hash, remoteKeySignature)
+		default:
+			return errKeySignatureVerifyUnimplemented
 		}
 	}
 
diff --git a/crypto_cbc.go b/crypto_cbc.go
index 4bc2031..6a4e7f4 100644
--- a/crypto_cbc.go
+++ b/crypto_cbc.go
@@ -1,11 +1,11 @@
 package dtls
 
-import (
+import ( //nolint:gci
 	"crypto/aes"
 	"crypto/cipher"
 	"crypto/hmac"
 	"crypto/rand"
-	"crypto/sha1" // #nosec
+	"crypto/sha1" //nolint:gosec
 	"encoding/binary"
 )
 
@@ -22,7 +22,7 @@ type cryptoCBC struct {
 }
 
 // Currently hardcoded to be SHA1 only
-var cryptoCBCMacFunc = sha1.New
+var cryptoCBCMacFunc = sha1.New //nolint:gochecknoglobals
 
 func newCryptoCBC(localKey, localWriteIV, localMac, remoteKey, remoteWriteIV, remoteMac []byte) (*cryptoCBC, error) {
 	writeBlock, err := aes.NewCipher(localKey)
diff --git a/crypto_ccm.go b/crypto_ccm.go
index fe84cd1..e933f00 100644
--- a/crypto_ccm.go
+++ b/crypto_ccm.go
@@ -4,11 +4,14 @@ import (
 	"crypto/aes"
 	"crypto/rand"
 	"encoding/binary"
+	"errors"
 	"fmt"
 
 	"github.com/pion/dtls/v2/pkg/crypto/ccm"
 )
 
+var errDecryptPacket = errors.New("decryptPacket")
+
 type cryptoCCMTagLen int
 
 const (
@@ -91,7 +94,7 @@ func (c *cryptoCCM) decrypt(in []byte) ([]byte, error) {
 	additionalData := generateAEADAdditionalData(&h, len(out)-int(c.tagLen))
 	out, err = c.remoteCCM.Open(out[:0], nonce, out, additionalData)
 	if err != nil {
-		return nil, fmt.Errorf("decryptPacket: %v", err)
+		return nil, fmt.Errorf("%w: %v", errDecryptPacket, err)
 	}
 	return append(in[:recordLayerHeaderSize], out...), nil
 }
diff --git a/crypto_gcm.go b/crypto_gcm.go
index 50a06e6..433326d 100644
--- a/crypto_gcm.go
+++ b/crypto_gcm.go
@@ -8,8 +8,10 @@ import (
 	"fmt"
 )
 
-const cryptoGCMTagLength = 16
-const cryptoGCMNonceLength = 12
+const (
+	cryptoGCMTagLength   = 16
+	cryptoGCMNonceLength = 12
+)
 
 // State needed to handle encrypted input/output
 type cryptoGCM struct {
@@ -86,7 +88,7 @@ func (c *cryptoGCM) decrypt(in []byte) ([]byte, error) {
 	additionalData := generateAEADAdditionalData(&h, len(out)-cryptoGCMTagLength)
 	out, err = c.remoteGCM.Open(out[:0], nonce, out, additionalData)
 	if err != nil {
-		return nil, fmt.Errorf("decryptPacket: %v", err)
+		return nil, fmt.Errorf("%w: %v", errDecryptPacket, err)
 	}
 	return append(in[:recordLayerHeaderSize], out...), nil
 }
diff --git a/curve_type.go b/curve_type.go
index 37771f6..9ea103b 100644
--- a/curve_type.go
+++ b/curve_type.go
@@ -7,6 +7,8 @@ const (
 	ellipticCurveTypeNamedCurve ellipticCurveType = 0x03
 )
 
-var ellipticCurveTypes = map[ellipticCurveType]bool{
-	ellipticCurveTypeNamedCurve: true,
+func ellipticCurveTypes() map[ellipticCurveType]bool {
+	return map[ellipticCurveType]bool{
+		ellipticCurveTypeNamedCurve: true,
+	}
 }
diff --git a/errors.go b/errors.go
index 4a36a9e..e551fd6 100644
--- a/errors.go
+++ b/errors.go
@@ -13,68 +13,68 @@ import (
 
 // Typed errors
 var (
-	ErrConnClosed = &FatalError{errors.New("conn is closed")}
+	ErrConnClosed = &FatalError{errors.New("conn is closed")} //nolint:goerr113
 
 	errDeadlineExceeded = &TimeoutError{xerrors.Errorf("read/write timeout: %w", context.DeadlineExceeded)}
 
-	errBufferTooSmall               = &TemporaryError{errors.New("buffer is too small")}
-	errContextUnsupported           = &TemporaryError{errors.New("context is not supported for ExportKeyingMaterial")}
-	errDTLSPacketInvalidLength      = &TemporaryError{errors.New("packet is too short")}
-	errHandshakeInProgress          = &TemporaryError{errors.New("handshake is in progress")}
-	errInvalidContentType           = &TemporaryError{errors.New("invalid content type")}
-	errInvalidMAC                   = &TemporaryError{errors.New("invalid mac")}
-	errInvalidPacketLength          = &TemporaryError{errors.New("packet length and declared length do not match")}
-	errReservedExportKeyingMaterial = &TemporaryError{errors.New("ExportKeyingMaterial can not be used with a reserved label")}
-
-	errCertificateVerifyNoCertificate   = &FatalError{errors.New("client sent certificate verify but we have no certificate to verify")}
-	errCipherSuiteNoIntersection        = &FatalError{errors.New("client+server do not support any shared cipher suites")}
-	errCipherSuiteUnset                 = &FatalError{errors.New("server hello can not be created without a cipher suite")}
-	errClientCertificateNotVerified     = &FatalError{errors.New("client sent certificate but did not verify it")}
-	errClientCertificateRequired        = &FatalError{errors.New("server required client verification, but got none")}
-	errClientNoMatchingSRTPProfile      = &FatalError{errors.New("server responded with SRTP Profile we do not support")}
-	errClientRequiredButNoServerEMS     = &FatalError{errors.New("client required Extended Master Secret extension, but server does not support it")}
-	errCompressionMethodUnset           = &FatalError{errors.New("server hello can not be created without a compression method")}
-	errCookieMismatch                   = &FatalError{errors.New("client+server cookie does not match")}
-	errCookieTooLong                    = &FatalError{errors.New("cookie must not be longer then 255 bytes")}
-	errIdentityNoPSK                    = &FatalError{errors.New("PSK Identity Hint provided but PSK is nil")}
-	errInvalidCertificate               = &FatalError{errors.New("no certificate provided")}
-	errInvalidCipherSpec                = &FatalError{errors.New("cipher spec invalid")}
-	errInvalidCipherSuite               = &FatalError{errors.New("invalid or unknown cipher suite")}
-	errInvalidClientKeyExchange         = &FatalError{errors.New("unable to determine if ClientKeyExchange is a public key or PSK Identity")}
-	errInvalidCompressionMethod         = &FatalError{errors.New("invalid or unknown compression method")}
-	errInvalidECDSASignature            = &FatalError{errors.New("ECDSA signature contained zero or negative values")}
-	errInvalidEllipticCurveType         = &FatalError{errors.New("invalid or unknown elliptic curve type")}
-	errInvalidExtensionType             = &FatalError{errors.New("invalid extension type")}
-	errInvalidHashAlgorithm             = &FatalError{errors.New("invalid hash algorithm")}
-	errInvalidNamedCurve                = &FatalError{errors.New("invalid named curve")}
-	errInvalidPrivateKey                = &FatalError{errors.New("invalid private key type")}
-	errInvalidSNIFormat                 = &FatalError{errors.New("invalid server name format")}
-	errInvalidSignatureAlgorithm        = &FatalError{errors.New("invalid signature algorithm")}
-	errKeySignatureMismatch             = &FatalError{errors.New("expected and actual key signature do not match")}
-	errNilNextConn                      = &FatalError{errors.New("Conn can not be created with a nil nextConn")}
-	errNoAvailableCipherSuites          = &FatalError{errors.New("connection can not be created, no CipherSuites satisfy this Config")}
-	errNoAvailableSignatureSchemes      = &FatalError{errors.New("connection can not be created, no SignatureScheme satisfy this Config")}
-	errNoCertificates                   = &FatalError{errors.New("no certificates configured")}
-	errNoConfigProvided                 = &FatalError{errors.New("no config provided")}
-	errNoSupportedEllipticCurves        = &FatalError{errors.New("client requested zero or more elliptic curves that are not supported by the server")}
-	errUnsupportedProtocolVersion       = &FatalError{errors.New("unsupported protocol version")}
-	errPSKAndCertificate                = &FatalError{errors.New("Certificate and PSK provided")} // nolint:stylecheck
-	errPSKAndIdentityMustBeSetForClient = &FatalError{errors.New("PSK and PSK Identity Hint must both be set for client")}
-	errRequestedButNoSRTPExtension      = &FatalError{errors.New("SRTP support was requested but server did not respond with use_srtp extension")}
-	errServerMustHaveCertificate        = &FatalError{errors.New("Certificate is mandatory for server")} // nolint:stylecheck
-	errServerNoMatchingSRTPProfile      = &FatalError{errors.New("client requested SRTP but we have no matching profiles")}
-	errServerRequiredButNoClientEMS     = &FatalError{errors.New("server requires the Extended Master Secret extension, but the client does not support it")}
-	errVerifyDataMismatch               = &FatalError{errors.New("expected and actual verify data does not match")}
-
-	errHandshakeMessageUnset             = &InternalError{errors.New("handshake message unset, unable to marshal")}
-	errInvalidFlight                     = &InternalError{errors.New("invalid flight number")}
-	errKeySignatureGenerateUnimplemented = &InternalError{errors.New("unable to generate key signature, unimplemented")}
-	errKeySignatureVerifyUnimplemented   = &InternalError{errors.New("unable to verify key signature, unimplemented")}
-	errLengthMismatch                    = &InternalError{errors.New("data length and declared length do not match")}
-	errNotEnoughRoomForNonce             = &InternalError{errors.New("buffer not long enough to contain nonce")}
-	errNotImplemented                    = &InternalError{errors.New("feature has not been implemented yet")}
-	errSequenceNumberOverflow            = &InternalError{errors.New("sequence number overflow")}
-	errUnableToMarshalFragmented         = &InternalError{errors.New("unable to marshal fragmented handshakes")}
+	errBufferTooSmall               = &TemporaryError{errors.New("buffer is too small")}                                        //nolint:goerr113
+	errContextUnsupported           = &TemporaryError{errors.New("context is not supported for ExportKeyingMaterial")}          //nolint:goerr113
+	errDTLSPacketInvalidLength      = &TemporaryError{errors.New("packet is too short")}                                        //nolint:goerr113
+	errHandshakeInProgress          = &TemporaryError{errors.New("handshake is in progress")}                                   //nolint:goerr113
+	errInvalidContentType           = &TemporaryError{errors.New("invalid content type")}                                       //nolint:goerr113
+	errInvalidMAC                   = &TemporaryError{errors.New("invalid mac")}                                                //nolint:goerr113
+	errInvalidPacketLength          = &TemporaryError{errors.New("packet length and declared length do not match")}             //nolint:goerr113
+	errReservedExportKeyingMaterial = &TemporaryError{errors.New("ExportKeyingMaterial can not be used with a reserved label")} //nolint:goerr113
+
+	errCertificateVerifyNoCertificate   = &FatalError{errors.New("client sent certificate verify but we have no certificate to verify")}                      //nolint:goerr113
+	errCipherSuiteNoIntersection        = &FatalError{errors.New("client+server do not support any shared cipher suites")}                                    //nolint:goerr113
+	errCipherSuiteUnset                 = &FatalError{errors.New("server hello can not be created without a cipher suite")}                                   //nolint:goerr113
+	errClientCertificateNotVerified     = &FatalError{errors.New("client sent certificate but did not verify it")}                                            //nolint:goerr113
+	errClientCertificateRequired        = &FatalError{errors.New("server required client verification, but got none")}                                        //nolint:goerr113
+	errClientNoMatchingSRTPProfile      = &FatalError{errors.New("server responded with SRTP Profile we do not support")}                                     //nolint:goerr113
+	errClientRequiredButNoServerEMS     = &FatalError{errors.New("client required Extended Master Secret extension, but server does not support it")}         //nolint:goerr113
+	errCompressionMethodUnset           = &FatalError{errors.New("server hello can not be created without a compression method")}                             //nolint:goerr113
+	errCookieMismatch                   = &FatalError{errors.New("client+server cookie does not match")}                                                      //nolint:goerr113
+	errCookieTooLong                    = &FatalError{errors.New("cookie must not be longer then 255 bytes")}                                                 //nolint:goerr113
+	errIdentityNoPSK                    = &FatalError{errors.New("PSK Identity Hint provided but PSK is nil")}                                                //nolint:goerr113
+	errInvalidCertificate               = &FatalError{errors.New("no certificate provided")}                                                                  //nolint:goerr113
+	errInvalidCipherSpec                = &FatalError{errors.New("cipher spec invalid")}                                                                      //nolint:goerr113
+	errInvalidCipherSuite               = &FatalError{errors.New("invalid or unknown cipher suite")}                                                          //nolint:goerr113
+	errInvalidClientKeyExchange         = &FatalError{errors.New("unable to determine if ClientKeyExchange is a public key or PSK Identity")}                 //nolint:goerr113
+	errInvalidCompressionMethod         = &FatalError{errors.New("invalid or unknown compression method")}                                                    //nolint:goerr113
+	errInvalidECDSASignature            = &FatalError{errors.New("ECDSA signature contained zero or negative values")}                                        //nolint:goerr113
+	errInvalidEllipticCurveType         = &FatalError{errors.New("invalid or unknown elliptic curve type")}                                                   //nolint:goerr113
+	errInvalidExtensionType             = &FatalError{errors.New("invalid extension type")}                                                                   //nolint:goerr113
+	errInvalidHashAlgorithm             = &FatalError{errors.New("invalid hash algorithm")}                                                                   //nolint:goerr113
+	errInvalidNamedCurve                = &FatalError{errors.New("invalid named curve")}                                                                      //nolint:goerr113
+	errInvalidPrivateKey                = &FatalError{errors.New("invalid private key type")}                                                                 //nolint:goerr113
+	errInvalidSNIFormat                 = &FatalError{errors.New("invalid server name format")}                                                               //nolint:goerr113
+	errInvalidSignatureAlgorithm        = &FatalError{errors.New("invalid signature algorithm")}                                                              //nolint:goerr113
+	errKeySignatureMismatch             = &FatalError{errors.New("expected and actual key signature do not match")}                                           //nolint:goerr113
+	errNilNextConn                      = &FatalError{errors.New("Conn can not be created with a nil nextConn")}                                              //nolint:goerr113
+	errNoAvailableCipherSuites          = &FatalError{errors.New("connection can not be created, no CipherSuites satisfy this Config")}                       //nolint:goerr113
+	errNoAvailableSignatureSchemes      = &FatalError{errors.New("connection can not be created, no SignatureScheme satisfy this Config")}                    //nolint:goerr113
+	errNoCertificates                   = &FatalError{errors.New("no certificates configured")}                                                               //nolint:goerr113
+	errNoConfigProvided                 = &FatalError{errors.New("no config provided")}                                                                       //nolint:goerr113
+	errNoSupportedEllipticCurves        = &FatalError{errors.New("client requested zero or more elliptic curves that are not supported by the server")}       //nolint:goerr113
+	errUnsupportedProtocolVersion       = &FatalError{errors.New("unsupported protocol version")}                                                             //nolint:goerr113
+	errPSKAndCertificate                = &FatalError{errors.New("Certificate and PSK provided")}                                                             //nolint:stylecheck
+	errPSKAndIdentityMustBeSetForClient = &FatalError{errors.New("PSK and PSK Identity Hint must both be set for client")}                                    //nolint:goerr113
+	errRequestedButNoSRTPExtension      = &FatalError{errors.New("SRTP support was requested but server did not respond with use_srtp extension")}            //nolint:goerr113
+	errServerMustHaveCertificate        = &FatalError{errors.New("Certificate is mandatory for server")}                                                      //nolint:stylecheck
+	errServerNoMatchingSRTPProfile      = &FatalError{errors.New("client requested SRTP but we have no matching profiles")}                                   //nolint:goerr113
+	errServerRequiredButNoClientEMS     = &FatalError{errors.New("server requires the Extended Master Secret extension, but the client does not support it")} //nolint:goerr113
+	errVerifyDataMismatch               = &FatalError{errors.New("expected and actual verify data does not match")}                                           //nolint:goerr113
+
+	errHandshakeMessageUnset             = &InternalError{errors.New("handshake message unset, unable to marshal")}      //nolint:goerr113
+	errInvalidFlight                     = &InternalError{errors.New("invalid flight number")}                           //nolint:goerr113
+	errKeySignatureGenerateUnimplemented = &InternalError{errors.New("unable to generate key signature, unimplemented")} //nolint:goerr113
+	errKeySignatureVerifyUnimplemented   = &InternalError{errors.New("unable to verify key signature, unimplemented")}   //nolint:goerr113
+	errLengthMismatch                    = &InternalError{errors.New("data length and declared length do not match")}    //nolint:goerr113
+	errNotEnoughRoomForNonce             = &InternalError{errors.New("buffer not long enough to contain nonce")}         //nolint:goerr113
+	errNotImplemented                    = &InternalError{errors.New("feature has not been implemented yet")}            //nolint:goerr113
+	errSequenceNumberOverflow            = &InternalError{errors.New("sequence number overflow")}                        //nolint:goerr113
+	errUnableToMarshalFragmented         = &InternalError{errors.New("unable to marshal fragmented handshakes")}         //nolint:goerr113
 )
 
 // FatalError indicates that the DTLS connection is no longer available.
diff --git a/examples/util/util.go b/examples/util/util.go
index db4aae4..8f53539 100644
--- a/examples/util/util.go
+++ b/examples/util/util.go
@@ -21,6 +21,14 @@ import (
 
 const bufSize = 8192
 
+var (
+	errBlockIsNotPrivateKey  = errors.New("block is not a private key, unable to load key")
+	errUnknownKeyTime        = errors.New("unknown key time in PKCS#8 wrapping, unable to load key")
+	errNoPrivateKeyFound     = errors.New("no private key found, unable to load key")
+	errBlockIsNotCertificate = errors.New("block is not a certificate, unable to load certificates")
+	errNoCertificateFound    = errors.New("no certificate found, unable to load certificates")
+)
+
 // Chat simulates a simple text chat session over the connection
 func Chat(conn io.ReadWriter) {
 	go func() {
@@ -92,7 +100,7 @@ func LoadKey(path string) (crypto.PrivateKey, error) {
 
 	block, _ := pem.Decode(rawData)
 	if block == nil || !strings.HasSuffix(block.Type, "PRIVATE KEY") {
-		return nil, errors.New("block is not a private key, unable to load key")
+		return nil, errBlockIsNotPrivateKey
 	}
 
 	if key, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
@@ -104,7 +112,7 @@ func LoadKey(path string) (crypto.PrivateKey, error) {
 		case *rsa.PrivateKey, *ecdsa.PrivateKey:
 			return key, nil
 		default:
-			return nil, errors.New("unknown key time in PKCS#8 wrapping, unable to load key")
+			return nil, errUnknownKeyTime
 		}
 	}
 
@@ -112,7 +120,7 @@ func LoadKey(path string) (crypto.PrivateKey, error) {
 		return key, nil
 	}
 
-	return nil, errors.New("no private key found, unable to load key")
+	return nil, errNoPrivateKeyFound
 }
 
 // LoadCertificate Load/read certificate(s) from file
@@ -131,7 +139,7 @@ func LoadCertificate(path string) (*tls.Certificate, error) {
 		}
 
 		if block.Type != "CERTIFICATE" {
-			return nil, errors.New("block is not a certificate, unable to load certificates")
+			return nil, errBlockIsNotCertificate
 		}
 
 		certificate.Certificate = append(certificate.Certificate, block.Bytes)
@@ -139,7 +147,7 @@ func LoadCertificate(path string) (*tls.Certificate, error) {
 	}
 
 	if len(certificate.Certificate) == 0 {
-		return nil, errors.New("no certificate found, unable to load certificates")
+		return nil, errNoCertificateFound
 	}
 
 	return &certificate, nil
diff --git a/extension_supported_elliptic_curves.go b/extension_supported_elliptic_curves.go
index 3eef92c..47e531e 100644
--- a/extension_supported_elliptic_curves.go
+++ b/extension_supported_elliptic_curves.go
@@ -46,7 +46,7 @@ func (e *extensionSupportedEllipticCurves) Unmarshal(data []byte) error {
 
 	for i := 0; i < groupCount; i++ {
 		supportedGroupID := namedCurve(binary.BigEndian.Uint16(data[(extensionSupportedGroupsHeaderSize + (i * 2)):]))
-		if _, ok := namedCurves[supportedGroupID]; ok {
+		if _, ok := namedCurves()[supportedGroupID]; ok {
 			e.ellipticCurves = append(e.ellipticCurves, supportedGroupID)
 		}
 	}
diff --git a/extension_supported_signature_algorithms.go b/extension_supported_signature_algorithms.go
index 0a8a7a0..5f83192 100644
--- a/extension_supported_signature_algorithms.go
+++ b/extension_supported_signature_algorithms.go
@@ -46,8 +46,8 @@ func (e *extensionSupportedSignatureAlgorithms) Unmarshal(data []byte) error {
 	for i := 0; i < algorithmCount; i++ {
 		supportedHashAlgorithm := hashAlgorithm(data[extensionSupportedSignatureAlgorithmsHeaderSize+(i*2)])
 		supportedSignatureAlgorithm := signatureAlgorithm(data[extensionSupportedSignatureAlgorithmsHeaderSize+(i*2)+1])
-		if _, ok := hashAlgorithms[supportedHashAlgorithm]; ok {
-			if _, ok := signatureAlgorithms[supportedSignatureAlgorithm]; ok {
+		if _, ok := hashAlgorithms()[supportedHashAlgorithm]; ok {
+			if _, ok := signatureAlgorithms()[supportedSignatureAlgorithm]; ok {
 				e.signatureHashAlgorithms = append(e.signatureHashAlgorithms, signatureHashAlgorithm{
 					supportedHashAlgorithm,
 					supportedSignatureAlgorithm,
diff --git a/extension_use_srtp.go b/extension_use_srtp.go
index f89a671..0805f49 100644
--- a/extension_use_srtp.go
+++ b/extension_use_srtp.go
@@ -45,7 +45,7 @@ func (e *extensionUseSRTP) Unmarshal(data []byte) error {
 
 	for i := 0; i < profileCount; i++ {
 		supportedProfile := SRTPProtectionProfile(binary.BigEndian.Uint16(data[(extensionUseSRTPHeaderSize + (i * 2)):]))
-		if _, ok := srtpProtectionProfiles[supportedProfile]; ok {
+		if _, ok := srtpProtectionProfiles()[supportedProfile]; ok {
 			e.protectionProfiles = append(e.protectionProfiles, supportedProfile)
 		}
 	}
diff --git a/flight1handler.go b/flight1handler.go
index e69f5ee..a957fbf 100644
--- a/flight1handler.go
+++ b/flight1handler.go
@@ -92,9 +92,10 @@ func flight1Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
 						cookie:             state.cookie,
 						random:             state.localRandom,
 						cipherSuites:       cfg.localCipherSuites,
-						compressionMethods: defaultCompressionMethods,
+						compressionMethods: defaultCompressionMethods(),
 						extensions:         extensions,
-					}},
+					},
+				},
 			},
 		},
 	}, nil, nil
diff --git a/flight3handler.go b/flight3handler.go
index 132c442..d5b7aeb 100644
--- a/flight3handler.go
+++ b/flight3handler.go
@@ -4,7 +4,7 @@ import (
 	"context"
 )
 
-func flight3Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert, error) {
+func flight3Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert, error) { //nolint:gocognit
 	// Clients may receive multiple HelloVerifyRequest messages with different cookies.
 	// Clients SHOULD handle this by sending a new ClientHello with a cookie in response
 	// to the new HelloVerifyRequest. RFC 6347 Section 4.2.1
@@ -164,9 +164,10 @@ func flight3Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
 						cookie:             state.cookie,
 						random:             state.localRandom,
 						cipherSuites:       cfg.localCipherSuites,
-						compressionMethods: defaultCompressionMethods,
+						compressionMethods: defaultCompressionMethods(),
 						extensions:         extensions,
-					}},
+					},
+				},
 			},
 		},
 	}, nil, nil
diff --git a/flight4handler.go b/flight4handler.go
index 5149f6d..e23cce4 100644
--- a/flight4handler.go
+++ b/flight4handler.go
@@ -5,7 +5,7 @@ import (
 	"crypto/x509"
 )
 
-func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert, error) {
+func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert, error) { //nolint:gocognit
 	seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence,
 		handshakeCachePullRule{handshakeTypeCertificate, cfg.initialEpoch, true, true},
 		handshakeCachePullRule{handshakeTypeClientKeyExchange, cfg.initialEpoch, true, false},
@@ -151,6 +151,8 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh
 		if !state.peerCertificatesVerified {
 			return 0, &alert{alertLevelFatal, alertBadCertificate}, errClientCertificateNotVerified
 		}
+	case NoClientCert, RequestClientCert:
+		return flight6, nil, nil
 	}
 
 	return flight6, nil, nil
@@ -192,9 +194,10 @@ func flight4Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
 					version:           protocolVersion1_2,
 					random:            state.localRandom,
 					cipherSuite:       state.cipherSuite,
-					compressionMethod: defaultCompressionMethods[0],
+					compressionMethod: defaultCompressionMethods()[0],
 					extensions:        extensions,
-				}},
+				},
+			},
 		},
 	})
 
@@ -212,7 +215,8 @@ func flight4Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
 				content: &handshake{
 					handshakeMessage: &handshakeMessageCertificate{
 						certificate: certificate.Certificate,
-					}},
+					},
+				},
 			},
 		})
 
@@ -244,7 +248,8 @@ func flight4Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
 						hashAlgorithm:      signatureHashAlgo.hash,
 						signatureAlgorithm: signatureHashAlgo.signature,
 						signature:          state.localKeySignature,
-					}},
+					},
+				},
 			},
 		})
 
@@ -277,7 +282,8 @@ func flight4Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
 				content: &handshake{
 					handshakeMessage: &handshakeMessageServerKeyExchange{
 						identityHint: cfg.localPSKIdentityHint,
-					}},
+					},
+				},
 			},
 		})
 	}
diff --git a/flight5handler.go b/flight5handler.go
index 8ee63ba..bb7c31b 100644
--- a/flight5handler.go
+++ b/flight5handler.go
@@ -44,7 +44,7 @@ func flight5Parse(ctx context.Context, c flightConn, state *State, cache *handsh
 	return flight5, nil, nil
 }
 
-func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert, error) {
+func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert, error) { //nolint:gocognit
 	var certBytes [][]byte
 	var privateKey crypto.PrivateKey
 	if len(cfg.localCertificates) > 0 {
@@ -68,7 +68,8 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
 					content: &handshake{
 						handshakeMessage: &handshakeMessageCertificate{
 							certificate: certBytes,
-						}},
+						},
+					},
 				},
 			})
 	}
@@ -177,7 +178,8 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
 						hashAlgorithm:      signatureHashAlgo.hash,
 						signatureAlgorithm: signatureHashAlgo.signature,
 						signature:          state.localCertificatesVerify,
-					}},
+					},
+				},
 			},
 		}
 		pkts = append(pkts, p)
@@ -236,7 +238,8 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
 				content: &handshake{
 					handshakeMessage: &handshakeMessageFinished{
 						verifyData: state.localVerifyData,
-					}},
+					},
+				},
 			},
 			shouldEncrypt:            true,
 			resetLocalSequenceNumber: true,
@@ -245,7 +248,7 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
 	return pkts, nil, nil
 }
 
-func initalizeCipherSuite(state *State, cache *handshakeCache, cfg *handshakeConfig, h *handshakeMessageServerKeyExchange, sendingPlainText []byte) (*alert, error) {
+func initalizeCipherSuite(state *State, cache *handshakeCache, cfg *handshakeConfig, h *handshakeMessageServerKeyExchange, sendingPlainText []byte) (*alert, error) { //nolint:gocognit
 	if state.cipherSuite.isInitialized() {
 		return nil, nil
 	}
diff --git a/flight6handler.go b/flight6handler.go
index 4f3a864..3884d78 100644
--- a/flight6handler.go
+++ b/flight6handler.go
@@ -65,7 +65,8 @@ func flight6Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
 				content: &handshake{
 					handshakeMessage: &handshakeMessageFinished{
 						verifyData: state.localVerifyData,
-					}},
+					},
+				},
 			},
 			shouldEncrypt:            true,
 			resetLocalSequenceNumber: true,
diff --git a/handshake_cache.go b/handshake_cache.go
index 90da29e..3ca5495 100644
--- a/handshake_cache.go
+++ b/handshake_cache.go
@@ -28,7 +28,7 @@ func newHandshakeCache() *handshakeCache {
 	return &handshakeCache{}
 }
 
-func (h *handshakeCache) push(data []byte, epoch, messageSequence uint16, typ handshakeType, isClient bool) bool {
+func (h *handshakeCache) push(data []byte, epoch, messageSequence uint16, typ handshakeType, isClient bool) bool { //nolint
 	h.mu.Lock()
 	defer h.mu.Unlock()
 
diff --git a/handshake_message_certificate_request.go b/handshake_message_certificate_request.go
index eafe174..d23a7f1 100644
--- a/handshake_message_certificate_request.go
+++ b/handshake_message_certificate_request.go
@@ -57,7 +57,7 @@ func (h *handshakeMessageCertificateRequest) Unmarshal(data []byte) error {
 
 	for i := 0; i < certificateTypesLength; i++ {
 		certType := clientCertificateType(data[offset+i])
-		if _, ok := clientCertificateTypes[certType]; ok {
+		if _, ok := clientCertificateTypes()[certType]; ok {
 			h.certificateTypes = append(h.certificateTypes, certType)
 		}
 	}
@@ -79,9 +79,9 @@ func (h *handshakeMessageCertificateRequest) Unmarshal(data []byte) error {
 		hash := hashAlgorithm(data[offset+i])
 		signature := signatureAlgorithm(data[offset+i+1])
 
-		if _, ok := hashAlgorithms[hash]; !ok {
+		if _, ok := hashAlgorithms()[hash]; !ok {
 			continue
-		} else if _, ok := signatureAlgorithms[signature]; !ok {
+		} else if _, ok := signatureAlgorithms()[signature]; !ok {
 			continue
 		}
 		h.signatureHashAlgorithms = append(h.signatureHashAlgorithms, signatureHashAlgorithm{signature: signature, hash: hash})
diff --git a/handshake_message_certificate_verify.go b/handshake_message_certificate_verify.go
index 2a45eb4..128c9b8 100644
--- a/handshake_message_certificate_verify.go
+++ b/handshake_message_certificate_verify.go
@@ -32,12 +32,12 @@ func (h *handshakeMessageCertificateVerify) Unmarshal(data []byte) error {
 	}
 
 	h.hashAlgorithm = hashAlgorithm(data[0])
-	if _, ok := hashAlgorithms[h.hashAlgorithm]; !ok {
+	if _, ok := hashAlgorithms()[h.hashAlgorithm]; !ok {
 		return errInvalidHashAlgorithm
 	}
 
 	h.signatureAlgorithm = signatureAlgorithm(data[1])
-	if _, ok := signatureAlgorithms[h.signatureAlgorithm]; !ok {
+	if _, ok := signatureAlgorithms()[h.signatureAlgorithm]; !ok {
 		return errInvalidSignatureAlgorithm
 	}
 
diff --git a/handshake_message_server_hello.go b/handshake_message_server_hello.go
index 5be0159..3251c50 100644
--- a/handshake_message_server_hello.go
+++ b/handshake_message_server_hello.go
@@ -81,7 +81,7 @@ func (h *handshakeMessageServerHello) Unmarshal(data []byte) error {
 	if len(data) < currOffset {
 		return errBufferTooSmall
 	}
-	if compressionMethod, ok := compressionMethods[compressionMethodID(data[currOffset])]; ok {
+	if compressionMethod, ok := compressionMethods()[compressionMethodID(data[currOffset])]; ok {
 		h.compressionMethod = compressionMethod
 		currOffset++
 	} else {
diff --git a/handshake_message_server_key_exchange.go b/handshake_message_server_key_exchange.go
index 6d01158..f9a1170 100644
--- a/handshake_message_server_key_exchange.go
+++ b/handshake_message_server_key_exchange.go
@@ -52,7 +52,7 @@ func (h *handshakeMessageServerKeyExchange) Unmarshal(data []byte) error {
 		return nil
 	}
 
-	if _, ok := ellipticCurveTypes[ellipticCurveType(data[0])]; ok {
+	if _, ok := ellipticCurveTypes()[ellipticCurveType(data[0])]; ok {
 		h.ellipticCurveType = ellipticCurveType(data[0])
 	} else {
 		return errInvalidEllipticCurveType
@@ -62,7 +62,7 @@ func (h *handshakeMessageServerKeyExchange) Unmarshal(data []byte) error {
 		return errBufferTooSmall
 	}
 	h.namedCurve = namedCurve(binary.BigEndian.Uint16(data[1:3]))
-	if _, ok := namedCurves[h.namedCurve]; !ok {
+	if _, ok := namedCurves()[h.namedCurve]; !ok {
 		return errInvalidNamedCurve
 	}
 	if len(data) < 4 {
@@ -79,7 +79,7 @@ func (h *handshakeMessageServerKeyExchange) Unmarshal(data []byte) error {
 		return errBufferTooSmall
 	}
 	h.hashAlgorithm = hashAlgorithm(data[offset])
-	if _, ok := hashAlgorithms[h.hashAlgorithm]; !ok {
+	if _, ok := hashAlgorithms()[h.hashAlgorithm]; !ok {
 		return errInvalidHashAlgorithm
 	}
 	offset++
@@ -87,7 +87,7 @@ func (h *handshakeMessageServerKeyExchange) Unmarshal(data []byte) error {
 		return errBufferTooSmall
 	}
 	h.signatureAlgorithm = signatureAlgorithm(data[offset])
-	if _, ok := signatureAlgorithms[h.signatureAlgorithm]; !ok {
+	if _, ok := signatureAlgorithms()[h.signatureAlgorithm]; !ok {
 		return errInvalidSignatureAlgorithm
 	}
 	offset++
diff --git a/handshake_random.go b/handshake_random.go
index 479132e..f0ad28f 100644
--- a/handshake_random.go
+++ b/handshake_random.go
@@ -6,8 +6,10 @@ import (
 	"time"
 )
 
-const randomBytesLength = 28
-const handshakeRandomLength = randomBytesLength + 4
+const (
+	randomBytesLength     = 28
+	handshakeRandomLength = randomBytesLength + 4
+)
 
 // https://tools.ietf.org/html/rfc4346#section-7.4.1.2
 type handshakeRandom struct {
diff --git a/handshaker.go b/handshaker.go
index a802d20..6c6c541 100644
--- a/handshaker.go
+++ b/handshaker.go
@@ -230,7 +230,7 @@ func (s *handshakeFSM) send(ctx context.Context, c flightConn) (handshakeState,
 	return handshakeWaiting, nil
 }
 
-func (s *handshakeFSM) wait(ctx context.Context, c flightConn) (handshakeState, error) {
+func (s *handshakeFSM) wait(ctx context.Context, c flightConn) (handshakeState, error) { //nolint:gocognit
 	parse, errFlight := s.currentFlight.getFlightParser()
 	if errFlight != nil {
 		if alertErr := c.notify(ctx, alertLevelFatal, alertInternalError); alertErr != nil {
diff --git a/hash_algorithm.go b/hash_algorithm.go
index 29ac2da..b659b36 100644
--- a/hash_algorithm.go
+++ b/hash_algorithm.go
@@ -1,9 +1,9 @@
 package dtls
 
-import (
+import ( //nolint:gci
 	"crypto"
-	"crypto/md5"  // #nosec
-	"crypto/sha1" // #nosec
+	"crypto/md5"  //nolint:gosec
+	"crypto/sha1" //nolint:gosec
 	"crypto/sha256"
 	"crypto/sha512"
 )
@@ -103,12 +103,14 @@ func (h hashAlgorithm) cryptoHash() crypto.Hash {
 	}
 }
 
-var hashAlgorithms = map[hashAlgorithm]struct{}{
-	hashAlgorithmMD5:     {},
-	hashAlgorithmSHA1:    {},
-	hashAlgorithmSHA224:  {},
-	hashAlgorithmSHA256:  {},
-	hashAlgorithmSHA384:  {},
-	hashAlgorithmSHA512:  {},
-	hashAlgorithmEd25519: {},
+func hashAlgorithms() map[hashAlgorithm]struct{} {
+	return map[hashAlgorithm]struct{}{
+		hashAlgorithmMD5:     {},
+		hashAlgorithmSHA1:    {},
+		hashAlgorithmSHA224:  {},
+		hashAlgorithmSHA256:  {},
+		hashAlgorithmSHA384:  {},
+		hashAlgorithmSHA512:  {},
+		hashAlgorithmEd25519: {},
+	}
 }
diff --git a/internal/net/connctx/connctx.go b/internal/net/connctx/connctx.go
index 3948994..7884510 100644
--- a/internal/net/connctx/connctx.go
+++ b/internal/net/connctx/connctx.go
@@ -32,7 +32,7 @@ type connCtx struct {
 	writeMu   sync.Mutex
 }
 
-var veryOld = time.Unix(0, 1)
+var veryOld = time.Unix(0, 1) //nolint:gochecknoglobals
 
 // New creates a new ConnCtx wrapping given net.Conn.
 func New(conn net.Conn) ConnCtx {
diff --git a/internal/net/dpipe/dpipe.go b/internal/net/dpipe/dpipe.go
index 9afd512..c68270a 100644
--- a/internal/net/dpipe/dpipe.go
+++ b/internal/net/dpipe/dpipe.go
@@ -57,10 +57,12 @@ func (c *conn) SetDeadline(t time.Time) error {
 	c.writeDeadline.Set(t)
 	return nil
 }
+
 func (c *conn) SetReadDeadline(t time.Time) error {
 	c.readDeadline.Set(t)
 	return nil
 }
+
 func (c *conn) SetWriteDeadline(t time.Time) error {
 	c.writeDeadline.Set(t)
 	return nil
diff --git a/named_curve.go b/named_curve.go
index e14257f..7775bcf 100644
--- a/named_curve.go
+++ b/named_curve.go
@@ -22,14 +22,16 @@ const (
 	namedCurveX25519 namedCurve = 0x001d
 )
 
-var namedCurves = map[namedCurve]bool{
-	namedCurveX25519: true,
-	namedCurveP256:   true,
-	namedCurveP384:   true,
+func namedCurves() map[namedCurve]bool {
+	return map[namedCurve]bool{
+		namedCurveX25519: true,
+		namedCurveP256:   true,
+		namedCurveP384:   true,
+	}
 }
 
 func generateKeypair(c namedCurve) (*namedCurveKeypair, error) {
-	switch c {
+	switch c { //nolint:golint
 	case namedCurveX25519:
 		tmp := make([]byte, 32)
 		if _, err := rand.Read(tmp); err != nil {
@@ -45,8 +47,9 @@ func generateKeypair(c namedCurve) (*namedCurveKeypair, error) {
 		return ellipticCurveKeypair(namedCurveP256, elliptic.P256(), elliptic.P256())
 	case namedCurveP384:
 		return ellipticCurveKeypair(namedCurveP384, elliptic.P384(), elliptic.P384())
+	default:
+		return nil, errInvalidNamedCurve
 	}
-	return nil, errInvalidNamedCurve
 }
 
 func ellipticCurveKeypair(nc namedCurve, c1, c2 elliptic.Curve) (*namedCurveKeypair, error) {
diff --git a/pkg/crypto/ccm/ccm.go b/pkg/crypto/ccm/ccm.go
index 252e632..20e3436 100644
--- a/pkg/crypto/ccm/ccm.go
+++ b/pkg/crypto/ccm/ccm.go
@@ -70,9 +70,9 @@ func (c *ccm) NonceSize() int { return 15 - int(c.L) }
 func (c *ccm) Overhead() int  { return int(c.M) }
 func (c *ccm) MaxLength() int { return maxlen(c.L, c.Overhead()) }
 
-func maxlen(L uint8, tagsize int) int {
-	max := (uint64(1) << (8 * L)) - 1
-	if m64 := uint64(math.MaxInt64) - uint64(tagsize); L > 8 || max > m64 {
+func maxlen(l uint8, tagsize int) int {
+	max := (uint64(1) << (8 * l)) - 1
+	if m64 := uint64(math.MaxInt64) - uint64(tagsize); l > 8 || max > m64 {
 		max = m64 // The maximum lentgh on a 64bit arch
 	}
 	if max != uint64(int(max)) {
@@ -113,9 +113,7 @@ func (c *ccm) cbcData(mac, data []byte) {
 	}
 }
 
-var (
-	errPlaintextTooLong = errors.New("ccm: plaintext too large")
-)
+var errPlaintextTooLong = errors.New("ccm: plaintext too large")
 
 func (c *ccm) tag(nonce, plaintext, adata []byte) ([]byte, error) {
 	var mac [ccmBlockSize]byte
@@ -223,7 +221,7 @@ func (c *ccm) Open(dst, nonce, ciphertext, adata []byte) ([]byte, error) {
 		return nil, errCiphertextTooLong
 	}
 
-	var tag = make([]byte, int(c.M))
+	tag := make([]byte, int(c.M))
 	copy(tag, ciphertext[len(ciphertext)-int(c.M):])
 	ciphertextWithoutTag := ciphertext[:len(ciphertext)-int(c.M)]
 
diff --git a/pkg/crypto/fingerprint/hash.go b/pkg/crypto/fingerprint/hash.go
index 99e7fa5..09107db 100644
--- a/pkg/crypto/fingerprint/hash.go
+++ b/pkg/crypto/fingerprint/hash.go
@@ -7,18 +7,20 @@ import (
 
 var errInvalidHashAlgorithm = errors.New("fingerprint: invalid hash algorithm")
 
-var nameToHash = map[string]crypto.Hash{
-	"md5":     crypto.MD5,    // [RFC3279]
-	"sha-1":   crypto.SHA1,   // [RFC3279]
-	"sha-224": crypto.SHA224, // [RFC4055]
-	"sha-256": crypto.SHA256, // [RFC4055]
-	"sha-384": crypto.SHA384, // [RFC4055]
-	"sha-512": crypto.SHA512, // [RFC4055]
+func nameToHash() map[string]crypto.Hash {
+	return map[string]crypto.Hash{
+		"md5":     crypto.MD5,    // [RFC3279]
+		"sha-1":   crypto.SHA1,   // [RFC3279]
+		"sha-224": crypto.SHA224, // [RFC4055]
+		"sha-256": crypto.SHA256, // [RFC4055]
+		"sha-384": crypto.SHA384, // [RFC4055]
+		"sha-512": crypto.SHA512, // [RFC4055]
+	}
 }
 
 // HashFromString allows looking up a hash algorithm by it's string representation
 func HashFromString(s string) (crypto.Hash, error) {
-	if h, ok := nameToHash[s]; ok {
+	if h, ok := nameToHash()[s]; ok {
 		return h, nil
 	}
 	return 0, errInvalidHashAlgorithm
@@ -26,7 +28,7 @@ func HashFromString(s string) (crypto.Hash, error) {
 
 // StringFromHash allows looking up a string representation of the crypto.Hash.
 func StringFromHash(hash crypto.Hash) (string, error) {
-	for s, h := range nameToHash {
+	for s, h := range nameToHash() {
 		if h == hash {
 			return s, nil
 		}
diff --git a/prf.go b/prf.go
index c83d94b..2d649a1 100644
--- a/prf.go
+++ b/prf.go
@@ -1,9 +1,9 @@
 package dtls
 
-import (
+import ( //nolint:gci
 	"crypto/elliptic"
 	"crypto/hmac"
-	"crypto/sha1" // #nosec
+	"crypto/sha1" //nolint:gosec
 	"encoding/binary"
 	"fmt"
 	"hash"
@@ -74,9 +74,9 @@ func prfPreMasterSecret(publicKey, privateKey []byte, curve namedCurve) ([]byte,
 		return ellipticCurvePreMasterSecret(publicKey, privateKey, elliptic.P256(), elliptic.P256())
 	case namedCurveP384:
 		return ellipticCurvePreMasterSecret(publicKey, privateKey, elliptic.P384(), elliptic.P384())
+	default:
+		return nil, errInvalidNamedCurve
 	}
-
-	return nil, errInvalidNamedCurve
 }
 
 func ellipticCurvePreMasterSecret(publicKey, privateKey []byte, c1, c2 elliptic.Curve) ([]byte, error) {
diff --git a/record_layer_header.go b/record_layer_header.go
index 09e9e14..69d1925 100644
--- a/record_layer_header.go
+++ b/record_layer_header.go
@@ -25,8 +25,10 @@ const (
 	VersionDTLS12 = 0xfefd
 )
 
-var protocolVersion1_0 = protocolVersion{dtls1_0Major, dtls1_0Minor}
-var protocolVersion1_2 = protocolVersion{dtls1_2Major, dtls1_2Minor}
+var (
+	protocolVersion1_0 = protocolVersion{dtls1_0Major, dtls1_0Minor} //nolint:gochecknoglobals
+	protocolVersion1_2 = protocolVersion{dtls1_2Major, dtls1_2Minor} //nolint:gochecknoglobals
+)
 
 // https://tools.ietf.org/html/rfc4346#section-6.2.1
 type protocolVersion struct {
diff --git a/signature_algorithm.go b/signature_algorithm.go
index f215cfc..65191de 100644
--- a/signature_algorithm.go
+++ b/signature_algorithm.go
@@ -9,8 +9,10 @@ const (
 	signatureAlgorithmEd25519 signatureAlgorithm = 7
 )
 
-var signatureAlgorithms = map[signatureAlgorithm]bool{
-	signatureAlgorithmRSA:     true,
-	signatureAlgorithmECDSA:   true,
-	signatureAlgorithmEd25519: true,
+func signatureAlgorithms() map[signatureAlgorithm]bool {
+	return map[signatureAlgorithm]bool{
+		signatureAlgorithmRSA:     true,
+		signatureAlgorithmECDSA:   true,
+		signatureAlgorithmEd25519: true,
+	}
 }
diff --git a/signature_hash_algorithm.go b/signature_hash_algorithm.go
index c01caed..97e53ef 100644
--- a/signature_hash_algorithm.go
+++ b/signature_hash_algorithm.go
@@ -60,13 +60,13 @@ func parseSignatureSchemes(sigs []tls.SignatureScheme, insecureHashes bool) ([]s
 	out := []signatureHashAlgorithm{}
 	for _, ss := range sigs {
 		sig := signatureAlgorithm(ss & 0xFF)
-		if _, ok := signatureAlgorithms[sig]; !ok {
+		if _, ok := signatureAlgorithms()[sig]; !ok {
 			return nil, &FatalError{
 				xerrors.Errorf("SignatureScheme %04x: %w", ss, errInvalidSignatureAlgorithm),
 			}
 		}
 		h := hashAlgorithm(ss >> 8)
-		if _, ok := hashAlgorithms[h]; !ok {
+		if _, ok := hashAlgorithms()[h]; !ok {
 			return nil, &FatalError{
 				xerrors.Errorf("SignatureScheme %04x: %w", ss, errInvalidHashAlgorithm),
 			}
diff --git a/srtp_protection_profile.go b/srtp_protection_profile.go
index 7443519..1d4faa5 100644
--- a/srtp_protection_profile.go
+++ b/srtp_protection_profile.go
@@ -11,9 +11,11 @@ const (
 	SRTP_AEAD_AES_256_GCM       SRTPProtectionProfile = 0x0008 // nolint
 )
 
-var srtpProtectionProfiles = map[SRTPProtectionProfile]bool{
-	SRTP_AES128_CM_HMAC_SHA1_80: true,
-	SRTP_AES128_CM_HMAC_SHA1_32: true,
-	SRTP_AEAD_AES_128_GCM:       true,
-	SRTP_AEAD_AES_256_GCM:       true,
+func srtpProtectionProfiles() map[SRTPProtectionProfile]bool {
+	return map[SRTPProtectionProfile]bool{
+		SRTP_AES128_CM_HMAC_SHA1_80: true,
+		SRTP_AES128_CM_HMAC_SHA1_32: true,
+		SRTP_AEAD_AES_128_GCM:       true,
+		SRTP_AEAD_AES_256_GCM:       true,
+	}
 }
diff --git a/state.go b/state.go
index 7c15dcc..33d2105 100644
--- a/state.go
+++ b/state.go
@@ -170,7 +170,7 @@ func (s *State) ExportKeyingMaterial(label string, context []byte, length int) (
 		return nil, errHandshakeInProgress
 	} else if len(context) != 0 {
 		return nil, errContextUnsupported
-	} else if _, ok := invalidKeyingLabels[label]; ok {
+	} else if _, ok := invalidKeyingLabels()[label]; ok {
 		return nil, errReservedExportKeyingMaterial
 	}
 
diff --git a/util.go b/util.go
index 09de441..b59f6b6 100644
--- a/util.go
+++ b/util.go
@@ -87,7 +87,7 @@ func findMatchingSRTPProfile(a, b []SRTPProtectionProfile) (SRTPProtectionProfil
 	return 0, false
 }
 
-func findMatchingCipherSuite(a, b []cipherSuite) (cipherSuite, bool) {
+func findMatchingCipherSuite(a, b []cipherSuite) (cipherSuite, bool) { //nolint
 	for _, aSuite := range a {
 		for _, bSuite := range b {
 			if aSuite.ID() == bSuite.ID() {


Test patch:
diff --git a/alert_test.go b/alert_test.go
index b61b71b..6db0ba2 100644
--- a/alert_test.go
+++ b/alert_test.go
@@ -1,6 +1,7 @@
 package dtls
 
 import (
+	"errors"
 	"reflect"
 	"testing"
 )
@@ -28,7 +29,7 @@ func TestAlert(t *testing.T) {
 		},
 	} {
 		a := &alert{}
-		if err := a.Unmarshal(test.Data); err != test.WantUnmarshalError {
+		if err := a.Unmarshal(test.Data); !errors.Is(err, test.WantUnmarshalError) {
 			t.Errorf("Unexpected Error %v: exp: %v got: %v", test.Name, test.WantUnmarshalError, err)
 		} else if !reflect.DeepEqual(test.Want, a) {
 			t.Errorf("%q alert.unmarshal: got %v, want %v", test.Name, a, test.Want)
diff --git a/change_cipher_spec_test.go b/change_cipher_spec_test.go
index 1e1a015..682bef6 100644
--- a/change_cipher_spec_test.go
+++ b/change_cipher_spec_test.go
@@ -1,6 +1,7 @@
 package dtls
 
 import (
+	"errors"
 	"reflect"
 	"testing"
 )
@@ -24,7 +25,7 @@ func TestChangeCipherSpecRoundTrip(t *testing.T) {
 
 func TestChangeCipherSpecInvalid(t *testing.T) {
 	c := changeCipherSpec{}
-	if err := c.Unmarshal([]byte{0x00}); err != errInvalidCipherSpec {
+	if err := c.Unmarshal([]byte{0x00}); !errors.Is(err, errInvalidCipherSpec) {
 		t.Errorf("ChangeCipherSpec invalid assert: got %#v, want %#v", err, errInvalidCipherSpec)
 	}
 }
diff --git a/cipher_suite_test.go b/cipher_suite_test.go
index ade6772..df9c10d 100644
--- a/cipher_suite_test.go
+++ b/cipher_suite_test.go
@@ -1,6 +1,7 @@
 package dtls
 
 import (
+	"errors"
 	"testing"
 )
 
@@ -15,10 +16,9 @@ func TestDecodeCipherSuites(t *testing.T) {
 
 	for _, testCase := range testCases {
 		_, err := decodeCipherSuites(testCase.buf)
-		if err != testCase.err {
+		if !errors.Is(err, testCase.err) {
 			t.Fatal("Unexpected error", err)
 		}
-		// todo: compare result
 	}
 }
 
diff --git a/compression_method_test.go b/compression_method_test.go
index d2c6d66..e6a3d50 100644
--- a/compression_method_test.go
+++ b/compression_method_test.go
@@ -1,6 +1,7 @@
 package dtls
 
 import (
+	"errors"
 	"testing"
 )
 
@@ -15,9 +16,8 @@ func TestDecodeCompressionMethods(t *testing.T) {
 
 	for _, testCase := range testCases {
 		_, err := decodeCompressionMethods(testCase.buf)
-		if err != testCase.err {
+		if !errors.Is(err, testCase.err) {
 			t.Fatal("Unexpected error", err)
 		}
-		// todo: compare result
 	}
 }
diff --git a/config_test.go b/config_test.go
index 13e4ac3..65247a1 100644
--- a/config_test.go
+++ b/config_test.go
@@ -4,18 +4,19 @@ import (
 	"crypto/tls"
 	"crypto/x509"
 	"encoding/pem"
+	"errors"
 	"testing"
 
 	"github.com/pion/dtls/v2/pkg/crypto/selfsign"
 )
 
 func TestValidateConfig(t *testing.T) {
-	//Empty config
-	if err := validateConfig(nil); err != errNoConfigProvided {
+	// Empty config
+	if err := validateConfig(nil); !errors.Is(err, errNoConfigProvided) {
 		t.Fatalf("TestValidateConfig: Config validation error exp(%v) failed(%v)", errNoConfigProvided, err)
 	}
 
-	//PSK and Certificate
+	// PSK and Certificate
 	cert, err := selfsign.GenerateSelfSigned()
 	if err != nil {
 		t.Fatalf("TestValidateConfig: Config validation error(%v), self signed certificate not generated", err)
@@ -28,21 +29,21 @@ func TestValidateConfig(t *testing.T) {
 		},
 		Certificates: []tls.Certificate{cert},
 	}
-	if err = validateConfig(config); err != errPSKAndCertificate {
+	if err = validateConfig(config); !errors.Is(err, errPSKAndCertificate) {
 		t.Fatalf("TestValidateConfig: Client error exp(%v) failed(%v)", errPSKAndCertificate, err)
 	}
 
-	//PSK identity hint with not PSK
+	// PSK identity hint with not PSK
 	config = &Config{
 		CipherSuites:    []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
 		PSK:             nil,
 		PSKIdentityHint: []byte{},
 	}
-	if err = validateConfig(config); err != errIdentityNoPSK {
+	if err = validateConfig(config); !errors.Is(err, errIdentityNoPSK) {
 		t.Fatalf("TestValidateConfig: Client error exp(%v) failed(%v)", errIdentityNoPSK, err)
 	}
 
-	//Invalid private key
+	// Invalid private key
 	block, _ := pem.Decode([]byte(rawPrivateKey))
 	rsaKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
 	if err != nil {
@@ -52,7 +53,7 @@ func TestValidateConfig(t *testing.T) {
 		CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
 		Certificates: []tls.Certificate{{Certificate: cert.Certificate, PrivateKey: rsaKey}},
 	}
-	if err = validateConfig(config); err != errInvalidPrivateKey {
+	if err = validateConfig(config); !errors.Is(err, errInvalidPrivateKey) {
 		t.Fatalf("TestValidateConfig: Client error exp(%v) failed(%v)", errInvalidPrivateKey, err)
 	}
 
@@ -61,17 +62,17 @@ func TestValidateConfig(t *testing.T) {
 		CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
 		Certificates: []tls.Certificate{{PrivateKey: cert.PrivateKey}},
 	}
-	if err = validateConfig(config); err != errInvalidCertificate {
+	if err = validateConfig(config); !errors.Is(err, errInvalidCertificate) {
 		t.Fatalf("TestValidateConfig: Client error exp(%v) failed(%v)", errInvalidCertificate, err)
 	}
 
-	//Invalid cipher suites
+	// Invalid cipher suites
 	config = &Config{CipherSuites: []CipherSuiteID{0x0000}}
 	if err = validateConfig(config); err == nil {
 		t.Fatal("TestValidateConfig: Client error expected with invalid CipherSuiteID")
 	}
 
-	//Valid config
+	// Valid config
 	config = &Config{
 		CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
 		Certificates: []tls.Certificate{cert},
diff --git a/conn_test.go b/conn_test.go
index 1edb0b5..45ccdbb 100644
--- a/conn_test.go
+++ b/conn_test.go
@@ -20,6 +20,14 @@ import (
 	"github.com/pion/transport/test"
 )
 
+var (
+	errTestPSKInvalidIdentity = errors.New("TestPSK: Server got invalid identity")
+	errPSKRejected            = errors.New("PSK Rejected")
+	errNotExpectedChain       = errors.New("not expected chain")
+	errExpecedChain           = errors.New("expected chain")
+	errWrongCert              = errors.New("wrong cert")
+)
+
 func TestStressDuplex(t *testing.T) {
 	// Limit runtime in case of deadlocks
 	lim := test.TimeOut(time.Second * 20)
@@ -138,10 +146,10 @@ func TestReadWriteDeadline(t *testing.T) {
 		t.Error(err)
 	}
 
-	if _, err := ca.Write(make([]byte, 100)); err != ErrConnClosed {
+	if _, err := ca.Write(make([]byte, 100)); !errors.Is(err, ErrConnClosed) {
 		t.Errorf("Write must return %v after close, got %v", ErrConnClosed, err)
 	}
-	if _, err := ca.Read(make([]byte, 100)); err != io.EOF {
+	if _, err := ca.Read(make([]byte, 100)); !errors.Is(err, io.EOF) {
 		t.Errorf("Read must return %v after close, got %v", io.EOF, err)
 	}
 }
@@ -165,7 +173,7 @@ func TestSequenceNumberOverflow(t *testing.T) {
 		if _, werr := ca.Write(make([]byte, 100)); werr != nil {
 			t.Errorf("Write must send message with maximum sequence number, but errord: %v", werr)
 		}
-		if _, werr := ca.Write(make([]byte, 100)); werr != errSequenceNumberOverflow {
+		if _, werr := ca.Write(make([]byte, 100)); !errors.Is(werr, errSequenceNumberOverflow) {
 			t.Errorf("Write must abandonsend message with maximum sequence number, but errord: %v", werr)
 		}
 
@@ -199,11 +207,12 @@ func TestSequenceNumberOverflow(t *testing.T) {
 							version:            protocolVersion1_2,
 							cookie:             make([]byte, 64),
 							cipherSuites:       defaultCipherSuites(),
-							compressionMethods: defaultCompressionMethods,
-						}},
+							compressionMethods: defaultCompressionMethods(),
+						},
+					},
 				},
 			},
-		}); werr != errSequenceNumberOverflow {
+		}); !errors.Is(werr, errSequenceNumberOverflow) {
 			t.Errorf("Connection must fail on handshake packet reaches maximum sequence number")
 		}
 
@@ -364,21 +373,21 @@ func TestExportKeyingMaterial(t *testing.T) {
 
 	state := c.ConnectionState()
 	_, err := state.ExportKeyingMaterial(exportLabel, nil, 0)
-	if err != errHandshakeInProgress {
+	if !errors.Is(err, errHandshakeInProgress) {
 		t.Errorf("ExportKeyingMaterial when epoch == 0: expected '%s' actual '%s'", errHandshakeInProgress, err)
 	}
 
 	c.setLocalEpoch(1)
 	state = c.ConnectionState()
 	_, err = state.ExportKeyingMaterial(exportLabel, []byte{0x00}, 0)
-	if err != errContextUnsupported {
+	if !errors.Is(err, errContextUnsupported) {
 		t.Errorf("ExportKeyingMaterial with context: expected '%s' actual '%s'", errContextUnsupported, err)
 	}
 
-	for k := range invalidKeyingLabels {
+	for k := range invalidKeyingLabels() {
 		state = c.ConnectionState()
 		_, err = state.ExportKeyingMaterial(k, nil, 0)
-		if err != errReservedExportKeyingMaterial {
+		if !errors.Is(err, errReservedExportKeyingMaterial) {
 			t.Errorf("ExportKeyingMaterial reserved label: expected '%s' actual '%s'", errReservedExportKeyingMaterial, err)
 		}
 	}
@@ -456,7 +465,7 @@ func TestPSK(t *testing.T) {
 			config := &Config{
 				PSK: func(hint []byte) ([]byte, error) {
 					if !bytes.Equal(clientIdentity, hint) {
-						return nil, fmt.Errorf("TestPSK: Server got invalid identity expected(% 02x) actual(% 02x)", clientIdentity, hint)
+						return nil, fmt.Errorf("%w: expected(% 02x) actual(% 02x)", errTestPSKInvalidIdentity, clientIdentity, hint)
 					}
 					return []byte{0xAB, 0xC1, 0x23}, nil
 				},
@@ -487,7 +496,7 @@ func TestPSKHintFail(t *testing.T) {
 	defer report()
 
 	serverAlertError := &errAlert{&alert{alertLevelFatal, alertInternalError}}
-	pskRejected := errors.New("PSK Rejected")
+	pskRejected := errPSKRejected
 
 	// Limit runtime in case of deadlocks
 	lim := test.TimeOut(time.Second * 20)
@@ -1036,7 +1045,7 @@ func TestServerCertificate(t *testing.T) {
 				clientCfg: &Config{RootCAs: caPool, Certificates: []tls.Certificate{cert}},
 				serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: RequireAnyClientCert, VerifyPeerCertificate: func(cert [][]byte, chain [][]*x509.Certificate) error {
 					if len(chain) != 0 {
-						return errors.New("not expected chain")
+						return errNotExpectedChain
 					}
 					return nil
 				}},
@@ -1045,7 +1054,7 @@ func TestServerCertificate(t *testing.T) {
 				clientCfg: &Config{RootCAs: caPool, Certificates: []tls.Certificate{cert}},
 				serverCfg: &Config{ClientCAs: caPool, Certificates: []tls.Certificate{cert}, ClientAuth: RequireAndVerifyClientCert, VerifyPeerCertificate: func(cert [][]byte, chain [][]*x509.Certificate) error {
 					if len(chain) == 0 {
-						return errors.New("expected chain")
+						return errExpecedChain
 					}
 					return nil
 				}},
@@ -1054,7 +1063,7 @@ func TestServerCertificate(t *testing.T) {
 				clientCfg: &Config{
 					RootCAs: caPool,
 					VerifyPeerCertificate: func([][]byte, [][]*x509.Certificate) error {
-						return errors.New("wrong cert")
+						return errWrongCert
 					},
 				},
 				serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
@@ -1349,9 +1358,10 @@ func TestServerTimeout(t *testing.T) {
 				cookie:             cookie,
 				random:             random,
 				cipherSuites:       cipherSuites,
-				compressionMethods: defaultCompressionMethods,
+				compressionMethods: defaultCompressionMethods(),
 				extensions:         extensions,
-			}},
+			},
+		},
 	}
 
 	packet, err := record.Marshal()
@@ -1462,8 +1472,9 @@ func TestProtocolVersionValidation(t *testing.T) {
 								cookie:             cookie,
 								random:             random,
 								cipherSuites:       []cipherSuite{&cipherSuiteTLSEcdheEcdsaWithAes128GcmSha256{}},
-								compressionMethods: defaultCompressionMethods,
-							}},
+								compressionMethods: defaultCompressionMethods(),
+							},
+						},
 					},
 				},
 			},
@@ -1479,8 +1490,9 @@ func TestProtocolVersionValidation(t *testing.T) {
 								cookie:             cookie,
 								random:             random,
 								cipherSuites:       []cipherSuite{&cipherSuiteTLSEcdheEcdsaWithAes128GcmSha256{}},
-								compressionMethods: defaultCompressionMethods,
-							}},
+								compressionMethods: defaultCompressionMethods(),
+							},
+						},
 					},
 					{
 						recordLayerHeader: recordLayerHeader{
@@ -1496,8 +1508,9 @@ func TestProtocolVersionValidation(t *testing.T) {
 								cookie:             cookie,
 								random:             random,
 								cipherSuites:       []cipherSuite{&cipherSuiteTLSEcdheEcdsaWithAes128GcmSha256{}},
-								compressionMethods: defaultCompressionMethods,
-							}},
+								compressionMethods: defaultCompressionMethods(),
+							},
+						},
 					},
 				},
 			},
@@ -1569,7 +1582,8 @@ func TestProtocolVersionValidation(t *testing.T) {
 							handshakeMessage: &handshakeMessageHelloVerifyRequest{
 								version: protocolVersion1_2,
 								cookie:  cookie,
-							}},
+							},
+						},
 					},
 					{
 						recordLayerHeader: recordLayerHeader{
@@ -1584,9 +1598,10 @@ func TestProtocolVersionValidation(t *testing.T) {
 								version:           protocolVersion{0xfe, 0xff}, // try to downgrade
 								random:            random,
 								cipherSuite:       &cipherSuiteTLSEcdheEcdsaWithAes128GcmSha256{},
-								compressionMethod: defaultCompressionMethods[0],
+								compressionMethod: defaultCompressionMethods()[0],
 							},
-						}},
+						},
+					},
 					{
 						recordLayerHeader: recordLayerHeader{
 							protocolVersion: protocolVersion1_2,
@@ -1597,7 +1612,8 @@ func TestProtocolVersionValidation(t *testing.T) {
 								messageSequence: 2,
 							},
 							handshakeMessage: &handshakeMessageCertificate{},
-						}},
+						},
+					},
 					{
 						recordLayerHeader: recordLayerHeader{
 							protocolVersion: protocolVersion1_2,
@@ -1615,7 +1631,8 @@ func TestProtocolVersionValidation(t *testing.T) {
 								signatureAlgorithm: signatureAlgorithmECDSA,
 								signature:          make([]byte, 64),
 							},
-						}},
+						},
+					},
 					{
 						recordLayerHeader: recordLayerHeader{
 							protocolVersion: protocolVersion1_2,
@@ -1626,7 +1643,8 @@ func TestProtocolVersionValidation(t *testing.T) {
 								messageSequence: 4,
 							},
 							handshakeMessage: &handshakeMessageServerHelloDone{},
-						}},
+						},
+					},
 				},
 			},
 		}
@@ -1721,7 +1739,8 @@ func TestMultipleHelloVerifyRequest(t *testing.T) {
 				handshakeMessage: &handshakeMessageHelloVerifyRequest{
 					version: protocolVersion1_2,
 					cookie:  cookie,
-				}},
+				},
+			},
 		}
 		packet, err := record.Marshal()
 		if err != nil {
diff --git a/e2e/e2e_lossy_test.go b/e2e/e2e_lossy_test.go
index f13038e..92a4074 100644
--- a/e2e/e2e_lossy_test.go
+++ b/e2e/e2e_lossy_test.go
@@ -120,7 +120,7 @@ func TestPionE2ELossy(t *testing.T) {
 			defer lim.Stop()
 
 			rand.Seed(time.Now().UTC().UnixNano())
-			chosenLoss := rand.Intn(9) + test.LossChanceRange
+			chosenLoss := rand.Intn(9) + test.LossChanceRange //nolint:gosec
 			serverDone := make(chan runResult)
 			clientDone := make(chan runResult)
 			br := transportTest.NewBridge()
diff --git a/e2e/e2e_openssl_test.go b/e2e/e2e_openssl_test.go
index 7019190..fd2e60f 100644
--- a/e2e/e2e_openssl_test.go
+++ b/e2e/e2e_openssl_test.go
@@ -26,7 +26,8 @@ func serverOpenSSL(c *comm) {
 		cfg := c.serverConfig
 
 		// create openssl arguments
-		args := []string{"s_server",
+		args := []string{
+			"s_server",
 			"-dtls1_2",
 			"-quiet",
 			"-verify_quiet",
@@ -106,7 +107,8 @@ func clientOpenSSL(c *comm) {
 	cfg := c.clientConfig
 
 	// create openssl arguments
-	args := []string{"s_client",
+	args := []string{
+		"s_client",
 		"-dtls1_2",
 		"-quiet",
 		"-verify_quiet",
@@ -228,6 +230,7 @@ func TestPionOpenSSLE2ESimple(t *testing.T) {
 		testPionE2ESimple(t, serverPion, clientOpenSSL)
 	})
 }
+
 func TestPionOpenSSLE2ESimplePSK(t *testing.T) {
 	t.Run("OpenSSLServer", func(t *testing.T) {
 		testPionE2ESimplePSK(t, serverOpenSSL, clientPion)
@@ -236,6 +239,7 @@ func TestPionOpenSSLE2ESimplePSK(t *testing.T) {
 		testPionE2ESimplePSK(t, serverPion, clientOpenSSL)
 	})
 }
+
 func TestPionOpenSSLE2EMTUs(t *testing.T) {
 	t.Run("OpenSSLServer", func(t *testing.T) {
 		testPionE2EMTUs(t, serverOpenSSL, clientPion)
diff --git a/e2e/e2e_test.go b/e2e/e2e_test.go
index 68a537e..1a77b3b 100644
--- a/e2e/e2e_test.go
+++ b/e2e/e2e_test.go
@@ -19,9 +19,13 @@ import (
 	"github.com/pion/transport/test"
 )
 
-const testMessage = "Hello World"
-const testTimeLimit = 5 * time.Second
-const messageRetry = 200 * time.Millisecond
+const (
+	testMessage   = "Hello World"
+	testTimeLimit = 5 * time.Second
+	messageRetry  = 200 * time.Millisecond
+)
+
+var errServerTimeout = errors.New("waiting on serverReady err: timeout")
 
 func randomPort(t testing.TB) int {
 	t.Helper()
@@ -165,7 +169,7 @@ func clientPion(c *comm) {
 	case <-c.serverReady:
 		// OK
 	case <-time.After(time.Second):
-		c.errChan <- errors.New("waiting on serverReady err: timeout")
+		c.errChan <- errServerTimeout
 	}
 
 	c.clientMutex.Lock()
@@ -315,9 +319,11 @@ func testPionE2EMTUs(t *testing.T, server, client func(*comm)) {
 func TestPionE2ESimple(t *testing.T) {
 	testPionE2ESimple(t, serverPion, clientPion)
 }
+
 func TestPionE2ESimplePSK(t *testing.T) {
 	testPionE2ESimplePSK(t, serverPion, clientPion)
 }
+
 func TestPionE2EMTUs(t *testing.T) {
 	testPionE2EMTUs(t, serverPion, clientPion)
 }
diff --git a/errors_test.go b/errors_test.go
index b619997..78ad8e8 100644
--- a/errors_test.go
+++ b/errors_test.go
@@ -9,9 +9,9 @@ import (
 	"golang.org/x/xerrors"
 )
 
-func TestErrorUnwrap(t *testing.T) {
-	errExample := errors.New("an example error")
+var errExample = errors.New("an example error")
 
+func TestErrorUnwrap(t *testing.T) {
 	cases := []struct {
 		err          error
 		errUnwrapped []error
@@ -43,7 +43,7 @@ func TestErrorUnwrap(t *testing.T) {
 			err := c.err
 			for _, unwrapped := range c.errUnwrapped {
 				e := xerrors.Unwrap(err)
-				if e != unwrapped {
+				if !errors.Is(e, unwrapped) {
 					t.Errorf("Unwrapped error is expected to be '%v', got '%v'", unwrapped, e)
 				}
 			}
@@ -52,8 +52,6 @@ func TestErrorUnwrap(t *testing.T) {
 }
 
 func TestErrorNetError(t *testing.T) {
-	errExample := errors.New("an example error")
-
 	cases := []struct {
 		err                error
 		str                string
diff --git a/handshake_message_certificate_test.go b/handshake_message_certificate_test.go
index 6002103..9d7b21f 100644
--- a/handshake_message_certificate_test.go
+++ b/handshake_message_certificate_test.go
@@ -42,7 +42,8 @@ func TestHandshakeMessageCertificate(t *testing.T) {
 		0x2a, 0x74, 0x33, 0x6d, 0xed, 0xac, 0x37, 0x21, 0xfa, 0x76, 0x5a, 0x4d, 0x78, 0x68, 0x1a, 0xdd,
 		0x80, 0xa4, 0xd4, 0xb7, 0x7f, 0x7d, 0x78, 0xb3, 0xfb, 0xf3, 0x95, 0xfb, 0x02, 0x21, 0x00, 0xc0,
 		0x73, 0x30, 0xda, 0x2b, 0xc0, 0x0c, 0x9e, 0xb2, 0x25, 0x0d, 0x46, 0xb0, 0xbc, 0x66, 0x7f, 0x71,
-		0x66, 0xbf, 0x16, 0xb3, 0x80, 0x78, 0xd0, 0x0c, 0xef, 0xcc, 0xf5, 0xc1, 0x15, 0x0f, 0x58}
+		0x66, 0xbf, 0x16, 0xb3, 0x80, 0x78, 0xd0, 0x0c, 0xef, 0xcc, 0xf5, 0xc1, 0x15, 0x0f, 0x58,
+	}
 
 	parsedCertificate := &x509.Certificate{
 		Raw:                     rawCertificate[6:],
diff --git a/handshake_message_client_hello_test.go b/handshake_message_client_hello_test.go
index 3899d7f..bd5186f 100644
--- a/handshake_message_client_hello_test.go
+++ b/handshake_message_client_hello_test.go
@@ -26,7 +26,7 @@ func TestHandshakeMessageClientHello(t *testing.T) {
 			&cipherSuiteTLSEcdheEcdsaWithAes256CbcSha{},
 		},
 		compressionMethods: []*compressionMethod{
-			compressionMethods[compressionMethodNull],
+			compressionMethods()[compressionMethodNull],
 		},
 		extensions: []extension{
 			&extensionSupportedEllipticCurves{ellipticCurves: []namedCurve{namedCurveX25519}},
diff --git a/handshake_message_server_hello_test.go b/handshake_message_server_hello_test.go
index bad5a23..19c7a21 100644
--- a/handshake_message_server_hello_test.go
+++ b/handshake_message_server_hello_test.go
@@ -20,7 +20,7 @@ func TestHandshakeMessageServerHello(t *testing.T) {
 			[28]byte{0x81, 0x0e, 0x98, 0x6c, 0x85, 0x3d, 0xa4, 0x39, 0xaf, 0x5f, 0xd6, 0x5c, 0xcc, 0x20, 0x7f, 0x7c, 0x78, 0xf1, 0x5f, 0x7e, 0x1c, 0xb7, 0xa1, 0x1e, 0xcf, 0x63, 0x84, 0x28},
 		},
 		cipherSuite:       &cipherSuiteTLSEcdheEcdsaWithAes128GcmSha256{},
-		compressionMethod: compressionMethods[compressionMethodNull],
+		compressionMethod: compressionMethods()[compressionMethodNull],
 		extensions:        []extension{},
 	}
 
diff --git a/hash_algorithm_test.go b/hash_algorithm_test.go
index bf01bd2..bc55b2e 100644
--- a/hash_algorithm_test.go
+++ b/hash_algorithm_test.go
@@ -7,7 +7,7 @@ import (
 )
 
 func TestHashAlgorithm_StringRoundtrip(t *testing.T) {
-	for algo := range hashAlgorithms {
+	for algo := range hashAlgorithms() {
 		if algo == hashAlgorithmEd25519 {
 			// Ed25519 does hashing and signing in one time.
 			continue
diff --git a/internal/net/connctx/connctx_test.go b/internal/net/connctx/connctx_test.go
index 7bc2c77..65e687b 100644
--- a/internal/net/connctx/connctx_test.go
+++ b/internal/net/connctx/connctx_test.go
@@ -3,6 +3,7 @@ package connctx
 import (
 	"bytes"
 	"context"
+	"errors"
 	"io"
 	"net"
 	"testing"
@@ -188,7 +189,7 @@ func TestWriteClosed(t *testing.T) {
 
 	b := make([]byte, 100)
 	n, err := c.Write(context.Background(), b)
-	if err != ErrClosing {
+	if !errors.Is(err, ErrClosing) {
 		t.Errorf("Expected error '%v', got '%v'", ErrClosing, err)
 	}
 	if n != 0 {
diff --git a/internal/net/dpipe/dpipe_test.go b/internal/net/dpipe/dpipe_test.go
index c3fed56..c9c9a3d 100644
--- a/internal/net/dpipe/dpipe_test.go
+++ b/internal/net/dpipe/dpipe_test.go
@@ -4,6 +4,7 @@ package dpipe
 
 import (
 	"bytes"
+	"errors"
 	"io"
 	"net"
 	"testing"
@@ -71,7 +72,7 @@ func TestPipe(t *testing.T) {
 	if err := ca.Close(); err != nil {
 		t.Errorf("Unexpected error on Close: %v", err)
 	}
-	if _, err := ca.Write(testData); err != io.ErrClosedPipe {
+	if _, err := ca.Write(testData); !errors.Is(err, io.ErrClosedPipe) {
 		t.Errorf("Write to closed conn should fail with %v, got %v", io.ErrClosedPipe, err)
 	}
 
@@ -81,7 +82,7 @@ func TestPipe(t *testing.T) {
 	}
 
 	readData := make([]byte, 4)
-	if _, err := ca.Read(readData); err != io.EOF {
+	if _, err := ca.Read(readData); !errors.Is(err, io.EOF) {
 		t.Errorf("Read from closed conn should fail with %v, got %v", io.EOF, err)
 	}
 
diff --git a/nettest_test.go b/nettest_test.go
index a0a0717..22bd955 100644
--- a/nettest_test.go
+++ b/nettest_test.go
@@ -7,9 +7,8 @@ import (
 	"testing"
 	"time"
 
-	"golang.org/x/net/nettest"
-
 	"github.com/pion/transport/test"
+	"golang.org/x/net/nettest"
 )
 
 func TestNetTest(t *testing.T) {
diff --git a/pkg/crypto/ccm/ccm_test.go b/pkg/crypto/ccm/ccm_test.go
index 6437587..0784a5a 100644
--- a/pkg/crypto/ccm/ccm_test.go
+++ b/pkg/crypto/ccm/ccm_test.go
@@ -6,6 +6,7 @@ import (
 	"bytes"
 	"crypto/aes"
 	"encoding/hex"
+	"errors"
 	"fmt"
 	"testing"
 )
@@ -18,8 +19,10 @@ func mustHexDecode(s string) []byte {
 	return r
 }
 
-var aesKey1to12 = mustHexDecode("c0c1c2c3c4c5c6c7c8c9cacbcccdcecf")
-var aesKey13to24 = mustHexDecode("d7828d13b2b0bdc325a76236df93cc6b")
+var (
+	aesKey1to12  = mustHexDecode("c0c1c2c3c4c5c6c7c8c9cacbcccdcecf") //nolint:gochecknoglobals
+	aesKey13to24 = mustHexDecode("d7828d13b2b0bdc325a76236df93cc6b") //nolint:gochecknoglobals
+)
 
 // AESKey: AES Key
 // CipherText: Authenticated and encrypted output
@@ -320,7 +323,7 @@ func TestNewCCMError(t *testing.T) {
 				t.Fatalf("could not initialize AES block cipher from key: %v", err)
 			}
 
-			if _, err := NewCCM(blk, c.M, len(c.Nonce)); err != c.err {
+			if _, err := NewCCM(blk, c.M, len(c.Nonce)); !errors.Is(err, c.err) {
 				t.Fatalf("expected error '%v', got '%v'", c.err, err)
 			}
 		})
@@ -362,7 +365,7 @@ func TestSealError(t *testing.T) {
 		c := c
 		t.Run(name, func(t *testing.T) {
 			defer func() {
-				if err := recover(); err != c.err {
+				if err := recover(); !errors.Is(err.(error), c.err) {
 					t.Errorf("expected panic '%v', got '%v'", c.err, err)
 				}
 			}()
@@ -408,7 +411,7 @@ func TestOpenError(t *testing.T) {
 		t.Run(name, func(t *testing.T) {
 			var dst []byte
 			_, err = lccm.Open(dst, c.Nonce, c.CipherText[c.ClearHeaderOctets:], c.CipherText[:c.ClearHeaderOctets])
-			if err != c.err {
+			if !errors.Is(err, c.err) {
 				t.Errorf("expected error '%v', got '%v'", c.err, err)
 			}
 		})
diff --git a/pkg/crypto/fingerprint/fingerprint_test.go b/pkg/crypto/fingerprint/fingerprint_test.go
index 0b1e9c9..1a7a11f 100644
--- a/pkg/crypto/fingerprint/fingerprint_test.go
+++ b/pkg/crypto/fingerprint/fingerprint_test.go
@@ -3,9 +3,12 @@ package fingerprint
 import (
 	"crypto"
 	"crypto/x509"
+	"errors"
 	"testing"
 )
 
+var errInvalidHashID = errors.New("invalid hash ID")
+
 func TestFingerprint(t *testing.T) {
 	rawCertificate := []byte{
 		0x30, 0x82, 0x01, 0x98, 0x30, 0x82, 0x01, 0x3d, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x11, 0x00, 0xa9, 0x91, 0x76, 0x0a, 0xcd, 0x97, 0x4c, 0x36, 0xba,
@@ -43,7 +46,7 @@ func TestFingerprint(t *testing.T) {
 
 func TestFingerprint_UnavailableHash(t *testing.T) {
 	_, err := Fingerprint(&x509.Certificate{}, crypto.Hash(0xFFFFFFFF))
-	if err != errHashUnavailable {
-		t.Errorf("Expected error '%v' for invalid hash ID, got '%v'", errHashUnavailable, err)
+	if !errors.Is(err, errHashUnavailable) {
+		t.Errorf("%w: Expected error '%v' for invalid hash ID, got '%v'", errInvalidHashID, errHashUnavailable, err)
 	}
 }
diff --git a/pkg/crypto/fingerprint/hash_test.go b/pkg/crypto/fingerprint/hash_test.go
index e9617b7..09ed969 100644
--- a/pkg/crypto/fingerprint/hash_test.go
+++ b/pkg/crypto/fingerprint/hash_test.go
@@ -2,13 +2,14 @@ package fingerprint
 
 import (
 	"crypto"
+	"errors"
 	"testing"
 )
 
 func TestHashFromString(t *testing.T) {
 	t.Run("InvalidHashAlgorithm", func(t *testing.T) {
 		_, err := HashFromString("invalid-hash-algorithm")
-		if err != errInvalidHashAlgorithm {
+		if !errors.Is(err, errInvalidHashAlgorithm) {
 			t.Errorf("Expected error '%v' for invalid hash name, got '%v'", errInvalidHashAlgorithm, err)
 		}
 	})
@@ -24,7 +25,7 @@ func TestHashFromString(t *testing.T) {
 }
 
 func TestStringFromHash_Roundtrip(t *testing.T) {
-	for _, h := range nameToHash {
+	for _, h := range nameToHash() {
 		s, err := StringFromHash(h)
 		if err != nil {
 			t.Fatalf("Unexpected error for valid hash algorithm, got '%v'", err)
diff --git a/record_layer_test.go b/record_layer_test.go
index 5c757ac..c27c8a9 100644
--- a/record_layer_test.go
+++ b/record_layer_test.go
@@ -1,6 +1,7 @@
 package dtls
 
 import (
+	"errors"
 	"reflect"
 	"testing"
 )
@@ -42,7 +43,7 @@ func TestUDPDecode(t *testing.T) {
 		},
 	} {
 		dtlsPkts, err := unpackDatagram(test.Data)
-		if err != test.WantError {
+		if !errors.Is(err, test.WantError) {
 			t.Errorf("Unexpected Error %q: exp: %v got: %v", test.Name, test.WantError, err)
 		} else if !reflect.DeepEqual(test.Want, dtlsPkts) {
 			t.Errorf("%q UDP decode: got %q, want %q", test.Name, dtlsPkts, test.Want)
@@ -73,14 +74,14 @@ func TestRecordLayerRoundTrip(t *testing.T) {
 		},
 	} {
 		r := &recordLayer{}
-		if err := r.Unmarshal(test.Data); err != test.WantUnmarshalError {
+		if err := r.Unmarshal(test.Data); !errors.Is(err, test.WantUnmarshalError) {
 			t.Errorf("Unexpected Error %q: exp: %v got: %v", test.Name, test.WantUnmarshalError, err)
 		} else if !reflect.DeepEqual(test.Want, r) {
 			t.Errorf("%q recordLayer.unmarshal: got %q, want %q", test.Name, r, test.Want)
 		}
 
 		data, marshalErr := r.Marshal()
-		if marshalErr != test.WantMarshalError {
+		if !errors.Is(marshalErr, test.WantMarshalError) {
 			t.Errorf("Unexpected Error %q: exp: %v got: %v", test.Name, test.WantMarshalError, marshalErr)
 		} else if !reflect.DeepEqual(test.Data, data) {
 			t.Errorf("%q recordLayer.marshal: got % 02x, want % 02x", test.Name, data, test.Data)
diff --git a/resume_test.go b/resume_test.go
index e72aad9..cad3d2d 100644
--- a/resume_test.go
+++ b/resume_test.go
@@ -3,6 +3,7 @@ package dtls
 import (
 	"bytes"
 	"crypto/tls"
+	"errors"
 	"fmt"
 	"net"
 	"sync"
@@ -13,6 +14,8 @@ import (
 	"github.com/pion/transport/test"
 )
 
+var errMessageMissmatch = errors.New("messages missmatch")
+
 func TestResumeClient(t *testing.T) {
 	DoTestResume(t, Client, Server)
 }
@@ -105,7 +108,7 @@ func DoTestResume(t *testing.T, newLocal, newRemote func(net.Conn, *Config) (*Co
 	}
 
 	if !bytes.Equal(message, recv[:n]) {
-		fatal(t, errChan, fmt.Errorf("messages missmatch: %s != %s", message, recv[:n]))
+		fatal(t, errChan, fmt.Errorf("%w: %s != %s", errMessageMissmatch, message, recv[:n]))
 	}
 
 	if err = localConn1.Close(); err != nil {
@@ -146,7 +149,7 @@ func DoTestResume(t *testing.T, newLocal, newRemote func(net.Conn, *Config) (*Co
 	}
 
 	if !bytes.Equal(message, recv[:n]) {
-		fatal(t, errChan, fmt.Errorf("messages missmatch: %s != %s", message, recv[:n]))
+		fatal(t, errChan, fmt.Errorf("%w: %s != %s", errMessageMissmatch, message, recv[:n]))
 	}
 }