forked from emiago/diago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigest_auth.go
153 lines (126 loc) · 3.51 KB
/
digest_auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024, Emir Aganovic
package diago
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"sync"
"time"
"github.com/emiago/sipgo/sip"
"github.com/icholy/digest"
)
type DigestAuth struct {
Username string
Password string
Realm string
Expire time.Duration
}
func (a *DigestAuth) expire() time.Duration {
if a.Expire > 0 {
return a.Expire
}
return 5 * time.Second
}
type digestChallengeEntry struct {
digest.Challenge
expireTimer *time.Timer
}
type DigestAuthServer struct {
mu sync.Mutex
cache map[string]*digestChallengeEntry
}
func NewDigestServer() *DigestAuthServer {
t := &DigestAuthServer{
cache: make(map[string]*digestChallengeEntry),
}
return t
}
func (s *DigestAuthServer) Close() {
s.mu.Lock()
defer s.mu.Unlock()
for _, v := range s.cache {
v.expireTimer.Stop()
}
}
var (
ErrDigestAuthNoChallenge = errors.New("no challenge")
ErrDigestAuthBadCreds = errors.New("bad credentials")
)
// AuthorizeRequest authorizes request. Returns SIP response that can be passed with error
func (s *DigestAuthServer) AuthorizeRequest(req *sip.Request, auth DigestAuth) (res *sip.Response, err error) {
h := req.GetHeader("Authorization")
// https://www.rfc-editor.org/rfc/rfc2617#page-6
if h == nil {
nonce, err := generateNonce()
if err != nil {
return sip.NewResponseFromRequest(req, sip.StatusInternalServerError, "Internal Server Error", nil), err
}
e := &digestChallengeEntry{
Challenge: digest.Challenge{
Realm: auth.Realm,
Nonce: nonce,
// Opaque: "sipgo",
Algorithm: "MD5",
},
}
chal := &e.Challenge
res := sip.NewResponseFromRequest(req, 401, "Unathorized", nil)
res.AppendHeader(sip.NewHeader("WWW-Authenticate", chal.String()))
s.mu.Lock()
s.cache[nonce] = e
s.mu.Unlock()
e.expireTimer = time.AfterFunc(auth.expire(), func() {
s.mu.Lock()
delete(s.cache, nonce)
s.mu.Unlock()
})
return res, nil
}
cred, err := digest.ParseCredentials(h.Value())
if err != nil {
return sip.NewResponseFromRequest(req, sip.StatusBadRequest, "Bad Request", nil), err
}
e, exists := s.cache[cred.Nonce]
if !exists {
return sip.NewResponseFromRequest(req, sip.StatusUnauthorized, "Unauthorized", nil), ErrDigestAuthNoChallenge
}
chal := &e.Challenge
// Make digest and compare response
digCred, err := digest.Digest(chal, digest.Options{
Method: req.Method.String(),
URI: cred.URI,
Username: auth.Username,
Password: auth.Password,
})
if err != nil {
// Mostly due to unsupported digest alg
return sip.NewResponseFromRequest(req, sip.StatusForbidden, "Forbidden", nil), err
}
if cred.Response != digCred.Response {
return sip.NewResponseFromRequest(req, sip.StatusUnauthorized, "Unauthorized", nil), ErrDigestAuthBadCreds
}
return sip.NewResponseFromRequest(req, sip.StatusOK, "OK", nil), nil
}
func (s *DigestAuthServer) AuthorizeDialog(d *DialogServerSession, auth DigestAuth) error {
if auth.Realm == "" {
auth.Realm = "sipgo"
}
// https://www.rfc-editor.org/rfc/rfc2617#page-6
req := d.InviteRequest
res, err := s.AuthorizeRequest(req, auth)
if err == nil && res.StatusCode != 200 {
err = fmt.Errorf("not authorized")
return errors.Join(err, d.WriteResponse(res))
}
return errors.Join(err, nil)
}
func generateNonce() (string, error) {
nonceBytes := make([]byte, 32)
_, err := rand.Read(nonceBytes)
if err != nil {
return "", fmt.Errorf("could not generate nonce")
}
return base64.URLEncoding.EncodeToString(nonceBytes), nil
}