Initial commit

Signed-off-by: Etzelia <etzelia@hotmail.com>
main
Etzelia 2021-08-10 00:16:27 -05:00
commit dd7953b452
No known key found for this signature in database
GPG Key ID: 708511AE7ABC5314
11 changed files with 521 additions and 0 deletions

2
.gitignore vendored 100644
View File

@ -0,0 +1,2 @@
.idea/
/mcm-register*

7
LICENSE 100644
View File

@ -0,0 +1,7 @@
Copyright 2020 Etzelia
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

48
cfb.go 100644
View File

@ -0,0 +1,48 @@
package main
import "crypto/cipher"
type cfb8 struct {
c cipher.Block
blockSize int
iv, ivReal, tmp []byte
de bool
}
func newCFB8(c cipher.Block, iv []byte, decrypt bool) cipher.Stream {
if len(iv) != 16 {
panic("bad iv length!")
}
cp := make([]byte, 256)
copy(cp, iv)
return &cfb8{
c: c,
blockSize: c.BlockSize(),
iv: cp[:16],
ivReal: cp,
tmp: make([]byte, 16),
de: decrypt,
}
}
func (cf *cfb8) XORKeyStream(dst, src []byte) {
for i := 0; i < len(src); i++ {
val := src[i]
cf.c.Encrypt(cf.tmp, cf.iv)
val = val ^ cf.tmp[0]
if cap(cf.iv) >= 17 {
cf.iv = cf.iv[1:17]
} else {
copy(cf.ivReal, cf.iv[1:])
cf.iv = cf.ivReal[:16]
}
if cf.de {
cf.iv[15] = src[i]
} else {
cf.iv[15] = val
}
dst[i] = val
}
}

46
digest.go 100644
View File

@ -0,0 +1,46 @@
package main
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"strings"
)
func digest(secret, publicKey []byte) (string, error) {
hash, err := func() (hash []byte, err error) {
h := sha1.New()
_, err = h.Write(secret)
if err != nil {
return nil, err
}
_, err = h.Write(publicKey)
if err != nil {
return nil, err
}
return h.Sum(nil), nil
}()
if err != nil {
return "", fmt.Errorf("error writing sha1: %v", err)
}
var s strings.Builder
if (hash[0] & 0x80) == 0x80 {
hash = twosComplement(hash)
s.WriteRune('-')
}
s.WriteString(strings.TrimLeft(hex.EncodeToString(hash), "0"))
return s.String(), nil
}
func twosComplement(p []byte) []byte {
carry := true
for i := len(p) - 1; i >= 0; i-- {
p[i] = ^p[i]
if carry {
carry = p[i] == 0xff
p[i]++
}
}
return p
}

115
encryption.go 100644
View File

@ -0,0 +1,115 @@
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"errors"
"fmt"
"github.com/Tnze/go-mc/net"
pk "github.com/Tnze/go-mc/net/packet"
"io"
"net/http"
"net/url"
)
var hasJoinedURL = func() *url.URL {
u, err := url.Parse("https://sessionserver.mojang.com/session/minecraft/hasJoined")
if err != nil {
panic(err)
}
return u
}()
func (s *Server) encryptionRequest(conn net.Conn) ([]byte, error) {
verify := make([]byte, 4)
_, _ = rand.Read(verify)
return verify, conn.WritePacket(pk.Marshal(0x01,
pk.String(""),
pk.ByteArray(s.publicKey),
pk.ByteArray(verify),
))
}
type profile struct {
ID string `json:"id"`
Name string `json:"name"`
}
func (p *profile) UUID() string {
return fmt.Sprintf("%s-%s-%s-%s-%s", p.ID[:8], p.ID[8:12], p.ID[12:16], p.ID[16:20], p.ID[20:32])
}
func (s *Server) encryptionResponse(conn net.Conn, username string, verify []byte) (*profile, []byte, error) {
var (
p pk.Packet
sharedSecret pk.ByteArray
verifyToken pk.ByteArray
)
err := conn.ReadPacket(&p)
if err != nil {
return nil, nil, fmt.Errorf("could not read packet: %w", err)
}
err = p.Scan(&sharedSecret, &verifyToken)
if err != nil {
return nil, nil, fmt.Errorf("could not scan packet: %w", err)
}
valid, err := s.verify(verifyToken, verify)
if err != nil || !valid {
return nil, nil, errors.New("could not verify token")
}
secret, err := rsa.DecryptPKCS1v15(rand.Reader, s.privateKey, sharedSecret)
if err != nil {
return nil, nil, fmt.Errorf("could not decrypt secret: %w", err)
}
serverID, err := digest(secret, s.publicKey)
if err != nil {
return nil, nil, fmt.Errorf("could not create digest: %w", err)
}
u := *hasJoinedURL
q := u.Query()
q.Set("username", username)
q.Set("serverId", serverID)
u.RawQuery = q.Encode()
res, err := http.Get(u.String())
if err != nil {
return nil, nil, fmt.Errorf("could not join server API: %w", err)
}
defer res.Body.Close()
var player profile
if err := json.NewDecoder(res.Body).Decode(&player); err != nil {
return nil, nil, fmt.Errorf("could not decode profile: %w", err)
}
return &player, secret, nil
}
func (s *Server) verify(encryptedVerifyToken, actualVerifyToken []byte) (bool, error) {
decryptedVerifyToken, err := rsa.DecryptPKCS1v15(rand.Reader, s.privateKey, encryptedVerifyToken)
if err != nil {
return false, fmt.Errorf("error decrypting verify token: %v", err)
}
return bytes.Equal(decryptedVerifyToken, actualVerifyToken), nil
}
func encryptedConn(conn net.Conn, secret []byte) (io.Writer, error) {
block, err := aes.NewCipher(secret)
if err != nil {
return nil, err
}
return &cipher.StreamWriter{
S: newCFB8(block, secret, false),
W: conn,
}, nil
}

