| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package auditor |
| 18 | |
| 19 | import ( |
| 20 | "database/sql" |
| 21 | "encoding/base64" |
| 22 | "fmt" |
| 23 | "os" |
| 24 | "time" |
| 25 | |
| 26 | "github.com/spf13/cobra" |
| 27 | "github.com/streadway/amqp" |
| 28 | |
| 29 | "github.com/sassoftware/relic/v7/cmdline/shared" |
| 30 | "github.com/sassoftware/relic/v7/config" |
| 31 | "github.com/sassoftware/relic/v7/internal/activation" |
| 32 | "github.com/sassoftware/relic/v7/lib/audit" |
| 33 | |
| 34 | _ "github.com/lib/pq" |
| 35 | ) |
| 36 | |
| 37 | var AuditCmd = &cobra.Command{ |
| 38 | Use: "audit", |
| 39 | Short: "Receive audit data from relic servers", |
| 40 | RunE: auditCmd, |
| 41 | } |
| 42 | |
| 43 | var argConfigFile string |
| 44 | |
| 45 | func init() { |
| 46 | shared.RootCmd.AddCommand(AuditCmd) |
| 47 | AuditCmd.Flags().StringVarP(&argConfigFile, "config", "c", "", "Name of relic-audit configuration file") |
| 48 | } |
| 49 | |
| 50 | func auditCmd(cmd *cobra.Command, args []string) error { |
| 51 | if err := readConfig(); err != nil { |
| 52 | return err |
| 53 | } |
| 54 | configs, err := getServerConfs() |
| 55 | if err != nil { |
| 56 | return err |
| 57 | } |
| 58 | // test logfile but open it as-needed to make rotation simpler |
| 59 | if auditConfig.LogFile != "" { |
| 60 | f, err := os.OpenFile(auditConfig.LogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) |
| 61 | if err != nil { |
| 62 | return err |
| 63 | } |
| 64 | f.Close() |
| 65 | } |
| 66 | // open and test database connection. the sql module manages a pool for goroutines as needed. |
| 67 | db, err := openDb() |
| 68 | if err != nil { |
| 69 | return err |
| 70 | } |
| 71 | if err := db.Ping(); err != nil { |
| 72 | return err |
| 73 | } |
| 74 | // start listeners for each broker |
| 75 | for _, cfg := range configs { |
| 76 | if err := startListener(cfg, db); err != nil { |
| 77 | return fmt.Errorf("%s: %w", cfg.Path(), err) |
| 78 | } |
| 79 | } |
| 80 | _ = activation.DaemonReady() |
| 81 | // nothing left to do in this goroutine |
| 82 | time.Sleep(1<<63 - 1) |
| 83 | return nil |
| 84 | } |
| 85 | |
| 86 | func openDb() (*sql.DB, error) { |
| 87 | return sql.Open("postgres", auditConfig.DatabaseURI) |
| 88 | } |
| 89 | |
| 90 | func startListener(conf *config.Config, db *sql.DB) error { |
| 91 | aconf := conf.Amqp |
| 92 | l, err := NewListener(aconf) |
| 93 | if err != nil { |
| 94 | return err |
| 95 | } |
| 96 | fmt.Fprintf(os.Stderr, "%s: connected\n", conf.Path()) |
| 97 | go func() { |
| 98 | l2 := l |
| 99 | var start time.Time |
| 100 | delay := new(expBackoff) |
| 101 | for { |
| 102 | if l2 != nil { |
| 103 | if err := l2.Loop(db); err != nil { |
| 104 | fmt.Fprintf(os.Stderr, "%s: %s\n", conf.Path(), err) |
| 105 | } |
| 106 | l2.Close() |
| 107 | l2 = nil |
| 108 | } |
| 109 | delay.CancelReset() |
| 110 | if time.Since(start) < time.Second { |
| 111 | delay.Sleep() |
| 112 | } |
| 113 | var err error |
| 114 | start = time.Now() |
| 115 | l2, err = NewListener(aconf) |
| 116 | if err != nil { |
| 117 | fmt.Fprintf(os.Stderr, "%s: %s\n", conf.Path(), err) |
| 118 | } else { |
| 119 | fmt.Fprintf(os.Stderr, "%s: connection reestablished\n", conf.Path()) |
| 120 | delay.ResetAfter(60 * time.Second) |
| 121 | } |
| 122 | } |
| 123 | }() |
| 124 | return nil |
| 125 | } |
| 126 | |
| 127 | type Listener struct { |
| 128 | aconf *config.AmqpConfig |
| 129 | conn *amqp.Connection |
| 130 | ch *amqp.Channel |
| 131 | qname string |
| 132 | } |
| 133 | |
| 134 | func NewListener(aconf *config.AmqpConfig) (*Listener, error) { |
| 135 | conn, err := audit.Connect(aconf) |
| 136 | if err != nil { |
| 137 | return nil, err |
| 138 | } |
| 139 | ch, err := conn.Channel() |
| 140 | if err != nil { |
| 141 | conn.Close() |
| 142 | return nil, err |
| 143 | } |
| 144 | hostname, _ := os.Hostname() |
| 145 | if hostname == "" { |
| 146 | hostname = "unknown" |
| 147 | } |
| 148 | qname := "audit." + hostname |
| 149 | l := &Listener{aconf, conn, ch, qname} |
| 150 | if err := ch.ExchangeDeclarePassive(aconf.ExchangeName(), amqp.ExchangeFanout, true, false, false, false, nil); err != nil { |
| 151 | l.Close() |
| 152 | return nil, err |
| 153 | } |
| 154 | if _, err := ch.QueueDeclare(qname, true, false, false, false, nil); err != nil { |
| 155 | l.Close() |
| 156 | return nil, err |
| 157 | } |
| 158 | if err := ch.QueueBind(qname, "", aconf.ExchangeName(), false, nil); err != nil { |
| 159 | l.Close() |
| 160 | return nil, err |
| 161 | } |
| 162 | return l, nil |
| 163 | } |
| 164 | |
| 165 | func (l *Listener) Loop(db *sql.DB) error { |
| 166 | errch := l.conn.NotifyClose(make(chan *amqp.Error, 1)) |
| 167 | delivery, err := l.ch.Consume(l.qname, "", false, true, false, false, nil) |
| 168 | if err != nil { |
| 169 | return err |
| 170 | } |
| 171 | for { |
| 172 | d, ok := <-delivery |
| 173 | if !ok { |
| 174 | break |
| 175 | } |
| 176 | info, err := audit.Parse(d.Body) |
| 177 | if err != nil { |
| 178 | fmt.Fprintf(os.Stderr, "parse failed: %s\n", err) |
| 179 | if err := d.Ack(false); err != nil { |
| 180 | return err |
| 181 | } |
| 182 | continue |
| 183 | } |
| 184 | if err := logToAll(db, info); err != nil { |
| 185 | // reject the message, disconnect, and start a timeout |
| 186 | fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) |
| 187 | _ = d.Reject(true) |
| 188 | return err |
| 189 | } |
| 190 | if err := d.Ack(false); err != nil { |
| 191 | return err |
| 192 | } |
| 193 | } |
| 194 | if err := <-errch; err != nil { |
| 195 | return err |
| 196 | } |
| 197 | return nil |
| 198 | } |
| 199 | |
| 200 | func logToAll(db *sql.DB, info *audit.Info) (err error) { |
| 201 | tx, err := db.Begin() |
| 202 | if err != nil { |
| 203 | return err |
| 204 | } |
| 205 | defer tx.Rollback() //nolint:Errcheck |
| 206 | rowid, err := insertRow(db, info) |
| 207 | if err != nil { |
| 208 | return err |
| 209 | } |
| 210 | if err := logGraylog(info, rowid); err != nil { |
| 211 | return err |
| 212 | } |
| 213 | if err := logToFile(info, rowid); err != nil { |
| 214 | return err |
| 215 | } |
| 216 | return tx.Commit() |
| 217 | } |
| 218 | |
| 219 | func insertRow(db *sql.DB, info *audit.Info) (int64, error) { |
| 220 | blob, err := info.Marshal() |
| 221 | if err != nil { |
| 222 | return 0, err |
| 223 | } |
| 224 | attrs64 := base64.StdEncoding.EncodeToString(blob) |
| 225 | var rowid int64 |
| 226 | row := db.QueryRow("INSERT INTO signatures (timestamp, client_name, client_ip, client_dn, client_filename, sig_hostname, sig_type, sig_keyname, attributes) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING signature_id", |
| 227 | info.Attributes["sig.timestamp"], |
| 228 | info.Attributes["client.name"], |
| 229 | info.Attributes["client.ip"], |
| 230 | info.Attributes["client.dn"], |
| 231 | info.Attributes["client.filename"], |
| 232 | info.Attributes["sig.hostname"], |
| 233 | info.Attributes["sig.type"], |
| 234 | info.Attributes["sig.keyname"], |
| 235 | attrs64, |
| 236 | ) |
| 237 | if err := row.Scan(&rowid); err != nil { |
| 238 | return 0, err |
| 239 | } |
| 240 | return rowid, nil |
| 241 | } |
| 242 | |
| 243 | func logToFile(info *audit.Info, rowid int64) error { |
| 244 | formatted := fmtRow(info, rowid) |
| 245 | if auditConfig.LogFile != "" { |
| 246 | f, err := os.OpenFile(auditConfig.LogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) |
| 247 | if err != nil { |
| 248 | return err |
| 249 | } |
| 250 | defer f.Close() |
| 251 | if _, err := fmt.Fprintln(f, formatted); err != nil { |
| 252 | return err |
| 253 | } |
| 254 | } else { |
| 255 | fmt.Println(formatted) |
| 256 | } |
| 257 | return nil |
| 258 | } |
| 259 | |
| 260 | func fmtRow(info *audit.Info, rowid int64) string { |
| 261 | client := info.Attributes["client.name"] |
| 262 | if client == nil { |
| 263 | client = "" |
| 264 | } |
| 265 | ip := info.Attributes["client.ip"] |
| 266 | if ip == nil { |
| 267 | ip = "" |
| 268 | } |
| 269 | dn := info.Attributes["client.dn"] |
| 270 | if dn == nil { |
| 271 | dn = "" |
| 272 | } |
| 273 | return fmt.Sprintf("[%s] client=%s dn=%s ip=%s server=%s sigtype=%s filename=%s key=%s rowid=%d", |
| 274 | info.Attributes["sig.timestamp"], |
| 275 | client, |
| 276 | dn, |
| 277 | ip, |
| 278 | info.Attributes["sig.hostname"], |
| 279 | info.Attributes["sig.type"], |
| 280 | info.Attributes["client.filename"], |
| 281 | info.Attributes["sig.keyname"], |
| 282 | rowid, |
| 283 | ) |
| 284 | } |
| 285 | |
| 286 | func (l *Listener) Close() error { |
| 287 | if l.ch != nil { |
| 288 | l.ch.Close() |
| 289 | l.ch = nil |
| 290 | } |
| 291 | if l.conn != nil { |
| 292 | l.conn.Close() |
| 293 | l.conn = nil |
| 294 | } |
| 295 | return nil |
| 296 | } |
| 297 | |
| 298 | const ( |
| 299 | backoffMin = 1 |
| 300 | backoffMax = 60 |
| 301 | backoffE = 2.7182818284590451 |
| 302 | ) |
| 303 | |
| 304 | type expBackoff struct { |
| 305 | e float32 |
| 306 | t *time.Timer |
| 307 | } |
| 308 | |
| 309 | func (e *expBackoff) Sleep() { |
| 310 | if e.e == 0 { |
| 311 | e.e = backoffMin |
| 312 | } |
| 313 | time.Sleep(time.Duration(e.e * float32(time.Second))) |
| 314 | e.e *= backoffE |
| 315 | if e.e > backoffMax { |
| 316 | e.e = backoffMax |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | func (e *expBackoff) ResetAfter(d time.Duration) { |
| 321 | if e.t != nil { |
| 322 | e.t.Stop() |
| 323 | } |
| 324 | e.t = time.AfterFunc(d, func() { |
| 325 | e.e = 0 |
| 326 | }) |
| 327 | } |
| 328 | |
| 329 | func (e *expBackoff) CancelReset() { |
| 330 | if e.t != nil { |
| 331 | e.t.Stop() |
| 332 | e.t = nil |
| 333 | } |
| 334 | } |