-
Notifications
You must be signed in to change notification settings - Fork 2
/
route.go
225 lines (195 loc) · 6.33 KB
/
route.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
package main
import (
"github.com/jackc/pgx/v4"
"github.com/logrusorgru/aurora/v3"
"io/ioutil"
"log"
"net/http"
"strings"
)
// Route defines a header to be checked for actions, and an array of actions to handle.
type Route struct {
HeaderName string
Actions []Action
}
// Action contains information about how a specified action should be handled.
type Action struct {
ActionName string
Callback func(e *Envelope)
NeedsAuthentication bool
ServiceType string
}
// NewRoute produces a new route struct with appropriate header defaults.
func NewRoute() Route {
return Route{
HeaderName: "SOAPAction",
}
}
// RoutingGroup defines a group of actions for a given service type.
type RoutingGroup struct {
Route *Route
ServiceType string
}
// HandleGroup returns a routing group type for the given service type.
func (r *Route) HandleGroup(serviceType string) RoutingGroup {
return RoutingGroup{
Route: r,
ServiceType: serviceType,
}
}
// Unauthenticated associates an action to a function to be handled without authentication.
func (r *RoutingGroup) Unauthenticated(action string, function func(e *Envelope)) {
r.Route.Actions = append(r.Route.Actions, Action{
ActionName: action,
Callback: function,
NeedsAuthentication: false,
ServiceType: r.ServiceType,
})
}
// Authenticated associates an action to a function to be handled with authentication.
func (r *RoutingGroup) Authenticated(action string, function func(e *Envelope)) {
r.Route.Actions = append(r.Route.Actions, Action{
ActionName: action,
Callback: function,
NeedsAuthentication: true,
ServiceType: r.ServiceType,
})
}
func (route *Route) Handle() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s via %s", aurora.Yellow(r.Method), aurora.Cyan(r.URL), aurora.Cyan(r.Host))
// Check if there's a header of the type we need.
service, actionName := parseAction(r.Header.Get("SOAPAction"))
if service == "" || actionName == "" || r.Method != "POST" {
printError(w, "WiiSOAP can't handle this. Try again later.")
return
}
// Verify this is a service type we know.
switch service {
case "ecs":
case "ias":
case "cas":
break
default:
printError(w, "Unsupported service type...")
return
}
debugPrint("[!] Incoming ", aurora.Yellow(strings.ToUpper(service)), " request - handling request ", aurora.Yellow(actionName))
body, err := ioutil.ReadAll(r.Body)
if err != nil {
printError(w, "Error reading request body...")
return
}
// Ensure we can route to this action before processing.
// Search all registered actions and find a matching action.
var action Action
for _, routeAction := range route.Actions {
if routeAction.ActionName == actionName && routeAction.ServiceType == service {
action = routeAction
}
}
// Action is only properly populated if we found it previously.
if action.ActionName == "" && action.ServiceType == "" {
printError(w, "WiiSOAP can't handle this. Try again later.")
return
}
debugPrint("Client sent:\n", aurora.BrightGreen(string(body)))
// Insert the current action being performed.
e, err := NewEnvelope(service, actionName, body)
if err != nil {
printError(w, "Error interpreting request body: "+err.Error())
return
}
// Check for authentication.
if action.NeedsAuthentication {
success, err := checkAuthentication(e)
// Catch-all in case of invalid formatting or true invalidity.
if !success || (err != nil) {
http.Error(w, "Unauthorized.", http.StatusUnauthorized)
return
}
}
// Call this action.
action.Callback(e)
// The action has now finished its task, and we can serialize.
// Output may or may not truly be XML depending on where things failed.
// We'll expect the best, however.
w.Header().Set("Content-Type", "text/xml; charset=utf-8")
success, contents := e.becomeXML()
if !success {
// This is not what we wanted, and we need to reflect that.
w.WriteHeader(http.StatusInternalServerError)
}
w.Write([]byte(contents))
debugPrint("Writing response:\n", aurora.BrightCyan(contents))
})
}
const (
RouteVerifyHashedStatement = `SELECT 1 FROM userbase WHERE device_token_hashed=$1 AND account_id=$2 AND device_id=$3`
RouteVerifyUnhashedStatement = `SELECT 1 FROM userbase WHERE device_token=$1 AND account_id=$2 AND device_id=$3`
)
// checkAuthentication validates various factors from a given request requiring authentication.
func checkAuthentication(e *Envelope) (bool, error) {
if ignoreAuth {
return true, nil
}
// Get necessary authentication identifiers.
deviceToken, err := e.getKey("DeviceToken")
if err != nil {
return false, err
}
accountId, err := e.AccountId()
if err != nil {
return false, err
}
hash, tokenType := determineTokenFormat(deviceToken)
if hash == "" || tokenType == TokenTypeInvalid {
return false, nil
}
var statement string
if tokenType == TokenTypeHashed {
statement = RouteVerifyHashedStatement
} else if tokenType == TokenTypeUnhashed {
statement = RouteVerifyUnhashedStatement
}
// Check using various input given.
row := pool.QueryRow(ctx, statement, hash, accountId, e.DeviceId())
var throwaway int
err = row.Scan(&throwaway)
if err == pgx.ErrNoRows {
return false, err
} else if err != nil {
// We shouldn't encounter other errors.
debugPrint("error occurred while checking authentication: %v\n", err)
return false, err
} else {
return true, nil
}
}
// validateTokenFormat confirms the prefix, size and type of tokens,
// which are expected to be in a format such as
// WT-5d41402abc4b2a76b9719d911017c592 or ST-aech1kae4sheequ8Zohwa.
// It returns an empty string on failure, alongside TokenTypeInvalid.
func determineTokenFormat(token string) (string, TokenType) {
tokenLen := len(token)
if tokenLen < 3 {
return "", TokenTypeInvalid
}
switch token[:3] {
case "ST-":
// Unhashed tokens are 24 characters in length.
if tokenLen == 24 {
return token[3:24], TokenTypeUnhashed
}
case "WT-":
// Hashed tokens are 35 characters in length.
if tokenLen == 35 {
return token[3:35], TokenTypeHashed
}
}
return "", TokenTypeInvalid
}
func printError(w http.ResponseWriter, reason string) {
http.Error(w, reason, http.StatusInternalServerError)
debugPrint("Failed to handle request: ", aurora.Red(reason))
}