BIN
favicon.png 100644

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

10
go.mod 100644
View File

@ -0,0 +1,10 @@
module git.canopymc.net/Etzelia/mcm-register
go 1.16
require (
github.com/Tnze/go-mc v1.17.1-0.20210806203433-99081e1b9cfb
github.com/google/uuid v1.1.1
github.com/peterbourgon/ff/v3 v3.1.0
go.jolheiser.com/beaver v1.1.2
)

25
go.sum 100644
View File

@ -0,0 +1,25 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Tnze/go-mc v1.17.1-0.20210806203433-99081e1b9cfb h1:jf5lM8mkIpYLFF2cORRGYVK9Mv/xuomG1hmR0b4EzXU=
github.com/Tnze/go-mc v1.17.1-0.20210806203433-99081e1b9cfb/go.mod h1:t0AI38F1BEmmy8/uLhr9RCOUeDbBj3oUNQH9akjzMc0=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/iancoleman/strcase v0.1.3 h1:dJBk1m2/qjL1twPLf68JND55vvivMupZ4wIzE8CTdBw=
github.com/iancoleman/strcase v0.1.3/go.mod h1:SK73tn/9oHe+/Y0h39VT4UCxmurVJkR5NA7kMEAOgSE=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/pelletier/go-toml v1.6.0 h1:aetoXYr0Tv7xRU/V4B4IZJ2QcbtMUFoNb3ORp7TzIK4=
github.com/pelletier/go-toml v1.6.0/go.mod h1:5N711Q9dKgbdkxHL+MEfF31hpT7l0S0s/t2kKREewys=
github.com/peterbourgon/ff/v3 v3.1.0 h1:5JAeDK5j/zhKFjyHEZQXwXBoDijERaos10RE+xamOsY=
github.com/peterbourgon/ff/v3 v3.1.0/go.mod h1:XNJLY8EIl6MjMVjBS4F0+G0LYoAqs0DTa4rmHHukKDE=
go.jolheiser.com/beaver v1.1.2 h1:X8voMSTy+8QUFzHlvG89EUVZY/xPQe6fQLVjUPjTvWY=
go.jolheiser.com/beaver v1.1.2/go.mod h1:7X4F5+XOGSC3LejTShoBdqtRCnPWcnRgmYGmG3EKW8g=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae h1:/WDfKMnPU+m5M4xB+6x4kaepxRw6jWvR5iDRdvjHgy8=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

43
main.go 100644
View File

@ -0,0 +1,43 @@
package main
import (
"flag"
"github.com/peterbourgon/ff/v3"
"github.com/peterbourgon/ff/v3/fftoml"
"go.jolheiser.com/beaver"
"net/http"
"os"
"time"
)
func main() {
fs := flag.NewFlagSet("afk", flag.ExitOnError)
portFlag := fs.Int("port", 25565, "Port to listen on")
timeoutFlag := fs.Int("timeout", 15, "HTTP timeout")
discordFlag := fs.String("discord", "", "Discord invite link")
debugFlag := fs.Bool("debug", false, "Debug Logging")
if err := ff.Parse(fs, os.Args[1:],
ff.WithEnvVarPrefix("MCM_REGISTER"),
ff.WithConfigFileFlag("config"),
ff.WithAllowMissingConfigFile(true),
ff.WithConfigFileParser(fftoml.New().Parse),
); err != nil {
beaver.Fatal(err)
return
}
if *debugFlag {
beaver.Console.Level = beaver.DEBUG
}
http.DefaultClient.Timeout = time.Second * time.Duration(*timeoutFlag)
server, err := NewServer(*discordFlag)
if err != nil {
beaver.Error(err)
return
}
if err := server.Start(*portFlag); err != nil {
beaver.Error(err)
}
}

69
ping.go 100644
View File

