| 217 | } |
| 218 | |
| 219 | func (l *LogWriter) open() error { |
| 220 | if l == nil { |
| 221 | return nil |
| 222 | } |
| 223 | |
| 224 | if err := os.MkdirAll(filepath.Dir(l.FilePath), 0755); err != nil { |
| 225 | return err |
| 226 | } |
| 227 | |
| 228 | size := func() int64 { |
| 229 | info, err := os.Stat(l.FilePath) |
| 230 | if err != nil { |
| 231 | return 0 |
| 232 | } |
| 233 | return info.Size() |
| 234 | } |
| 235 | |
| 236 | openNew := func() error { |
| 237 | f, err := os.OpenFile(l.FilePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) |
| 238 | if err != nil { |
| 239 | return err |
| 240 | } |
| 241 | l.file = f |
| 242 | l.writer = bufio.NewWriterSize(l.file, bufferSize) |
| 243 | |
| 244 | if l.EncryptionKey != nil { |
| 245 | iv := make([]byte, 16) |
| 246 | if _, err := rand.Read(iv); err != nil { // cve fix is here |
| 247 | return err |
| 248 | } |
| 249 | lengthInput := make([]byte, 4) |
| 250 | binary.BigEndian.PutUint32(lengthInput, uint32(len(VerificationText))) // header has 16+4 bytes now |
| 251 | |
| 252 | bytes, err := encrypt(l.EncryptionKey, iv, []byte(VerificationText)) |
| 253 | if err != nil { |
| 254 | return err |
| 255 | } |
| 256 | cipher := append(append(iv, lengthInput...), bytes...) |
| 257 | if _, err = l.writer.Write(cipher); err != nil { |
| 258 | return err |
| 259 | } |
| 260 | } |
| 261 | l.size = size() |
| 262 | return nil |
| 263 | } |
| 264 | |
| 265 | info, err := os.Stat(l.FilePath) |
| 266 | if err != nil { // if any error try to open new log file itself |
| 267 | return openNew() |
| 268 | } |
| 269 | |
| 270 | // encryption is enabled and file is corrupted as not able to read the IV |
| 271 | if l.EncryptionKey != nil && info.Size() < 12 { |
| 272 | return openNew() |
| 273 | } |
| 274 | |
| 275 | f, err := os.OpenFile(l.FilePath, os.O_APPEND|os.O_RDWR, os.ModePerm) |
| 276 | if err != nil { |