-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Security add #18
Open
Olegsandrik
wants to merge
21
commits into
develop
Choose a base branch
from
security
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Security add #18
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
3eef05f
Добавление хеширования паролей
Olegsandrik b8a59ae
Поправил названия
Olegsandrik 54806ac
Добавление CSRFtokenа
Olegsandrik 1ace540
Структуризация csrfmw
Olegsandrik 637af1b
Правки
Olegsandrik 54ae236
Соль теперь приклеена к захешированному паролю
Olegsandrik 150d11b
работа с тестами
Olegsandrik 4ce1972
[*]: update merge
b0pof df58392
[*]: test fix
b0pof 9f675a1
[*]: 100% tests fix
b0pof 373c115
Правки от линтера
Olegsandrik 46f43d0
Правка линтера
Olegsandrik e6ea080
форматирование
Olegsandrik 85d9721
Вынос функции хеширования в пакет helper
Olegsandrik 949683e
Устранение зависимости от кук в csrfmw
Olegsandrik 9a2a4f4
правки
Olegsandrik 9b2344c
Тесты на csrf token
Olegsandrik 6864aee
merge develop
Olegsandrik eb0a310
Правки
Olegsandrik ea00ae7
правки линтера
Olegsandrik 8f2a57c
правки mw
Olegsandrik File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package models | ||
|
||
import ( | ||
"fmt" | ||
|
||
"github.com/dgrijalva/jwt-go" | ||
"github.com/pkg/errors" | ||
|
||
"time" | ||
) | ||
|
||
type JwtToken struct { | ||
Secret []byte | ||
} | ||
|
||
func NewJwtToken(secret string) (*JwtToken, error) { | ||
return &JwtToken{Secret: []byte(secret)}, nil | ||
} | ||
|
||
type JwtCsrfClaims struct { | ||
SessionID string `json:"sid"` | ||
jwt.StandardClaims | ||
} | ||
|
||
func (tk *JwtToken) Create(sID string, tokenExpTime int64) (string, error) { | ||
data := JwtCsrfClaims{ | ||
SessionID: sID, | ||
StandardClaims: jwt.StandardClaims{ | ||
ExpiresAt: tokenExpTime, | ||
IssuedAt: time.Now().Unix(), | ||
}, | ||
} | ||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, data) | ||
return token.SignedString(tk.Secret) | ||
} | ||
|
||
func (tk *JwtToken) parseSecretGetter(token *jwt.Token) (interface{}, error) { | ||
method, ok := token.Method.(*jwt.SigningMethodHMAC) | ||
if !ok || method.Alg() != "HS256" { | ||
return nil, errors.New("bad sign method") | ||
} | ||
return tk.Secret, nil | ||
} | ||
|
||
func (tk *JwtToken) Check(sID string, inputToken string) (bool, error) { | ||
payload := &JwtCsrfClaims{} | ||
_, err := jwt.ParseWithClaims(inputToken, payload, tk.parseSecretGetter) | ||
if err != nil { | ||
return false, fmt.Errorf("cant parse jwt token: %w", err) | ||
} | ||
if payload.Valid() != nil { | ||
return false, fmt.Errorf("invalid jwt token: %w", err) | ||
} | ||
return payload.SessionID == sID, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package models_test | ||
|
||
import ( | ||
"strconv" | ||
"testing" | ||
"time" | ||
|
||
"github.com/go-park-mail-ru/2024_1_FullFocus/internal/models" | ||
) | ||
|
||
func TestCreateCSRF(t *testing.T) { | ||
tokens, _ := models.NewJwtToken("test") | ||
uID := strconv.Itoa(1) | ||
_, err := tokens.Create(uID, time.Now().Add(1*time.Hour).Unix()) | ||
if err != nil { | ||
t.Fatalf("err with creation") | ||
} | ||
} | ||
|
||
func TestCheckCSRF(t *testing.T) { | ||
tokens, _ := models.NewJwtToken("test") | ||
uID := strconv.Itoa(1) | ||
token, err := tokens.Create(uID, time.Now().Add(1*time.Hour).Unix()) | ||
if err != nil { | ||
t.Fatalf("err with creation 1 token") | ||
} | ||
_, err = tokens.Check(uID, token) | ||
if err != nil { | ||
t.Fatalf("err with check token") | ||
} | ||
} | ||
|
||
func TestCheckFailCSRF(t *testing.T) { | ||
tokens, _ := models.NewJwtToken("test") | ||
uID := strconv.Itoa(1) | ||
token, err := tokens.Create(uID, time.Now().Add(1*time.Second).Unix()) | ||
time.Sleep(3 * time.Second) | ||
if err != nil { | ||
t.Fatalf("err with creation 1 token") | ||
} | ||
_, err = tokens.Check(uID, token) | ||
if err != nil { | ||
t.Log("success") | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package helper | ||
|
||
import ( | ||
"bytes" | ||
|
||
"golang.org/x/crypto/argon2" | ||
) | ||
|
||
const ( | ||
_countBytes = 8 | ||
_countMemory = 65536 | ||
_countTreads = 4 | ||
_countKeyLen = 32 | ||
) | ||
|
||
func hashPass(salt []byte, plainPassword string) []byte { | ||
hashedPass := argon2.IDKey([]byte(plainPassword), salt, 1, _countMemory, _countTreads, _countKeyLen) | ||
return append(salt, hashedPass...) | ||
} | ||
|
||
func CheckPass(passHash []byte, plainPassword string) bool { | ||
salt := passHash[0:8] | ||
userPassHash := hashPass(salt, plainPassword) | ||
return bytes.Equal(userPassHash, passHash) | ||
} | ||
|
||
func MakeNewPassHash(password string) (string, error) { | ||
/*salt := make([]byte, _countBytes) | ||
_, err := rand.Read(salt) | ||
if err != nil { | ||
return "", err | ||
} | ||
passwordHash := hashPass(salt, password) | ||
charset := "latin1" | ||
e, err := ianaindex.MIME.Encoding(charset) | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
r := transform.NewReader(bytes.NewBufferString(string(passwordHash)), e.NewDecoder()) | ||
result, err := ioutil.ReadAll(r) | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
|
||
*/ | ||
return password, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
package middleware | ||
|
||
import ( | ||
"fmt" | ||
"strings" | ||
"time" | ||
|
||
"github.com/go-park-mail-ru/2024_1_FullFocus/internal/delivery/dto" | ||
"github.com/go-park-mail-ru/2024_1_FullFocus/internal/models" | ||
"github.com/go-park-mail-ru/2024_1_FullFocus/internal/pkg/helper" | ||
"github.com/go-park-mail-ru/2024_1_FullFocus/internal/pkg/logger" | ||
"github.com/gorilla/mux" | ||
|
||
"net/http" | ||
) | ||
|
||
const _timeOut = 20 | ||
|
||
func CSRFMiddleware() mux.MiddlewareFunc { | ||
return func(next http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
ctx := r.Context() | ||
if strings.Contains(r.URL.Path, "public") { | ||
next.ServeHTTP(w, r) | ||
return | ||
} | ||
|
||
if r.Method == http.MethodGet || r.Method == http.MethodHead { | ||
err := SetSCRFToken(w, r) | ||
if err != nil { | ||
logger.Debug(ctx, fmt.Sprintf("csrf token creation error: %v", err)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тут тоже, нужно на запрос ответить |
||
helper.JSONResponse(ctx, w, 200, dto.ErrResponse{ | ||
Status: 400, | ||
Msg: err.Error(), | ||
MsgRus: "Ошибка создания csrf token", | ||
}) | ||
return | ||
} | ||
} else { | ||
err := CheckSCRFToken(r) | ||
if err != nil { | ||
logger.Debug(ctx, fmt.Sprintf("csrf token check error: %v", err)) | ||
helper.JSONResponse(ctx, w, 200, dto.ErrResponse{ | ||
Status: 400, | ||
Msg: err.Error(), | ||
MsgRus: "Ошибка проверки csrf token", | ||
}) | ||
return | ||
} | ||
} | ||
next.ServeHTTP(w, r) | ||
}) | ||
} | ||
} | ||
|
||
func SetSCRFToken(w http.ResponseWriter, r *http.Request) error { | ||
tokens, _ := models.NewJwtToken("qsRY2e4hcM5T7X984E9WQ5uZ8Nty7fxB") | ||
ctx := r.Context() | ||
token, err := tokens.Create("sID", time.Now().Add(_timeOut*time.Minute).Unix()) | ||
logger.Info(ctx, fmt.Sprintf("err wiht csrf: %v", err)) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
w.Header().Set("X-Csrf-Token", token) | ||
return nil | ||
} | ||
|
||
func CheckSCRFToken(r *http.Request) error { | ||
tokens, _ := models.NewJwtToken("qsRY2e4hcM5T7X984E9WQ5uZ8Nty7fxB") | ||
ctx := r.Context() | ||
csrfToken := r.Header.Get("X-Csrf-Token") | ||
_, err := tokens.Check("sID", csrfToken) | ||
logger.Info(ctx, fmt.Sprintf("err wiht csrf: %v", err)) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
{"version":"1","format":"xl-single","id":"38f1154f-153c-4976-a563-7c4e6735aaae","xl":{"version":"3","this":"2c90ecd9-79c7-4f38-9a8d-5b0da5741b6a","sets":[["2c90ecd9-79c7-4f38-9a8d-5b0da5741b6a"]],"distributionAlgo":"SIPMOD+PARITY"}} |
Binary file not shown.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
нужны тесты