@ -0,0 +1,69 @@
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/Tnze/go-mc/bot"
"github.com/Tnze/go-mc/chat"
"github.com/Tnze/go-mc/net"
pk "github.com/Tnze/go-mc/net/packet"
"github.com/google/uuid"
"go.jolheiser.com/beaver"
)
func (s *Server) acceptListPing(conn net.Conn) {
var p pk.Packet
for i := 0; i < 2; i++ {
err := conn.ReadPacket(&p)
if err != nil {
return
}
switch p.ID {
case 0x00:
err = conn.WritePacket(pk.Marshal(0x00, pk.String(listResp())))
case 0x01:
err = conn.WritePacket(p)
}
if err != nil {
return
}
}
}
type player struct {
Name string `json:"name"`
ID uuid.UUID `json:"id"`
}
// listResp return server status as JSON string
func listResp() string {
var list struct {
Version struct {
Name string `json:"name"`
Protocol int `json:"protocol"`
} `json:"version"`
Players struct {
Max int `json:"max"`
Online int `json:"online"`
Sample []player `json:"sample"`
} `json:"players"`
Description chat.Message `json:"description"`
FavIcon string `json:"favicon,omitempty"`
}
list.Version.Name = "Register Server"
list.Version.Protocol = bot.ProtocolVersion
list.Players.Max = 0
list.Players.Online = 0
list.Players.Sample = []player{}
list.Description = chat.Message{Text: "Login to register!"}
list.FavIcon = fmt.Sprintf("data:image/png;base64,%s", base64.StdEncoding.EncodeToString(favicon))
data, err := json.Marshal(list)
if err != nil {
beaver.Errorf("could not marshal JSON: %v", err)
}
return string(data)
}

156
server.go 100644
View File

@ -0,0 +1,156 @@
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
_ "embed"
"fmt"
"github.com/Tnze/go-mc/chat"
"github.com/Tnze/go-mc/net"
pk "github.com/Tnze/go-mc/net/packet"
"github.com/google/uuid"
"go.jolheiser.com/beaver"
)
//go:embed favicon.png
var favicon []byte
type Server struct {
privateKey *rsa.PrivateKey
publicKey []byte
discordInvite string
}
func NewServer(discordInvite string) (*Server, error) {
private, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return nil, fmt.Errorf("error generate private key: %v", err)
}
public, err := x509.MarshalPKIXPublicKey(private.Public())
if err != nil {
return nil, fmt.Errorf("error form public key to PKIX, ASN.1 DER: %v", err)
}
private.Precompute()
return &Server{
privateKey: private,
publicKey: public,
discordInvite: discordInvite,
}, nil
}
func (s *Server) Start(port int) error {
beaver.Infof("Listening on http://localhost:%d", port)
l, err := net.ListenMC(fmt.Sprintf(":%d", port))
if err != nil {
return fmt.Errorf("listen error: %v", err)
}
for {
conn, err := l.Accept()
if err != nil {
beaver.Errorf("Accept error: %v", err)
}
go s.acceptConn(conn)
}
}
func (s *Server) acceptConn(conn net.Conn) {
defer conn.Close()
// handshake
_, intention, err := s.handshake(conn)
if err != nil {
beaver.Errorf("Handshake error: %v", err)
return
}
switch intention {
default:
beaver.Errorf("Unknown handshake intention: %v", intention)
case 1:
s.acceptListPing(conn)
case 2:
s.handlePlaying(conn)
}
}
func (s *Server) handlePlaying(conn net.Conn) {
info, err := s.acceptLogin(conn)
if err != nil {
beaver.Errorf("login failed: %v", err)
return
}
verify, err := s.encryptionRequest(conn)
if err != nil {
beaver.Errorf("could not send encryption request: %v", err)
return
}
profile, secret, err := s.encryptionResponse(conn, info.Name, verify)
if err != nil {
beaver.Errorf("could not get encryption response: %v", err)
return
}
// TODO Register
econn, err := encryptedConn(conn, secret)
if err != nil {
beaver.Errorf("could not create encrypted connection: %v", err)
return
}
msg := fmt.Sprintf("Thanks for registering, %s!", profile.Name)
if s.discordInvite != "" {
msg += fmt.Sprintf("\n\nJoin the Discord\n%s", s.discordInvite)
}
packet := pk.Marshal(0x00,
chat.Message{Text: msg},
)
if err := packet.Pack(econn, 0); err != nil {
beaver.Errorf("could not disconnect player: %v", err)
}
}
type PlayerInfo struct {
Name string
UUID uuid.UUID
OPLevel int
}
// acceptLogin check player's account
func (s *Server) acceptLogin(conn net.Conn) (info PlayerInfo, err error) {
//login start
var p pk.Packet
err = conn.ReadPacket(&p)
if err != nil {
return
}
err = p.Scan((*pk.String)(&info.Name)) //decode username as pk.String
if err != nil {
return
}
return
}
// handshake receive and parse Handshake packet
func (s *Server) handshake(conn net.Conn) (protocol, intention int32, err error) {
var (
p pk.Packet
Protocol, Intention pk.VarInt
ServerAddress pk.String // ignored
ServerPort pk.UnsignedShort // ignored
)
// receive handshake packet
if err = conn.ReadPacket(&p); err != nil {
return
}
err = p.Scan(&Protocol, &ServerAddress, &ServerPort, &Intention)
return int32(Protocol), int32(Intention), err
}