-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathauth.go
228 lines (197 loc) · 5.12 KB
/
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package potoq
import (
"context"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/hex"
"encoding/json"
"fmt"
"golang.org/x/time/rate"
"io"
math_rand "math/rand"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/google/uuid"
"github.com/Craftserve/potoq/packets"
)
var ErrBadLogin = fmt.Errorf("Bad Login!")
var ErrUnauthenticated = fmt.Errorf("Player unauthenticated")
var ErrTooManyRequests = fmt.Errorf("Too many requests, try again later!")
var authenticators []*Authenticator
func init() {
var publicIPs []net.IP
interfaces, _ := net.Interfaces()
for _, intf := range interfaces {
addrs, _ := intf.Addrs()
for _, i := range addrs {
ip := i.(*net.IPNet).IP.To4()
if ip != nil && ip.IsGlobalUnicast() {
publicIPs = append(publicIPs, ip)
}
}
}
for _, ip := range publicIPs {
a, err := newAuthenticator(ip)
if err != nil {
panic(err)
}
authenticators = append(authenticators, a)
}
}
func getRandomAuthenticator() *Authenticator {
return authenticators[math_rand.Intn(len(authenticators))]
}
type Authenticator struct {
ServerID string
ServerKey *rsa.PrivateKey
PublicKey []byte // encoded
HttpClient *http.Client
Limiter *rate.Limiter
}
func newAuthenticator(ip net.IP) (*Authenticator, error) {
var buf [8]byte
_, err := io.ReadFull(rand.Reader, buf[:])
if err != nil {
return nil, err
}
serverID := hex.EncodeToString(buf[:])
serverKey, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return nil, err
}
serverKey.Precompute()
publicKey, err := x509.MarshalPKIXPublicKey(serverKey.Public())
if err != nil {
return nil, err
}
dialer := &net.Dialer{Timeout: time.Second, LocalAddr: &net.TCPAddr{IP: ip}}
transport := &http.Transport{DialContext: dialer.DialContext}
return &Authenticator{
ServerID: serverID,
ServerKey: serverKey,
PublicKey: publicKey,
HttpClient: &http.Client{
Transport: transport,
Timeout: 3 * time.Second,
},
Limiter: rate.NewLimiter(200, 1000),
}, nil
}
func (a *Authenticator) HasJoined(ctx context.Context, handler *Handler, secret []byte) error {
if !ValidateNickname(handler.Nickname) {
return fmt.Errorf("Invalid nickname")
}
if !a.Limiter.Allow() {
return ErrTooManyRequests
}
var query = make(url.Values)
query.Set("serverId", authDigest([]byte(a.ServerID), secret, a.PublicKey))
query.Set("username", handler.Nickname)
req, err := http.NewRequest("GET", "https://sessionserver.mojang.com/session/minecraft/hasJoined?"+query.Encode(), nil)
if err != nil {
return err
}
resp, err := a.HttpClient.Do(req.WithContext(ctx))
if err != nil {
handler.Log().WithError(err).Println("HasJoined failed")
return ErrBadLogin
}
defer resp.Body.Close()
var response struct {
UUID uuid.UUID `json:"id"`
Name string `json:"name"`
Properties []packets.AuthProperty `json:"properties"`
// Legacy bool `json:"legacy"`
// Demo bool `json:"demo"`
}
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
return err
}
handler.Nickname = response.Name
handler.UUID = response.UUID
handler.AuthProperties = response.Properties
return nil
}
func authDigest(serverID, secret, publicKey []byte) string {
h := sha1.New()
h.Write(serverID)
h.Write(secret)
h.Write(publicKey)
hash := h.Sum(nil)
// Check for negative hashes
negative := (hash[0] & 0x80) == 0x80
if negative {
hash = twosComplement(hash)
}
// Trim away zeroes
res := strings.TrimLeft(fmt.Sprintf("%x", hash), "0")
if negative {
res = "-" + res
}
return res
}
// little endian
func twosComplement(p []byte) []byte {
carry := true
for i := len(p) - 1; i >= 0; i-- {
p[i] = byte(^p[i])
if carry {
carry = p[i] == 0xff
p[i]++
}
}
return p
}
func (a *Authenticator) HasPaid(ctx context.Context, nickname string) (paid bool, err error) {
if !ValidateNickname(nickname) {
return false, fmt.Errorf("Invalid nickname")
}
if !a.Limiter.Allow() {
return false, ErrTooManyRequests
}
// Blocked from hetzner: "https://api.mojang.com/users/profiles/minecraft/" + nickname (?)
req, err := http.NewRequest("GET", "https://api.minetools.eu/uuid/"+nickname, nil)
if err != nil {
return false, err
}
resp, err := a.HttpClient.Do(req.WithContext(ctx))
if err != nil {
return false, err
}
defer resp.Body.Close()
var v struct {
Id string `json:"id"`
}
switch resp.StatusCode {
case http.StatusOK:
err = json.NewDecoder(resp.Body).Decode(&v)
if err != nil {
return false, err
}
return v.Id != "null", nil
case http.StatusTooManyRequests:
return false, ErrTooManyRequests
default:
return false, fmt.Errorf("unexpected status code: %v", resp.StatusCode)
}
}
var nicknameRegexp = regexp.MustCompile("[A-Za-z0-9_]{3,16}")
func ValidateNickname(nickname string) bool {
return nicknameRegexp.MatchString(nickname)
}
func OfflinePlayerUUID(nickname string) uuid.UUID {
h := md5.New()
io.WriteString(h, "OfflinePlayer:"+nickname)
var uuid, _ = uuid.FromBytes(h.Sum(nil))
uuid[6] = (uuid[6] & 0x0f) | uint8((3&0xf)<<4)
uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant
return uuid
}