gosec/rules/slowloris.go

72 lines
2 KiB
Go
Raw Normal View History

2022-04-30 11:38:50 +01:00
// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rules
import (
"go/ast"
"github.com/securego/gosec/v2"
2023-02-15 19:44:13 +00:00
"github.com/securego/gosec/v2/issue"
2022-04-30 11:38:50 +01:00
)
type slowloris struct {
2023-02-15 19:44:13 +00:00
issue.MetaData
2022-04-30 11:38:50 +01:00
}
func (r *slowloris) ID() string {
return r.MetaData.ID
}
func containsReadHeaderTimeout(node *ast.CompositeLit) bool {
if node == nil {
return false
}
for _, elt := range node.Elts {
if kv, ok := elt.(*ast.KeyValueExpr); ok {
if ident, ok := kv.Key.(*ast.Ident); ok {
2022-06-23 13:58:13 +01:00
if ident.Name == "ReadHeaderTimeout" || ident.Name == "ReadTimeout" {
2022-04-30 11:38:50 +01:00
return true
}
}
}
}
return false
}
2023-02-15 19:44:13 +00:00
func (r *slowloris) Match(n ast.Node, ctx *gosec.Context) (*issue.Issue, error) {
2022-04-30 11:38:50 +01:00
switch node := n.(type) {
case *ast.CompositeLit:
actualType := ctx.Info.TypeOf(node.Type)
if actualType != nil && actualType.String() == "net/http.Server" {
if !containsReadHeaderTimeout(node) {
2023-02-15 19:44:13 +00:00
return ctx.NewIssue(node, r.ID(), r.What, r.Severity, r.Confidence), nil
2022-04-30 11:38:50 +01:00
}
}
}
return nil, nil
}
// NewSlowloris attempts to find the http.Server struct and check if the ReadHeaderTimeout is configured.
2023-03-20 09:08:49 +00:00
func NewSlowloris(id string, _ gosec.Config) (gosec.Rule, []ast.Node) {
2022-04-30 11:38:50 +01:00
return &slowloris{
2023-02-15 19:44:13 +00:00
MetaData: issue.MetaData{
2022-04-30 11:38:50 +01:00
ID: id,
What: "Potential Slowloris Attack because ReadHeaderTimeout is not configured in the http.Server",
2023-02-15 19:44:13 +00:00
Confidence: issue.Low,
Severity: issue.Medium,
2022-04-30 11:38:50 +01:00
},
}, []ast.Node{(*ast.CompositeLit)(nil)}
}