apiary/cmd/apiary.go

246 lines
6.3 KiB
Go
Raw Normal View History

2021-04-10 05:58:01 +00:00
package main
import (
"context"
"fmt"
2021-04-10 06:16:59 +00:00
"net/http"
2021-04-10 05:58:01 +00:00
"os"
"os/signal"
"time"
2021-10-21 10:36:01 +00:00
sshlib "github.com/gliderlabs/ssh"
2021-04-10 05:58:01 +00:00
"github.com/urfave/cli/v2"
"github.uio.no/torjus/apiary"
"github.uio.no/torjus/apiary/config"
2021-10-21 08:33:28 +00:00
"github.uio.no/torjus/apiary/honeypot/ports"
2021-10-21 10:36:01 +00:00
"github.uio.no/torjus/apiary/honeypot/ssh"
"github.uio.no/torjus/apiary/honeypot/ssh/store"
2021-04-10 05:58:01 +00:00
"github.uio.no/torjus/apiary/web"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
2021-04-10 09:24:10 +00:00
"golang.org/x/crypto/acme/autocert"
2021-04-10 05:58:01 +00:00
)
func main() {
app := &cli.App{
Name: "apiary",
2021-04-12 06:58:39 +00:00
Version: apiary.FullVersion(),
2021-04-10 05:58:01 +00:00
Authors: []*cli.Author{
{
Name: "Torjus Håkestad",
Email: "torjus@usit.uio.no",
},
},
Commands: []*cli.Command{
{
Name: "serve",
Action: ActionServe,
Usage: "Start Apiary server",
},
},
}
if err := app.Run(os.Args); err != nil {
fmt.Printf("Error: %s\n", err)
os.Exit(1)
}
}
func ActionServe(c *cli.Context) error {
cfg, err := getConfig()
if err != nil {
return err
}
2021-04-10 09:24:10 +00:00
// Setup logging
2021-04-10 05:58:01 +00:00
loggers := setupLoggers(cfg)
2021-09-17 00:05:07 +00:00
loggers.rootLogger.Infow("Starting apiary", "version", apiary.FullVersion())
2021-04-10 05:58:01 +00:00
2021-04-10 09:24:10 +00:00
// Setup store
2021-04-10 05:58:01 +00:00
var s store.LoginAttemptStore
switch cfg.Store.Type {
case "MEMORY", "memory":
2021-09-17 00:01:43 +00:00
loggers.rootLogger.Debugw("Initializing store", "store_type", "memory")
2021-04-10 05:58:01 +00:00
s = &store.MemoryStore{}
case "POSTGRES", "postgres":
pgStore, err := store.NewPostgresStore(cfg.Store.Postgres.DSN)
if err != nil {
return err
}
if err := pgStore.InitDB(); err != nil {
return err
}
2021-09-17 00:01:43 +00:00
if cfg.Store.EnableCache {
loggers.rootLogger.Debugw("Initializing store", "store_type", "cache-postgres")
cachingStore := store.NewCachingStore(pgStore)
s = cachingStore
} else {
loggers.rootLogger.Debugw("Initializing store", "store_type", "postgres")
s = pgStore
}
2021-04-10 05:58:01 +00:00
default:
return fmt.Errorf("Invalid store configured")
}
2021-04-10 09:24:10 +00:00
// Setup honeypot
2021-10-21 10:36:01 +00:00
hs, err := ssh.NewHoneypotServer(cfg.Honeypot, s)
2021-04-10 05:58:01 +00:00
if err != nil {
return err
}
hs.Logger = loggers.honeypotLogger
2021-04-10 09:24:10 +00:00
// Setup webserver
2021-04-10 05:58:01 +00:00
web := web.NewServer(cfg.Frontend, hs, s)
web.AccessLogger = loggers.webAccessLogger
web.ServerLogger = loggers.webServerLogger
2021-04-10 09:24:10 +00:00
if cfg.Frontend.Autocert.Enable {
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(cfg.Frontend.Autocert.Domains...),
Email: cfg.Frontend.Autocert.Email,
}
if cfg.Frontend.Autocert.CacheDir != "" {
certManager.Cache = autocert.DirCache(cfg.Frontend.Autocert.CacheDir)
}
tlsConfig := certManager.TLSConfig()
web.TLSConfig = tlsConfig
}
2021-04-10 05:58:01 +00:00
2021-04-10 09:24:10 +00:00
// Setup interrupt handling
2021-04-10 05:58:01 +00:00
interruptChan := make(chan os.Signal, 1)
signal.Notify(interruptChan, os.Interrupt)
rootCtx, rootCancel := context.WithCancel(c.Context)
serversCtx, serversCancel := context.WithCancel(rootCtx)
2021-10-21 08:33:28 +00:00
// Setup portlistener, if configured
if cfg.Ports.Enable {
portsCtx, cancel := context.WithCancel(rootCtx)
defer cancel()
// TODO: Add more stores
store := &ports.MemoryStore{}
portsServer := ports.New(store)
portsServer.Logger = loggers.portsLogger
for _, port := range cfg.Ports.TCPPorts {
portsServer.AddTCPPort(port)
}
go func() {
loggers.rootLogger.Info("Starting ports server")
portsServer.Start(portsCtx)
}()
}
2021-04-10 05:58:01 +00:00
// Handle interrupt
go func() {
<-interruptChan
2021-04-10 06:16:59 +00:00
loggers.rootLogger.Info("Interrupt received, shutting down")
2021-04-10 05:58:01 +00:00
serversCancel()
}()
// Start ssh server
go func() {
2021-04-10 06:16:59 +00:00
loggers.rootLogger.Info("Starting SSH server")
2021-10-21 10:36:01 +00:00
if err := hs.ListenAndServe(); err != nil && err != sshlib.ErrServerClosed {
2021-04-10 06:16:59 +00:00
loggers.rootLogger.Warnw("SSH server returned error", "error", err)
}
2021-04-10 05:58:01 +00:00
}()
// Start web server
go func() {
2021-04-10 06:16:59 +00:00
loggers.rootLogger.Info("Starting web server")
2021-04-10 09:24:10 +00:00
if err := web.StartServe(); err != nil && err != http.ErrServerClosed {
2021-04-10 06:16:59 +00:00
loggers.rootLogger.Warnw("Web server returned error", "error", err)
}
2021-04-10 05:58:01 +00:00
}()
go func() {
<-serversCtx.Done()
// Stop SSH server
sshShutdownCtx, sshShutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer sshShutdownCancel()
loggers.rootLogger.Info("SSH server shutdown started")
if err := hs.Shutdown(sshShutdownCtx); err != nil {
loggers.rootLogger.Infow("Error shutting down SSH server", "error", err)
}
loggers.rootLogger.Info("SSH server shutdown complete")
// Stop Web server
webShutdownCtx, webShutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer webShutdownCancel()
loggers.rootLogger.Info("Web server shutdown started")
if err := web.Shutdown(webShutdownCtx); err != nil {
loggers.rootLogger.Infow("Error shutting down web server", "error", err)
}
loggers.rootLogger.Info("Web server shutdown complete")
rootCancel()
}()
<-rootCtx.Done()
return nil
}
type loggerCollection struct {
rootLogger *zap.SugaredLogger
honeypotLogger *zap.SugaredLogger
webAccessLogger *zap.SugaredLogger
webServerLogger *zap.SugaredLogger
2021-10-21 08:33:28 +00:00
portsLogger *zap.SugaredLogger
2021-04-10 05:58:01 +00:00
}
func setupLoggers(cfg config.Config) *loggerCollection {
logEncoderCfg := zap.NewProductionEncoderConfig()
logEncoderCfg.EncodeCaller = func(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {}
level := zap.NewAtomicLevelAt(zap.InfoLevel)
logEncoderCfg.EncodeLevel = zapcore.CapitalColorLevelEncoder
logEncoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder
logEncoderCfg.EncodeDuration = zapcore.NanosDurationEncoder
rootLoggerCfg := &zap.Config{
Level: level,
OutputPaths: []string{"stdout"},
ErrorOutputPaths: []string{"stderr"},
Encoding: "console",
EncoderConfig: logEncoderCfg,
}
rootLogger, err := rootLoggerCfg.Build()
if err != nil {
panic(err)
}
return &loggerCollection{
rootLogger: rootLogger.Named("APP").Sugar(),
honeypotLogger: rootLogger.Named("HON").Sugar(),
webAccessLogger: rootLogger.Named("ACC").Sugar(),
webServerLogger: rootLogger.Named("WEB").Sugar(),
2021-10-21 08:33:28 +00:00
portsLogger: rootLogger.Named("PRT").Sugar(),
2021-04-10 05:58:01 +00:00
}
}
func getConfig() (config.Config, error) {
defaultLocations := []string{
"apiary.toml",
"/etc/apiary.toml",
2021-04-10 07:05:30 +00:00
"/etc/apiary/apiary.toml",
2021-04-10 05:58:01 +00:00
}
for _, fname := range defaultLocations {
if _, err := os.Stat(fname); os.IsNotExist(err) {
continue
}
cfg, err := config.FromFile(fname)
if err != nil {
return config.Config{}, err
}
return cfg, nil
}
return config.Config{}, fmt.Errorf("Could not find config file")
}