/
main.go
213 lines (170 loc) · 4.9 KB
/
main.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
package main
import (
"crypto/tls"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/alecthomas/kingpin"
"github.com/go-martini/martini"
"github.com/jmoiron/sqlx"
"github.com/martini-contrib/gzip"
"github.com/martini-contrib/method"
)
const TestString = "Umse ♪"
var templateManager *TemplateManager
var restrictionHandlers map[string]RestrictionHandler
var config *configuration
var sessions *SessionMiddleware
var (
password = kingpin.Flag("password", "Encryption key in plain text (discouraged)").String()
configFile = kingpin.Flag("config", "Configuration file to use").ExistingFile()
)
func main() {
kingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version("1.0").Author("Christoph Mewes")
kingpin.CommandLine.Help = "HTTP application server to run the Raziel secret management"
kingpin.Parse()
if *configFile == "" {
kingpin.FatalUsage("No configuration file (--config) given!")
}
// load config file
err := loadConfigFile()
if err != nil {
kingpin.FatalUsage(err.Error())
}
// connect to database
database, err := sqlx.Connect("mysql", config.Database.Source)
if err != nil {
kingpin.FatalUsage(err.Error())
}
validateMasterPassword(database)
// init restriction handlers
restrictionHandlers = make(map[string]RestrictionHandler)
addRestrictionHandler(ApiKeyRestriction{})
addRestrictionHandler(TlsCertRestriction{})
addRestrictionHandler(OriginIpRestriction{})
addRestrictionHandler(DateRestriction{})
addRestrictionHandler(TimeRestriction{})
addRestrictionHandler(FileRestriction{})
addRestrictionHandler(HitLimitRestriction{})
addRestrictionHandler(ThrottleRestriction{})
// init templates
templateManager = NewTemplateManager("templates")
// setup basic Martini server
martini.Env = martini.Dev
if config.Environment == "production" || config.Environment == "prod" {
martini.Env = martini.Prod
}
m := martini.New()
m.Use(martini.Logger())
m.Use(gzip.All())
m.Use(martini.Recovery())
m.Use(martini.Static("www"))
m.Use(method.Override())
// force all handlers to run inside a transaction
m.Use(func(c martini.Context) {
tx := database.MustBegin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
panic(r)
}
}()
c.Map(tx)
c.Next()
err := tx.Commit()
if err != nil {
panic(err)
}
})
// setup session and CSRF support
duration, err := time.ParseDuration(config.Session.Lifetime)
if err != nil {
log.Fatal("Invalid session lifetime configured: " + err.Error())
}
sessions = NewSessionMiddleware(cookieOptions{
Name: config.Session.CookieName,
MaxAge: duration,
HttpOnly: true,
Secure: config.Session.Secure,
})
sessions.Setup(m)
// re-compile all templates on each hit
if martini.Env != martini.Prod {
m.Use(func() {
templateManager.Init()
})
}
// use a custom return handler to make our mini response structs possible
// (this overwrites the existing handler)
m.Map(newReturnHandler())
r := martini.NewRouter()
m.MapTo(r, (*martini.Routes)(nil))
m.Action(r.Handle)
martini := &martini.ClassicMartini{m, r}
setupDashboardCtrl(martini)
setupProfileCtrl(martini)
setupLoginCtrl(martini)
setupSecretsCtrl(martini)
setupUsersCtrl(martini)
setupConsumersCtrl(martini)
setupAuditLogCtrl(martini)
setupAccessLogCtrl(martini)
setupDeliveryCtrl(martini)
// setup our own http server and configure TLS
srv := &http.Server{
Addr: config.Server.Listen,
Handler: martini,
TLSConfig: &tls.Config{
CipherSuites: config.CipherSuites(),
},
}
log.Fatal(srv.ListenAndServeTLS(config.Server.Certificate, config.Server.PrivateKey))
}
func addRestrictionHandler(handler RestrictionHandler) {
restrictionHandlers[handler.GetIdentifier()] = handler
}
func loadConfigFile() error {
content, err := ioutil.ReadFile(*configFile)
if err != nil {
return err
}
config = &configuration{}
err = json.Unmarshal(content, &config)
if err != nil {
return err
}
return nil
}
type dbConfig struct {
Key string `db:"key"`
Value []byte `db:"value"`
}
func validateMasterPassword(db *sqlx.DB) {
c := dbConfig{}
db.Get(&c, "SELECT `key`, `value` FROM `config` WHERE `key` = 'teststring'")
if c.Key == "" {
panic("Could not read the teststring from the config table. Your database is broken.")
}
// not yet initialized, so store the ciphertext
if len(c.Value) == 0 {
ciphertext, err := Encrypt([]byte(TestString))
if err != nil {
panic(err)
}
_, err = db.Exec("UPDATE `config` SET `value` = ? WHERE `key` = ?", ciphertext, c.Key)
if err != nil {
panic("Could not write initial password marker: " + err.Error())
}
} else {
plaintext, err := Decrypt(c.Value)
if err != nil {
panic("The configured password is not usable for the configured database.")
}
// this should never happen: a wrong password should always yield an error in Decrypt()
if TestString != string(plaintext) {
panic("The configured password is not usable for the configured database.")
}
}
}