Debian Codegraph @

internal/util/util.go

raw symbols SCIP
1 package util
2
3 import (
4 "bytes"
5 "context"
6 "crypto/tls"
7 "fmt"
8 "log"
9 "mime"
10 "mime/quotedprintable"
11 "net"
12 "net/mail"
13 "net/smtp"
14 "os"
15 "os/exec"
16 "strconv"
17 "strings"
18 "syscall"
19 "text/template"
20 "time"
21 )
22
23 type EmailRecipient struct {
24 Email string
25 FirstName string // optional
26 LastName string // optional
27 }
28
29 const rawMessageTemplate = `From: Email-Reminder <{{.Sender}}>
30 To: {{.Recipient}}
31 Subject: {{.Subject}}
32 X-Auto-Response-Suppress: All
33 Content-Language: en
34 User-Agent: email-reminder/{{.AppVersion}}
35 MIME-Version: 1.0
36 Content-Type: text/plain; charset=UTF-8
37 Content-Disposition: inline
38 Content-Transfer-Encoding: quoted-printable
39
40 {{.Body}}`
41
42 func ParseBool(value string) (bool, error) {
43 switch strings.ToLower(value) {
44 case "no":
45 return false, nil
46 case "yes":
47 return true, nil
48 default:
49 return strconv.ParseBool(value)
50 }
51 }
52
53 // SecureExecCommand executes a command only if the binary has secure permissions.
54 // It validates that the executable is owned by root and not writable by group or others,
55 // and enforces a 5-second timeout to prevent hanging on malicious executables.
56 // This mitigates command injection vulnerabilities by ensuring system binaries haven't been compromised.
57 func SecureExecCommand(path string, args ...string) ([]byte, error) {
58 info, err := os.Stat(path)
59 if err != nil {
60 return nil, fmt.Errorf("cannot stat executable: %w", err)
61 }
62 stat, ok := info.Sys().(*syscall.Stat_t)
63 if !ok {
64 return nil, fmt.Errorf("cannot get file ownership info")
65 }
66
67 // Check ownership and permissions
68 if stat.Uid != 0 {
69 return nil, fmt.Errorf("executable not owned by root (owner: %d)", stat.Uid)
70 }
71 if permissions := info.Mode().Perm(); permissions&0022 != 0 {
72 return nil, fmt.Errorf("executable is writable by non-owner (mode: %o)", permissions)
73 }
74
75 // Execute with timeout
76 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
77 defer cancel()
78 cmd := exec.CommandContext(ctx, path, args...)
79 return cmd.Output()
80 }
81
82 // ValidateEmail validates email addresses using RFC5322 via mail.ParseAddress(),
83 // while also accepting local delivery formats supported by local mail servers.
84 func ValidateEmail(email string) error {
85 if email == "" {
86 return fmt.Errorf("email address is empty")
87 }
88
89 // RFC 3696 Errata 1690 specifies a maximum email address length of 254 characters
90 // https://www.rfc-editor.org/errata/eid1690
91 if len(email) > 254 {
92 return fmt.Errorf("email address exceeds maximum length of 254 characters")
93 }
94
95 // Normalize addresses accepted by Postfix for RFC5322 parsing
96 normalized := email
97 if !strings.Contains(email, "@") {
98 // Bare username (e.g., "root") - add @localhost for parsing
99 normalized = email + "@localhost"
100 } else if strings.HasPrefix(email, "@") {
101 // @hostname format (e.g., "@example.com") - add dummy local part for parsing
102 normalized = "dummy.user" + email
103 }
104
105 addr, err := mail.ParseAddress(normalized) // RFC5322
106 if err != nil {
107 return fmt.Errorf("invalid email format: %w", err)
108 }
109
110 // Ensure no display name was included
111 if addr.Address != normalized {
112 return fmt.Errorf("email address contains unexpected formatting")
113 }
114
115 return nil
116 }
117
118 func IsLastDayOfTheMonth(now time.Time) bool {
119 tomorrow := now.AddDate(0, 0, 1)
120 return tomorrow.Month() != now.Month()
121 }
122
123 // Formatted email address suitable for the To header (e.g., "John Doe <[email protected]>"), or just the email if no name is present
124 func (e EmailRecipient) NameAndEmail() string {
125 // Combine first and last names
126 name := strings.TrimSpace(strings.Join([]string{e.FirstName, e.LastName}, " "))
127
128 if name == "" && e.Email == "" {
129 return ""
130 }
131
132 address := mail.Address{Name: name, Address: e.Email}
133 return address.String()
134 }
135
136 func AssembleRawMessage(body string, subject string, recipient string, sender string, appVersion string) string {
137 body = strings.ReplaceAll(body, "\n", "\r\n") // required by RFC822
138 var qpBody bytes.Buffer
139 w := quotedprintable.NewWriter(&qpBody)
140 w.Write([]byte(body))
141 w.Close()
142
143 msgTemplate := template.Must(
144 template.New("raw-message").Parse(strings.ReplaceAll(rawMessageTemplate, "\n", "\r\n")),
145 )
146
147 var msg strings.Builder
148 msgTemplate.Execute(&msg, struct {
149 Sender string
150 Recipient string
151 Subject string
152 AppVersion string
153 Body string
154 }{
155 Sender: sender,
156 Recipient: recipient,
157 Subject: mime.QEncoding.Encode("UTF-8", subject),
158 AppVersion: appVersion,
159 Body: qpBody.String(),
160 })
161
162 return msg.String()
163 }
164
165 // SendMailPlaintext sends email via plain SMTP on port 25 without any TLS/STARTTLS.
166 // This is useful for localhost connections where STARTTLS might fail due to certificate mismatches.
167 func SendMailPlaintext(host string, auth smtp.Auth, from string, to []string, msg []byte) error {
168 conn, err := net.Dial("tcp", net.JoinHostPort(host, "25"))
169 if err != nil {
170 return fmt.Errorf("failed to establish connection: %w", err)
171 }
172 defer conn.Close()
173
174 client, err := smtp.NewClient(conn, host)
175 if err != nil {
176 return fmt.Errorf("failed to create SMTP client: %w", err)
177 }
178
179 if auth != nil {
180 if ok, _ := client.Extension("AUTH"); ok {
181 if err := client.Auth(auth); err != nil {
182 return fmt.Errorf("failed to authenticate with SMTP server: %w", err)
183 }
184 }
185 }
186
187 if err := client.Mail(from); err != nil {
188 return fmt.Errorf("MAIL command failed for %s: %w", from, err)
189 }
190 for _, recipient := range to {
191 if err := client.Rcpt(recipient); err != nil {
192 return fmt.Errorf("RCPT command failed for %s: %w", recipient, err)
193 }
194 }
195
196 data, err := client.Data()
197 if err != nil {
198 return fmt.Errorf("DATA command failed: %w", err)
199 }
200 if _, err := data.Write(msg); err != nil {
201 return fmt.Errorf("failed to write message body: %w", err)
202 }
203 if err := data.Close(); err != nil {
204 return fmt.Errorf("failed to close message body: %w", err)
205 }
206
207 if err := client.Quit(); err != nil {
208 return fmt.Errorf("failed to terminate SMTP session: %w", err)
209 }
210 return nil
211 }
212
213 // Loosely based on https://gist.github.com/chrisgillis/10888032
214 func SendMailImplicitTLS(host string, auth smtp.Auth, from string, to []string, msg []byte) error {
215 conn, err := tls.Dial("tcp", net.JoinHostPort(host, "465"), &tls.Config{
216 ServerName: host,
217 MinVersion: tls.VersionTLS12,
218 })
219 if err != nil {
220 return fmt.Errorf("failed to establish TLS connection: %w", err)
221 }
222 defer conn.Close()
223
224 client, err := smtp.NewClient(conn, host)
225 if err != nil {
226 return fmt.Errorf("failed to create SMTP client: %w", err)
227 }
228
229 if auth != nil {
230 if ok, _ := client.Extension("AUTH"); ok {
231 if err := client.Auth(auth); err != nil {
232 return fmt.Errorf("failed to authenticate with SMTP server: %w", err)
233 }
234 }
235 }
236
237 if err := client.Mail(from); err != nil {
238 return fmt.Errorf("MAIL command failed for %s: %w", from, err)
239 }
240 for _, recipient := range to {
241 if err := client.Rcpt(recipient); err != nil {
242 return fmt.Errorf("RCPT command failed for %s: %w", recipient, err)
243 }
244 }
245
246 data, err := client.Data()
247 if err != nil {
248 return fmt.Errorf("DATA command failed: %w", err)
249 }
250 if _, err := data.Write(msg); err != nil {
251 return fmt.Errorf("failed to write message body: %w", err)
252 }
253 if err := data.Close(); err != nil {
254 return fmt.Errorf("failed to close message body: %w", err)
255 }
256
257 if err := client.Quit(); err != nil {
258 return fmt.Errorf("failed to terminate SMTP session: %w", err)
259 }
260 return nil
261 }
262
263 // Ensure that the home directory is owned by the expected user
264 func ValidateHomeDirectory(homePath string, expectedUid uint32) error {
265 info, err := os.Lstat(homePath) // Use Lstat to detect symlinks
266 if err != nil {
267 return fmt.Errorf("cannot access home directory '%s': %w", homePath, err)
268 }
269
270 if info.Mode()&os.ModeSymlink != 0 {
271 return fmt.Errorf("home directory '%s' is a symlink", homePath)
272 }
273 if !info.IsDir() {
274 return fmt.Errorf("home directory '%s' is not a directory", homePath)
275 }
276
277 if stat, ok := info.Sys().(*syscall.Stat_t); ok { // Only works on UNIX
278 if stat.Uid != expectedUid {
279 return fmt.Errorf("home directory '%s' is not owned by uid %d (actual owner: %d)", homePath, expectedUid, stat.Uid)
280 }
281 } else {
282 log.Printf("cannot get ownership information for '%s'", homePath)
283 }
284
285 return nil
286 }
287
288 // ValidateOpenFile checks that an already-open file is owned by the expected user
289 // and is a regular file (not a device, socket, symlink, etc.).
290 func ValidateOpenFile(file *os.File, expectedUid uint32) error {
291 info, err := file.Stat()
292 if err != nil {
293 return fmt.Errorf("cannot stat file '%s': %w", file.Name(), err)
294 }
295
296 stat, ok := info.Sys().(*syscall.Stat_t) // Only works on UNIX
297 if !ok {
298 return fmt.Errorf("cannot get ownership information for '%s'", file.Name())
299 }
300
301 if stat.Uid != expectedUid {
302 return fmt.Errorf("file '%s' is not owned by uid %d (actual owner: %d)", file.Name(), expectedUid, stat.Uid)
303 }
304
305 if !info.Mode().IsRegular() {
306 return fmt.Errorf("'%s' is not a regular file (mode: %s)", file.Name(), info.Mode().Type())
307 }
308
309 return nil
310 }
311
312 // Complete email body with friendly greeting and footer
313 func FullBody(body string, recipient EmailRecipient, version string) string {
314 firstName := recipient.FirstName
315 if firstName == "" {
316 firstName = "there"
317 }
318 return fmt.Sprintf(`Hi %s,
319
320 %s
321
322 Have a good day!
323
324 --
325 Sent by Email-Reminder %s
326 https://launchpad.net/email-reminder`, firstName, body, version)
327 }