/
models.go
177 lines (161 loc) · 4.3 KB
/
models.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
package models
import (
"crypto/rand"
"fmt"
"io"
"time"
"crypto/tls"
"crypto/x509"
"io/ioutil"
"bitbucket.org/liamstask/goose/lib/goose"
mysql "github.com/go-sql-driver/mysql"
"github.com/gophish/gophish/config"
log "github.com/gophish/gophish/logger"
"github.com/jinzhu/gorm"
_ "github.com/mattn/go-sqlite3" // Blank import needed to import sqlite3
)
var db *gorm.DB
var conf *config.Config
const MaxDatabaseConnectionAttempts int = 10
const (
CampaignInProgress string = "In progress"
CampaignQueued string = "Queued"
CampaignCreated string = "Created"
CampaignEmailsSent string = "Emails Sent"
CampaignComplete string = "Completed"
EventSent string = "Email Sent"
EventSendingError string = "Error Sending Email"
EventOpened string = "Email Opened"
EventClicked string = "Clicked Link"
EventDataSubmit string = "Submitted Data"
EventReported string = "Email Reported"
EventProxyRequest string = "Proxied request"
StatusSuccess string = "Success"
StatusQueued string = "Queued"
StatusSending string = "Sending"
StatusUnknown string = "Unknown"
StatusScheduled string = "Scheduled"
StatusRetry string = "Retrying"
Error string = "Error"
)
// Flash is used to hold flash information for use in templates.
type Flash struct {
Type string
Message string
}
// Response contains the attributes found in an API response
type Response struct {
Message string `json:"message"`
Success bool `json:"success"`
Data interface{} `json:"data"`
}
// Copy of auth.GenerateSecureKey to prevent cyclic import with auth library
func generateSecureKey() string {
k := make([]byte, 32)
io.ReadFull(rand.Reader, k)
return fmt.Sprintf("%x", k)
}
func chooseDBDriver(name, openStr string) goose.DBDriver {
d := goose.DBDriver{Name: name, OpenStr: openStr}
switch name {
case "mysql":
d.Import = "github.com/go-sql-driver/mysql"
d.Dialect = &goose.MySqlDialect{}
// Default database is sqlite3
default:
d.Import = "github.com/mattn/go-sqlite3"
d.Dialect = &goose.Sqlite3Dialect{}
}
return d
}
// Setup initializes the Conn object
// It also populates the Gophish Config object
func Setup(c *config.Config) error {
// Setup the package-scoped config
conf = c
// Setup the goose configuration
migrateConf := &goose.DBConf{
MigrationsDir: conf.MigrationsPath,
Env: "production",
Driver: chooseDBDriver(conf.DBName, conf.DBPath),
}
// Get the latest possible migration
latest, err := goose.GetMostRecentDBVersion(migrateConf.MigrationsDir)
if err != nil {
log.Error(err)
return err
}
// Register certificates for tls encrypted db connections
if conf.DBSSLCaPath != "" {
switch conf.DBName {
case "mysql":
rootCertPool := x509.NewCertPool()
pem, err := ioutil.ReadFile(conf.DBSSLCaPath)
if err != nil {
log.Error(err)
return err
}
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
log.Error("Failed to append PEM.")
return err
}
mysql.RegisterTLSConfig("ssl_ca", &tls.Config{
RootCAs: rootCertPool,
})
// Default database is sqlite3, which supports no tls, as connection
// is file based
default:
}
}
// Open our database connection
i := 0
for {
db, err = gorm.Open(conf.DBName, conf.DBPath)
if err == nil {
break
}
if err != nil && i >= MaxDatabaseConnectionAttempts {
log.Error(err)
return err
}
i += 1
log.Warn("waiting for database to be up...")
time.Sleep(5 * time.Second)
}
db.LogMode(false)
db.SetLogger(log.Logger)
db.DB().SetMaxOpenConns(1)
if err != nil {
log.Error(err)
return err
}
// Migrate up to the latest version
err = goose.RunMigrationsOnDb(migrateConf, migrateConf.MigrationsDir, latest, db.DB())
if err != nil {
log.Error(err)
return err
}
// Create the admin user if it doesn't exist
var userCount int64
db.Model(&User{}).Count(&userCount)
adminRole, err := GetRoleBySlug(RoleAdmin)
if err != nil {
log.Error(err)
return err
}
if userCount == 0 {
initUser := User{
Username: "admin",
Hash: "$2a$10$IYkPp0.QsM81lYYPrQx6W.U6oQGw7wMpozrKhKAHUBVL4mkm/EvAS", //gophish
Role: adminRole,
RoleID: adminRole.ID,
}
initUser.ApiKey = generateSecureKey()
err = db.Save(&initUser).Error
if err != nil {
log.Error(err)
return err
}
}
return nil
}