Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
297 lines (247 loc) · 8.76 KB
/
Copy pathmain.go
File metadata and controls
297 lines (247 loc) · 8.76 KB
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*
* Copyright (C) 2024 Nethesis S.r.l.
* http://www.nethesis.it - info@nethesis.it
*
* SPDX-License-Identifier: GPL-2.0-only
*
* author: Edoardo Spadoni <edoardo.spadoni@nethesis.it>
*/
package main
import (
"context"
"io"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/fatih/structs"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
"golang.org/x/time/rate"
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/NethServer/nethsecurity-controller/api/response"
"github.com/NethServer/nethsecurity-controller/api/configuration"
"github.com/NethServer/nethsecurity-controller/api/internal/sshterm"
"github.com/NethServer/nethsecurity-controller/api/logs"
"github.com/NethServer/nethsecurity-controller/api/methods"
"github.com/NethServer/nethsecurity-controller/api/middleware"
"github.com/NethServer/nethsecurity-controller/api/routines"
"github.com/NethServer/nethsecurity-controller/api/socket"
"github.com/NethServer/nethsecurity-controller/api/storage"
"github.com/NethServer/nethsecurity-controller/api/utils"
)
// @title NethSecurity Controller API Server
// @version 1.0
// @description NethSecurity Controller API Server is used to manage multiple stand-alone NethSecurity instances
// @termsOfService https://nethserver.org/terms/
// @contact.name NethServer Developer Team
// @contact.url https://nethserver.org/support
// @license.name GNU GENERAL PUBLIC LICENSE
// @host localhost:5000
// @schemes http
// @BasePath /api
func setup() *gin.Engine {
// init logs with syslog
logs.Init("nethsecurity_controller")
// init configuration
configuration.Init()
// init storage
storage.Init()
// init socket connection
socket.Init()
// init geoip
utils.InitGeoIP()
// start geoip refresh loop
go routines.RefreshGeoIPDatabase()
// starts remote info loop
go routines.RefreshRemoteInfoLoop()
// disable log to stdout when running in release mode
if gin.Mode() == gin.ReleaseMode {
gin.DefaultWriter = io.Discard
}
// init routers
router := gin.Default()
// the app is only ever reached via the local reverse proxy (module Traefik,
// itself behind the NS8 core Traefik), both on loopback: trust only that
// hop's X-Forwarded-For so ClientIP() resolves the real client IP for
// RateLimiter instead of bucketing all traffic under 127.0.0.1
router.SetTrustedProxies([]string{"127.0.0.1", "::1"})
// Generous global per-IP rate limit as a coarse safety net across all
// routes (a looser second layer behind the tighter per-route limits on
// the pre-auth routes). Set GLOBAL_RATE_LIMIT_AVERAGE=0 to disable.
if configuration.Config.GlobalRateLimitAverage > 0 {
router.Use(middleware.RateLimiter(
rate.Limit(configuration.Config.GlobalRateLimitAverage),
configuration.Config.GlobalRateLimitBurst,
))
}
// add default compression
router.Use(gzip.Gzip(gzip.DefaultCompression))
// cors configuration only in debug mode GIN_MODE=debug (default)
if gin.Mode() == gin.DebugMode {
// gin gonic cors conf
corsConf := cors.DefaultConfig()
corsConf.AllowHeaders = []string{"Authorization", "Content-Type", "Accept"}
corsConf.AllowAllOrigins = true
router.Use(cors.New(corsConf))
}
// define api group
api := router.Group("/")
// define login and logout endpoint. BodyLimit caps each request's size;
// the global per-IP rate limiter (see above) bounds request frequency
// across every route, including these pre-authentication ones.
api.POST("/login", middleware.BodyLimit(32<<10), middleware.InstanceJWT().LoginHandler)
api.POST("/logout", middleware.BodyLimit(1<<10), middleware.InstanceJWT().LogoutHandler)
// define healthcheck endpoint
api.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
// 2FA APIs
api.POST("/2fa/otp-verify", middleware.BodyLimit(32<<10), methods.OTPVerify)
// define server registration
api.POST("/units/register", middleware.BodyLimit(8<<10), methods.RegisterUnit)
// define JWT middleware
api.Use(middleware.InstanceJWT().MiddlewareFunc())
{
// refresh handler
api.GET("/refresh", middleware.InstanceJWT().RefreshHandler)
// 2FA APIs
api.GET("/2fa", methods.Get2FAStatus)
api.DELETE("/2fa", methods.Del2FAStatus)
api.GET("/2fa/qr-code", methods.QRCode)
// accounts APIs
accounts := api.Group("/accounts")
{
// accounts CRUD
accounts.GET("", methods.GetAccounts)
accounts.GET("/:account_id", methods.GetAccount)
accounts.POST("", methods.AddAccount)
accounts.PUT("/:account_id", methods.UpdateAccount)
accounts.DELETE("/:account_id", methods.DeleteAccount)
// account password change
accounts.PUT("/password", methods.UpdatePassword)
// ssh keys read and write
accounts.GET("/ssh-keys", methods.GetSSHKeys)
accounts.POST("/ssh-keys", methods.AddSSHKeys)
accounts.DELETE("/ssh-keys", methods.DeleteSSHKeys)
}
// default APIs
defaults := api.Group("/defaults")
{
defaults.GET("", methods.GetDefaults)
}
// units APIs
units := api.Group("/units")
{
units.GET("", methods.GetUnits)
units.GET("/:unit_id", methods.GetUnit)
units.GET("/:unit_id/info", methods.GetUnitInfo)
units.GET("/:unit_id/token", methods.GetToken)
units.POST("", methods.AddUnit)
units.DELETE("/:unit_id", methods.DeleteUnit)
}
// unit_groups APIs
unitGroups := api.Group("/unit_groups")
{
unitGroups.GET("", methods.ListUnitGroups)
unitGroups.GET("/:group_id", methods.GetUnitGroup)
unitGroups.POST("", methods.AddUnitGroup)
unitGroups.PUT("/:group_id", methods.UpdateUnitGroup)
unitGroups.DELETE("/:group_id", methods.DeleteUnitGroup)
}
// platforms APIs
api.GET("/platform", methods.GetPlatformInfo)
}
// Ingest APIs: receive data from firewalls
authorized := router.Group("/ingest", middleware.BasicUnitAuth(), middleware.BodyLimit(8<<20)) // 8 Mib limit
authorized.POST("/info", methods.AddInfo)
authorized.POST("/:firewall_api", methods.HandelMonitoring)
// Forwarded authentication middleware
forwarded := router.Group("/auth", middleware.BasicUserAuth())
forwarded.GET("", func(c *gin.Context) {
c.Status(http.StatusOK)
})
forwarded.GET("/:unit_id", func(c *gin.Context) {
c.Status(http.StatusOK)
})
// SSH terminal over websocket, cookie auth since browsers can't set headers on websockets
pool, _ := storage.ReportInstance()
terminal := sshterm.New(sshterm.PGUnits{Pool: pool}, sshterm.DirKeys{Dir: configuration.Config.DataDir})
router.GET("/units/:unit_id/terminal", middleware.CookieJWT().MiddlewareFunc(), func(c *gin.Context) {
user := jwt.ExtractClaims(c)["id"].(string)
unitID := c.Param("unit_id")
if !methods.UserCanAccessUnit(user, unitID) {
c.JSON(http.StatusForbidden, structs.Map(response.StatusForbidden{
Code: 403,
Message: "user does not have access to this unit",
Data: nil,
}))
return
}
terminal.Serve(c.Writer, c.Request, user, unitID)
})
// Prometheus metrics endpoint
prometheus := router.Group("/prometheus", gin.BasicAuth(gin.Accounts{
configuration.Config.PrometheusAuthUsername: configuration.Config.PrometheusAuthPassword,
}))
prometheus.GET("/targets", methods.GetPrometheusTargets)
// handle missing endpoint
router.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, structs.Map(response.StatusNotFound{
Code: 404,
Message: "API not found",
Data: nil,
}))
})
return router
}
func main() {
router := setup()
// Create HTTP servers for each listen address
servers := make([]*http.Server, len(configuration.Config.ListenAddress))
for i, addr := range configuration.Config.ListenAddress {
servers[i] = &http.Server{
Addr: addr,
Handler: router,
}
}
// Start servers in goroutines
for _, srv := range servers {
go func(server *http.Server) {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}(srv)
}
// Wait for interrupt signal
// - SIGINT and SIGTERM for graceful shutdown
// - SIGUSR1 to reload ACLs
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM, syscall.SIGUSR1)
for {
sig := <-quit
switch sig {
case syscall.SIGUSR1:
logs.Logs.Println("[INFO][API] Received SIGUSR1, reloading ACLs...")
storage.ReloadACLs()
// Continue running after ACL reload
case syscall.SIGINT, syscall.SIGTERM:
logs.Logs.Println("[INFO][API] Shutdown signal received, shutting down servers...")
// The context is used to inform the server it has 5 seconds to finish
// the request it is currently handling
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Shutdown all servers gracefully
for _, srv := range servers {
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server forced to shutdown:", err)
}
}
logs.Logs.Println("[INFO][API] Servers exiting")
return
}
}
}