Coverage Report
Generated on 03 Feb 26 20:24 +0000 with gocov-html
Package Overview: agent 75.10%

This is a coverage report created after analysis of the agent package. It has been generated with the following command:

gocov test agent | gocov-html

Here are the stats. Please select a function name to view its implementation and see what's left for testing.

easyjsonD587a15Encode1(...) agent/api_proto_easyjson.go 100.00% 28/28
FailureWatchdog.RecordFailure(...) agent/watchdog.go 100.00% 18/18
query(...) agent/rbl.go 100.00% 15/15
Agent.ServeLogRBLStat(...) agent/agent.go 100.00% 13/13
CPanelAuthMsg.Unmarshal(...) agent/cpanel.go 100.00% 13/13
License.Signed(...) agent/license.go 100.00% 11/11
LicenseWatcher.validLicense(...) agent/license.go 100.00% 10/10
easyjson3c9d2b01EncodeGithubComUserHello(...) agent/request_easyjson.go 100.00% 10/10
Record.MarshalMsg(...) agent/record_msgp.go 100.00% 9/9
validLicense(...) agent/license.go 100.00% 8/8
NewWhiteList(...) agent/whitelist.go 100.00% 6/6
FailureWatchdogRecord.MarshalMsg(...) agent/watchdog_record_gen.go 100.00% 6/6
WhiteList.reload(...) agent/whitelist.go 100.00% 6/6
Record.Msgsize(...) agent/record_msgp.go 100.00% 6/6
NewFailureWatchdog(...) agent/watchdog.go 100.00% 6/6
LicenseWatcher.notify(...) agent/license.go 100.00% 4/4
@140:8(...) agent/config.go 100.00% 4/4
Database.writeRecord(...) agent/database.go 100.00% 4/4
@43:8(...) agent/conn_tracker.go 100.00% 3/3
License.UnmarshalJSON(...) agent/license_proto_easyjson.go 100.00% 3/3
License.MarshalJSON(...) agent/license_proto_easyjson.go 100.00% 3/3
StatRecord.MarshalJSON(...) agent/api_proto_easyjson.go 100.00% 3/3
LicenseWatcher.Subscribe(...) agent/license.go 100.00% 3/3
StatRecord.UnmarshalJSON(...) agent/api_proto_easyjson.go 100.00% 3/3
LicenseWatcher.readLicenseAndNotify(...) agent/license.go 100.00% 3/3
Request.UnmarshalJSON(...) agent/request_easyjson.go 100.00% 3/3
Request.MarshalJSON(...) agent/request_easyjson.go 100.00% 3/3
SendMessagesApiRequest.MarshalJSON(...) agent/api_proto_easyjson.go 100.00% 3/3
Response.UnmarshalJSON(...) agent/request_easyjson.go 100.00% 3/3
SendMessagesApiRequest.UnmarshalJSON(...) agent/api_proto_easyjson.go 100.00% 3/3
Response.MarshalJSON(...) agent/request_easyjson.go 100.00% 3/3
ConnTracker.TrackActivity(...) agent/conn_tracker.go 100.00% 2/2
LicenseWatcher.Stop(...) agent/license.go 100.00% 2/2
LicenseWatcher.Start(...) agent/license.go 100.00% 2/2
@113:5(...) agent/license.go 100.00% 2/2
Database.WithUserIPWhitelist(...) agent/database.go 100.00% 2/2
Database.WithUserWhitelist(...) agent/database.go 100.00% 2/2
FailureWatchdogRecord.Msgsize(...) agent/watchdog_record_gen.go 100.00% 2/2
FailureWatchdogRecord.DumpToFile(...) agent/watchdog_record.go 100.00% 2/2
FailureWatchdogRecord.Unmarshal(...) agent/watchdog_record.go 100.00% 2/2
FailureWatchdogRecord.Marshal(...) agent/watchdog_record.go 100.00% 2/2
Record.Unmarshal(...) agent/record.go 100.00% 2/2
Record.Marshal(...) agent/record.go 100.00% 2/2
ModuleStringResponse(...) agent/module.go 100.00% 2/2
@80:19(...) agent/rbl.go 100.00% 2/2
UserIPLockConfig.ForgeAutowhitelistLockConfig(...) agent/config.go 100.00% 1/1
NewConnTracker(...) agent/conn_tracker.go 100.00% 1/1
loadLockConfigIP(...) agent/config.go 100.00% 1/1
@23:20(...) agent/utils.go 100.00% 1/1
UserIPLockConfig.IsAutowhitelistEnabled(...) agent/config.go 100.00% 1/1
@49:17(...) agent/api.go 100.00% 1/1
@186:17(...) agent/rbl.go 100.00% 1/1
StatRecord.UnmarshalEasyJSON(...) agent/api_proto_easyjson.go 100.00% 1/1
ConnTracker.Stop(...) agent/conn_tracker.go 100.00% 1/1
init(...) agent/sentry.go 100.00% 1/1
StatRecord.MarshalEasyJSON(...) agent/api_proto_easyjson.go 100.00% 1/1
Agent.RequestId(...) agent/agent.go 100.00% 1/1
loadLockConfigUser(...) agent/config.go 100.00% 1/1
loadLockConfigUserIP(...) agent/config.go 100.00% 1/1
NewSendMessageAPI(...) agent/api.go 100.00% 1/1
LockConfig.IsEnabled(...) agent/config.go 100.00% 1/1
Config.IsVerboseLoggingMode(...) agent/config.go 100.00% 1/1
UserWhiteList.reset(...) agent/whitelist.go 100.00% 1/1
UserWhiteList.loadLine(...) agent/whitelist.go 100.00% 1/1
IPWhiteList.reset(...) agent/whitelist.go 100.00% 1/1
Config.IsSentryEnabled(...) agent/config.go 100.00% 1/1
Config.IsLogfileEnabled(...) agent/config.go 100.00% 1/1
NewLicenseWatcher(...) agent/license.go 100.00% 1/1
License.signedContent(...) agent/license.go 100.00% 1/1
UserIPWhiteList.reset(...) agent/whitelist.go 100.00% 1/1
easyjson2c6259e0Encode1(...) agent/license_proto_easyjson.go 97.56% 40/41
easyjsonD587a15Encode12(...) agent/api_proto_easyjson.go 97.56% 40/41
easyjsonD587a15Encode11(...) agent/api_proto_easyjson.go 96.88% 31/32
Agent.WriteStat(...) agent/agent.go 96.43% 27/28
Database.writeAttempt(...) agent/database.go 96.00% 24/25
readWhiteList(...) agent/whitelist.go 92.86% 13/14
easyjson3c9d2b01EncodeGithubComUserHello1(...) agent/request_easyjson.go 92.31% 36/39
UserIPWhiteList.In(...) agent/whitelist.go 92.31% 12/13
CheckRBL(...) agent/rbl.go 91.67% 11/12
ConnTracker.HandleActivity(...) agent/conn_tracker.go 91.67% 11/12
IPWhiteList.In(...) agent/whitelist.go 90.91% 10/11
rblLookupIP(...) agent/rbl.go 90.91% 10/11
IPWhiteList.loadLine(...) agent/whitelist.go 90.00% 9/10
getOsRelease(...) agent/sentry.go 90.00% 9/10
LicenseWatcher.rereadLicense(...) agent/license.go 89.47% 17/19
UserWhiteList.In(...) agent/whitelist.go 88.89% 8/9
CPanelFtpAuthRecv(...) agent/cpanel.go 88.89% 8/9
@212:20(...) agent/rbl.go 88.89% 8/9
UserIPWhiteList.loadLine(...) agent/whitelist.go 88.24% 15/17
Database.Close(...) agent/database.go 87.50% 7/8
LicenseWatcher.watcher(...) agent/license.go 87.50% 7/8
LoadLicense(...) agent/license.go 87.50% 7/8
Agent.ServeListener(...) agent/agent.go 86.67% 13/15
Agent.Stop(...) agent/agent.go 84.85% 28/33
LoadPublicKey(...) agent/license.go 84.62% 11/13
@417:6(...) agent/agent.go 83.33% 10/12
init(...) agent/agent.go 83.33% 5/6
Agent.Serve(...) agent/agent.go 83.33% 5/6
@169:18(...) agent/agent.go 83.33% 5/6
Agent.ServeSendStat(...) agent/agent.go 82.35% 14/17
NewIPWhiteList(...) agent/whitelist.go 81.82% 9/11
NewUserIPWhiteList(...) agent/whitelist.go 80.00% 4/5
SendMessageAPI.send(...) agent/api.go 80.00% 4/5
loadHostPort(...) agent/config.go 80.00% 4/5
NewUserWhiteList(...) agent/whitelist.go 80.00% 4/5
Database.expireOld(...) agent/database.go 79.49% 31/39
Database.WriteAttempts(...) agent/database.go 78.26% 18/23
FailureWatchdogRecord.ReadFromFile(...) agent/watchdog_record.go 77.78% 7/9
getOwnIP(...) agent/sentry.go 77.78% 7/9
Agent.ProcessModuleRequest(...) agent/module.go 76.60% 36/47
Agent.ProcessCPanelFtpAuthRequest(...) agent/cpanel.go 75.64% 59/78
NewSentryLogger(...) agent/sentry.go 75.00% 21/28
shouldLogError(...) agent/agent.go 75.00% 6/8
WhiteList.isNeedUpdate(...) agent/whitelist.go 75.00% 6/8
Request.CheckSign(...) agent/request.go 75.00% 3/4
GetAgentLicStatus(...) agent/license.go 75.00% 3/4
IsRunningSystemd(...) agent/service.go 75.00% 3/4
Agent.Start(...) agent/agent.go 74.32% 55/74
DatabaseOpen(...) agent/database.go 73.33% 11/15
Database.readRecord(...) agent/database.go 73.33% 11/15
easyjson2c6259e0Decode1(...) agent/license_proto_easyjson.go 72.73% 32/44
Database.RemoveSuccess(...) agent/database.go 72.00% 18/25
easyjsonD587a15Decode1(...) agent/api_proto_easyjson.go 71.43% 20/28
Database.serveExpireOld(...) agent/database.go 71.43% 10/14
ConnProcess(...) agent/utils.go 71.43% 5/7
ConfigLoad(...) agent/config.go 71.43% 5/7
easyjsonD587a15Decode12(...) agent/api_proto_easyjson.go 70.45% 31/44
easyjsonD587a15Decode11(...) agent/api_proto_easyjson.go 70.00% 28/40
Database.CheckLock(...) agent/database.go 68.97% 20/29
Request.calcSign(...) agent/request.go 66.67% 12/18
connProcessPid(...) agent/utils.go 66.67% 10/15
WhiteList.Update(...) agent/whitelist.go 66.67% 8/12
NewRBL(...) agent/rbl.go 66.67% 6/9
SendMessageAPI.SendStats(...) agent/api.go 66.67% 4/6
GetListeners(...) agent/socket.go 64.71% 11/17
FailureWatchdogRecord.UnmarshalMsg(...) agent/watchdog_record_gen.go 63.64% 21/33
easyjson3c9d2b01DecodeGithubComUserHello(...) agent/request_easyjson.go 63.64% 14/22
Agent.ProcessCPanelFtpAuthConn(...) agent/cpanel.go 63.64% 14/22
rbl.Check(...) agent/rbl.go 63.64% 7/11
@68:25(...) agent/api.go 61.54% 8/13
rangeInt(...) agent/config.go 60.00% 3/5
rangeInt64(...) agent/config.go 60.00% 3/5
easyjson3c9d2b01DecodeGithubComUserHello1(...) agent/request_easyjson.go 59.62% 31/52
Record.UnmarshalMsg(...) agent/record_msgp.go 59.57% 28/47
Agent.ProcessModuleConn(...) agent/module.go 59.52% 25/42
FailureWatchdogRecord.DecodeMsg(...) agent/watchdog_record_gen.go 53.12% 17/32
FailureWatchdog.CapturePanic(...) agent/watchdog.go 50.00% 3/6
@91:9(...) agent/watchdog.go 50.00% 1/2
ReverseIP(...) agent/rbl.go 46.67% 7/15
FailureWatchdogRecord.EncodeMsg(...) agent/watchdog_record_gen.go 46.15% 6/13
loadKeyFile(...) agent/config.go 44.44% 4/9
getServerId(...) agent/sentry.go 40.00% 4/10
@182:18(...) agent/agent.go 33.33% 2/6
ToIP(...) agent/agent.go 33.33% 2/6
ModifyDovecotSocket(...) agent/socket.go 18.75% 3/16
main(...) agent/main.go 0.00% 0/36
Request.GetOverdueBy(...) agent/request.go 0.00% 0/7
rateSample.sample(...) agent/sentry.go 0.00% 0/5
disableFtpIntegration(...) agent/watchdog.go 0.00% 0/5
DatabaseDrop(...) agent/database.go 0.00% 0/5
serviceCmd(...) agent/service.go 0.00% 0/5
errHasSuffixRateLimit.IsLimited(...) agent/sentry.go 0.00% 0/4
systemd(...) agent/service.go 0.00% 0/2
TimeoutMS.Duration(...) agent/request.go 0.00% 0/1
loadLockConfig(...) agent/config.go 0.00% 0/1
Response.MarshalEasyJSON(...) agent/request_easyjson.go 0.00% 0/1
TimestampMS.Time(...) agent/request.go 0.00% 0/1
SendMessagesApiRequest.MarshalEasyJSON(...) agent/api_proto_easyjson.go 0.00% 0/1
Response.UnmarshalEasyJSON(...) agent/request_easyjson.go 0.00% 0/1
ServiceStart(...) agent/service.go 0.00% 0/1
SendMessagesApiRequest.UnmarshalEasyJSON(...) agent/api_proto_easyjson.go 0.00% 0/1
ServiceStop(...) agent/service.go 0.00% 0/1
ServiceRestart(...) agent/service.go 0.00% 0/1
Request.MarshalEasyJSON(...) agent/request_easyjson.go 0.00% 0/1
License.UnmarshalEasyJSON(...) agent/license_proto_easyjson.go 0.00% 0/1
License.MarshalEasyJSON(...) agent/license_proto_easyjson.go 0.00% 0/1
Request.UnmarshalEasyJSON(...) agent/request_easyjson.go 0.00% 0/1
@137:32(...) agent/license.go 100.00% 0/0
func easyjsonD587a15Encode1
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

65
func easyjsonD587a15Encode1(out *jwriter.Writer, in StatRecord) {
66
        out.RawByte('{')
67
        first := true
68
        _ = first
69
        {
70
                const prefix string = ",\"name\":"
71
                out.RawString(prefix[1:])
72
                out.String(string(in.Name))
73
        }
74
        {
75
                const prefix string = ",\"attackers_ip\":"
76
                out.RawString(prefix)
77
                out.String(string(in.AttackersIP))
78
        }
79
        {
80
                const prefix string = ",\"rule\":"
81
                out.RawString(prefix)
82
                out.Int(int(in.Rule))
83
        }
84
        {
85
                const prefix string = ",\"message\":"
86
                out.RawString(prefix)
87
                out.String(string(in.Message))
88
        }
89
        {
90
                const prefix string = ",\"severity\":"
91
                out.RawString(prefix)
92
                out.Int(int(in.Severity))
93
        }
94
        {
95
                const prefix string = ",\"retries\":"
96
                out.RawString(prefix)
97
                out.Int(int(in.Retries))
98
        }
99
        {
100
                const prefix string = ",\"timestamp\":"
101
                out.RawString(prefix)
102
                out.Int64(int64(in.Timestamp))
103
        }
104
        {
105
                const prefix string = ",\"plugin_id\":"
106
                out.RawString(prefix)
107
                out.String(string(in.PluginId))
108
        }
109
        out.RawByte('}')
110
}
func FailureWatchdog.RecordFailure
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog.go:

66
func (w *FailureWatchdog) RecordFailure(timestamp time.Time) {
67
        if !w.Enabled {
68
                return
69
        }
70
71
        var r FailureWatchdogRecord
72
        if err := r.ReadFromFile(w.path); err != nil && !errors.Is(err, afero.ErrFileNotFound) {
73
                log.WithError(err).Errorf("failed to read failure watchdog file: %v", err)
74
                return
75
        }
76
77
        timestamps := []int64{}
78
        for _, t := range r.Timestamps {
79
                since := timestamp.Sub(time.Unix(0, t))
80
81
                if since < w.Period {
82
                        timestamps = append(timestamps, t)
83
                }
84
        }
85
        timestamps = append(timestamps, timestamp.UnixNano())
86
87
        excess := len(timestamps) - w.Limit
88
        if excess > 0 {
89
                timestamps = timestamps[excess:]
90
91
                defer func() {
92
                        if err := w.cb(); err != nil {
93
                                log.WithError(err).Errorf("failed to execute callback: %v", err)
94
                        }
95
                }()
96
        }
97
98
        r.Timestamps = timestamps
99
        r.DumpToFile(w.path)
100
}
func query
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/rbl.go:

73
func query(ctx context.Context, nameserver string, rbl string, host string, r *Result) {
74
        r.Listed = false
75
76
        resolver := net.Resolver{
77
                PreferGo: true,
78
        }
79
        if nameserver != "" {
80
                resolver.Dial = func(ctx context.Context, network, address string) (net.Conn, error) {
81
                        d := net.Dialer{}
82
                        return d.DialContext(ctx, "udp", nameserver)
83
                }
84
        }
85
86
        lookup := fmt.Sprintf("%s.%s", host, rbl)
87
88
        res, err := resolver.LookupHost(ctx, lookup)
89
        if len(res) > 0 {
90
                r.Listed = true
91
                txt, _ := resolver.LookupTXT(ctx, lookup)
92
                if len(txt) > 0 {
93
                        r.Text = txt[0]
94
                }
95
        }
96
        if err != nil {
97
                r.Error = true
98
                r.ErrorType = err
99
        }
100
101
        return
102
}
func Agent.ServeLogRBLStat
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

353
func (p *Agent) ServeLogRBLStat() {
354
        defer failureWatchdog.CapturePanic()
355
        var (
356
                statsSuccessOld, statsTimeoutOld, statsErrorsOld int64
357
                stop                                             bool
358
        )
359
360
        for !stop {
361
                select {
362
                case <-p.statsRBLCheckStop:
363
                        stop = true
364
                case <-time.After(5 * time.Minute):
365
                }
366
                statsSuccess := atomic.LoadInt64(&p.statRBLCheck.Success) - statsSuccessOld
367
                statsTimeout := atomic.LoadInt64(&p.statRBLCheck.Timeout) - statsTimeoutOld
368
                statsErrors := atomic.LoadInt64(&p.statRBLCheck.Errors) - statsErrorsOld
369
370
                if statsTimeout > 0 || statsErrors > 0 {
371
                        log.WithFields(log.Fields{
372
                                "fingerprint": []string{"RBLCheckStatsHasErrors"},
373
                                "success":     statsSuccess,
374
                                "timeout":     statsTimeout,
375
                                "errors":      statsErrors,
376
                        }).Warnf("RBL Check requests stats: success=%d timeout=%d errors=%d",
377
                                statsSuccess, statsTimeout, statsErrors)
378
                }
379
380
                statsSuccessOld += statsSuccess
381
                statsTimeoutOld += statsTimeout
382
                statsErrorsOld += statsErrors
383
        }
384
}
func CPanelAuthMsg.Unmarshal
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/cpanel.go:

236
func (r *CPanelAuthMsg) Unmarshal(b []byte) *CPanelAuthMsg {
237
        lines := bytes.Split(b, []byte{'\n'})
238
        for _, line := range lines {
239
                i := bytes.IndexByte(line, ':')
240
                if i == -1 {
241
                        continue
242
                }
243
                key := line[:i]
244
                value := line[i+1:]
245
                switch string(key) {
246
                case "account":
247
                        r.Account = string(value)
248
                case "password":
249
                        r.Password = string(value)
250
                case "peer":
251
                        r.Peer = string(value)
252
                case "auth_ok":
253
                        r.AuthOk = string(value)
254
                }
255
        }
256
        return r
257
}
func License.Signed
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

43
func (lic *License) Signed(pubKey *rsa.PublicKey) bool {
44
        lic.Sign = ""
45
        signed := lic.signedContent()
46
        for _, sigB64 := range lic.Signatures {
47
                sig, err := base64.StdEncoding.DecodeString(sigB64)
48
                if err != nil {
49
                        continue
50
                }
51
                hashed := sha512.Sum512(signed)
52
                if err := rsa.VerifyPKCS1v15(pubKey, crypto.SHA512, hashed[:], []byte(sig)); err == nil {
53
                        lic.Sign = sigB64
54
                        return true
55
                }
56
        }
57
        return false
58
}
func LicenseWatcher.validLicense
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

191
func (lw *LicenseWatcher) validLicense(lic *License) bool {
192
        if lic.err != nil {
193
                return false
194
        }
195
196
        isValid, errPubKey := validLicense(lic, lw.pubKeyPath)
197
        if isValid {
198
                return isValid
199
        }
200
201
        isAltValid, errAltPubKey := validLicense(lic, lw.altPubKeyPath)
202
        if errAltPubKey == nil {
203
                return isAltValid
204
        }
205
206
        lic.err = errors.Join(errPubKey, errAltPubKey)
207
        return false
208
}
func easyjson3c9d2b01EncodeGithubComUserHello
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

53
func easyjson3c9d2b01EncodeGithubComUserHello(out *jwriter.Writer, in Response) {
54
        out.RawByte('{')
55
        first := true
56
        _ = first
57
        {
58
                const prefix string = ",\"action\":"
59
                out.RawString(prefix[1:])
60
                out.String(string(in.Action))
61
        }
62
        {
63
                const prefix string = ",\"message\":"
64
                out.RawString(prefix)
65
                out.String(string(in.Message))
66
        }
67
        out.RawByte('}')
68
}
func Record.MarshalMsg
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/record_msgp.go:

10
func (z *Record) MarshalMsg(b []byte) (o []byte, err error) {
11
        o = msgp.Require(b, z.Msgsize())
12
        // map header, size 2
13
        // string "e"
14
        o = append(o, 0x82, 0xa1, 0x65)
15
        o = msgp.AppendInt64(o, z.LockExpireAt)
16
        // string "a"
17
        o = append(o, 0xa1, 0x61)
18
        o = msgp.AppendMapHeader(o, uint32(len(z.Attempts)))
19
        for za0001, za0002 := range z.Attempts {
20
                o = msgp.AppendString(o, za0001)
21
                o = msgp.AppendInt64(o, za0002)
22
        }
23
        return
24
}
func validLicense
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

223
func validLicense(lic *License, pubKeyPath string) (bool, error) {
224
        f, err := appFs.Open(pubKeyPath)
225
        if err != nil {
226
                return false, fmt.Errorf("fs.Open(%#v) failed: %v", pubKeyPath, err)
227
        }
228
        defer f.Close()
229
        pubKey, err := LoadPublicKey(f)
230
        if err != nil {
231
                return false, fmt.Errorf("LoadPublicKey() failed: %s", err)
232
        }
233
        // NOTE: we do not check if license is expired, which may be wrong,
234
        // but that is what agent does at the moment.
235
        return lic.Signed(pubKey), nil
236
}
func NewWhiteList
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

53
func NewWhiteList(fileNameList []string, ResetHandler func(), LoadLineHandler func(line string)) *WhiteList {
54
        wl := &WhiteList{
55
                file:            make(map[string]time.Time, len(fileNameList)),
56
                lastCheckTime:   make(chan time.Time, 1),
57
                ResetHandler:    ResetHandler,
58
                LoadLineHandler: LoadLineHandler,
59
        }
60
61
        for _, fileName := range fileNameList {
62
                wl.file[fileName] = time.Time{}
63
        }
64
        wl.reload()
65
        wl.lastCheckTime <- time.Now()
66
        return wl
67
}
func FailureWatchdogRecord.MarshalMsg
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog_record_gen.go:

81
func (z *FailureWatchdogRecord) MarshalMsg(b []byte) (o []byte, err error) {
82
        o = msgp.Require(b, z.Msgsize())
83
        // map header, size 1
84
        // string "timestamps"
85
        o = append(o, 0x81, 0xaa, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x73)
86
        o = msgp.AppendArrayHeader(o, uint32(len(z.Timestamps)))
87
        for za0001 := range z.Timestamps {
88
                o = msgp.AppendInt64(o, z.Timestamps[za0001])
89
        }
90
        return
91
}
func WhiteList.reload
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

83
func (wl *WhiteList) reload() {
84
        if wl.ResetHandler != nil {
85
                wl.ResetHandler()
86
        }
87
        for fileName, _ := range wl.file {
88
                fileModTime, err := readWhiteList(fileName, wl.LoadLineHandler)
89
                if err == nil {
90
                        wl.file[fileName] = fileModTime
91
                }
92
        }
93
}
func Record.Msgsize
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/record_msgp.go:

93
func (z *Record) Msgsize() (s int) {
94
        s = 1 + 2 + msgp.Int64Size + 2 + msgp.MapHeaderSize
95
        if z.Attempts != nil {
96
                for za0001, za0002 := range z.Attempts {
97
                        _ = za0002
98
                        s += msgp.StringPrefixSize + len(za0001) + msgp.Int64Size
99
                }
100
        }
101
        return
102
}
func NewFailureWatchdog
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog.go:

35
func NewFailureWatchdog(period time.Duration, limit int, enabled bool) FailureWatchdog {
36
        failureWatchdog := FailureWatchdog{
37
                DefaultFailureWatchdogPeriod,
38
                DefaultFailureWatchdogLimit,
39
                enabled,
40
                failureWatchdogFilepath,
41
                disableFtpIntegration,
42
        }
43
        if limit >= 0 {
44
                failureWatchdog.Limit = limit
45
        }
46
47
        if period >= 0 {
48
                failureWatchdog.Period = period
49
        }
50
        return failureWatchdog
51
}
func LicenseWatcher.notify
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

183
func (lw *LicenseWatcher) notify(lic *License, valid bool) {
184
        lw.lock.Lock()
185
        for _, f := range lw.subs {
186
                f(*lic, valid)
187
        }
188
        lw.lock.Unlock()
189
}
func @140:8
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

140
func() []string {
141
                        rbl := i.Section("").Key("rbl").Strings(",")
142
                        if len(rbl) > 0 {
143
                                return rbl
144
                        }
145
                        return []string{"net-brute.rbl.imunify.com"}
146
                }
func Database.writeRecord
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

420
func (db Database) writeRecord(batch *leveldb.Batch, key string, record *Record) {
421
        if record.LockExpireAt == 0 && len(record.Attempts) == 0 {
422
                batch.Delete([]byte(key))
423
        }
424
        batch.Put([]byte(key), record.Marshal())
425
426
        log.WithField("record", record).Tracef("---[db]->> %v", key)
427
}
func @43:8
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/conn_tracker.go:

43
func() {
44
                timer.Stop()
45
                close(ct.idleChan)
46
                close(ct.Done)
47
        }
func License.UnmarshalJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license_proto_easyjson.go:

171
func (v *License) UnmarshalJSON(data []byte) error {
172
        r := jlexer.Lexer{Data: data}
173
        easyjson2c6259e0Decode1(&r, v)
174
        return r.Error()
175
}
func License.MarshalJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license_proto_easyjson.go:

159
func (v License) MarshalJSON() ([]byte, error) {
160
        w := jwriter.Writer{}
161
        easyjson2c6259e0Encode1(&w, v)
162
        return w.Buffer.BuildBytes(), w.Error
163
}
func StatRecord.MarshalJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

113
func (v StatRecord) MarshalJSON() ([]byte, error) {
114
        w := jwriter.Writer{}
115
        easyjsonD587a15Encode1(&w, v)
116
        return w.Buffer.BuildBytes(), w.Error
117
}
func LicenseWatcher.Subscribe
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

217
func (lw *LicenseWatcher) Subscribe(f LicenseListener) {
218
        lw.lock.Lock()
219
        lw.subs = append(lw.subs, f)
220
        lw.lock.Unlock()
221
}
func StatRecord.UnmarshalJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

125
func (v *StatRecord) UnmarshalJSON(data []byte) error {
126
        r := jlexer.Lexer{Data: data}
127
        easyjsonD587a15Decode1(&r, v)
128
        return r.Error()
129
}
func LicenseWatcher.readLicenseAndNotify
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

139
func (lw *LicenseWatcher) readLicenseAndNotify() {
140
        if lic := lw.rereadLicense(); lic != nil {
141
                lw.notify(lic, lw.validLicense(lic))
142
        }
143
        readLicenseAndNotifyDone()
144
}
func Request.UnmarshalJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

254
func (v *Request) UnmarshalJSON(data []byte) error {
255
        r := jlexer.Lexer{Data: data}
256
        easyjson3c9d2b01DecodeGithubComUserHello1(&r, v)
257
        return r.Error()
258
}
func Request.MarshalJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

242
func (v Request) MarshalJSON() ([]byte, error) {
243
        w := jwriter.Writer{}
244
        easyjson3c9d2b01EncodeGithubComUserHello1(&w, v)
245
        return w.Buffer.BuildBytes(), w.Error
246
}
func SendMessagesApiRequest.MarshalJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

246
func (v SendMessagesApiRequest) MarshalJSON() ([]byte, error) {
247
        w := jwriter.Writer{}
248
        easyjsonD587a15Encode11(&w, v)
249
        return w.Buffer.BuildBytes(), w.Error
250
}
func Response.UnmarshalJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

83
func (v *Response) UnmarshalJSON(data []byte) error {
84
        r := jlexer.Lexer{Data: data}
85
        easyjson3c9d2b01DecodeGithubComUserHello(&r, v)
86
        return r.Error()
87
}
func SendMessagesApiRequest.UnmarshalJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

258
func (v *SendMessagesApiRequest) UnmarshalJSON(data []byte) error {
259
        r := jlexer.Lexer{Data: data}
260
        easyjsonD587a15Decode11(&r, v)
261
        return r.Error()
262
}
func Response.MarshalJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

71
func (v Response) MarshalJSON() ([]byte, error) {
72
        w := jwriter.Writer{}
73
        easyjson3c9d2b01EncodeGithubComUserHello(&w, v)
74
        return w.Buffer.BuildBytes(), w.Error
75
}
func ConnTracker.TrackActivity
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/conn_tracker.go:

31
func (ct *ConnTracker) TrackActivity(isIdle bool) {
32
        if ct.isClosed.Load() == false {
33
                ct.idleChan <- isIdle
34
        }
35
}
func LicenseWatcher.Stop
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

211
func (lw *LicenseWatcher) Stop() {
212
        close(lw.done)
213
        lw.wg.Wait()
214
}
func LicenseWatcher.Start
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

111
func (lw *LicenseWatcher) Start() {
112
        lw.wg.Add(1)
113
        go func() {
114
                defer failureWatchdog.CapturePanic()
115
                lw.watcher()
116
        }()
117
}
func @113:5
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

113
func() {
114
                defer failureWatchdog.CapturePanic()
115
                lw.watcher()
116
        }
func Database.WithUserIPWhitelist
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

75
func (db *Database) WithUserIPWhitelist(wl *UserIPWhiteList) *Database {
76
        db.userIPWhitelist = wl
77
        return db
78
}
func Database.WithUserWhitelist
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

70
func (db *Database) WithUserWhitelist(wl *UserWhiteList) *Database {
71
        db.usersWhitelist = wl
72
        return db
73
}
func FailureWatchdogRecord.Msgsize
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog_record_gen.go:

143
func (z *FailureWatchdogRecord) Msgsize() (s int) {
144
        s = 1 + 11 + msgp.ArrayHeaderSize + (len(z.Timestamps) * (msgp.Int64Size))
145
        return
146
}
func FailureWatchdogRecord.DumpToFile
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog_record.go:

42
func (r *FailureWatchdogRecord) DumpToFile(path string) error {
43
        data := r.Marshal()
44
        return afero.WriteFile(appFs, path, data, 0o644)
45
}
func FailureWatchdogRecord.Unmarshal
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog_record.go:

18
func (r *FailureWatchdogRecord) Unmarshal(data []byte) error {
19
        _, err := r.UnmarshalMsg(data)
20
        return err
21
}
func FailureWatchdogRecord.Marshal
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog_record.go:

13
func (r FailureWatchdogRecord) Marshal() []byte {
14
        b, _ := r.MarshalMsg(nil)
15
        return b
16
}
func Record.Unmarshal
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/record.go:

15
func (r *Record) Unmarshal(data []byte) error {
16
        _, err := r.UnmarshalMsg(data)
17
        return err
18
}
func Record.Marshal
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/record.go:

10
func (r Record) Marshal() []byte {
11
        b, _ := r.MarshalMsg(nil)
12
        return b
13
}
func ModuleStringResponse
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/module.go:

107
func ModuleStringResponse(action, message string) []byte {
108
        b, _ := Response{Action: action, Message: message}.MarshalJSON()
109
        return b
110
}
func @80:19
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/rbl.go:

80
func(ctx context.Context, network, address string) (net.Conn, error) {
81
                        d := net.Dialer{}
82
                        return d.DialContext(ctx, "udp", nameserver)
83
                }
func UserIPLockConfig.ForgeAutowhitelistLockConfig
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

79
func (l UserIPLockConfig) ForgeAutowhitelistLockConfig() LockConfig {
80
        return LockConfig{
81
                Timeout:  l.AutowhitelistTimeout,
82
                Attempts: 1,
83
                Period:   l.AutowhitelistTimeout,
84
        }
85
}
func NewConnTracker
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/conn_tracker.go:

21
func NewConnTracker(duration time.Duration) *ConnTracker {
22
        return &ConnTracker{
23
                Duration: duration,
24
                Done:     make(chan struct{}),
25
                idleChan: make(chan bool, idleChanBufferSize),
26
                stop:     make(chan struct{}),
27
        }
28
}
func loadLockConfigIP
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

232
func loadLockConfigIP(s *ini.Section, defaultWhitelist string, defaultIncludeList string) LockConfig {
233
        return LockConfig{
234
                Timeout:           rangeInt64(s.Key("IP_LOCK_TIMEOUT"), 5, 0, 9999999) * 60,
235
                Attempts:          rangeInt(s.Key("IP_LOCK_ATTEMPTS"), 10, 0, 100),
236
                Period:            rangeInt64(s.Key("IP_LOCK_MINUTES"), 5, 0, 9999999) * 60,
237
                WhitelistFileName: s.Key("whitelisted_ips_path").MustString(defaultWhitelist) + "," + s.Key("whitelisted_ips_include").MustString(defaultIncludeList),
238
        }
239
}
func @23:20
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/utils.go:

23
func(fd uintptr) {
24
                cred, err = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
25
        }
func UserIPLockConfig.IsAutowhitelistEnabled
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

75
func (l UserIPLockConfig) IsAutowhitelistEnabled() bool {
76
        return l.AutowhitelistTimeout > 0
77
}
func @49:17
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api.go:

49
func(counts gobreaker.Counts) bool {
50
                                return counts.ConsecutiveFailures >= 3
51
                        }
func @186:17
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/rbl.go:

186
func() {
187
                        err = value.err
188
                }
func StatRecord.UnmarshalEasyJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

132
func (v *StatRecord) UnmarshalEasyJSON(l *jlexer.Lexer) {
133
        easyjsonD587a15Decode1(l, v)
134
}
func ConnTracker.Stop
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/conn_tracker.go:

69
func (ct *ConnTracker) Stop() {
70
        close(ct.stop)
71
}
func init
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/sentry.go:

21
func init() {
22
        rand.Seed(time.Now().UnixNano())
23
}
func StatRecord.MarshalEasyJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

120
func (v StatRecord) MarshalEasyJSON(w *jwriter.Writer) {
121
        easyjsonD587a15Encode1(w, v)
122
}
func Agent.RequestId
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

440
func (p *Agent) RequestId() uint {
441
        return uint(atomic.AddUint32(&p.requestId, 1))
442
}
func loadLockConfigUser
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

223
func loadLockConfigUser(s *ini.Section, defaultWhitelist string) LockConfig {
224
        return LockConfig{
225
                Timeout:           rangeInt64(s.Key("USER_LOCK_TIMEOUT"), 5, 0, 9999999) * 60,
226
                Attempts:          rangeInt(s.Key("USER_LOCK_ATTEMPTS"), 10, 0, 100),
227
                Period:            rangeInt64(s.Key("USER_LOCK_MINUTES"), 5, 0, 9999999) * 60,
228
                WhitelistFileName: s.Key("whitelisted_users_path").MustString(defaultWhitelist),
229
        }
230
}
func loadLockConfigUserIP
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

241
func loadLockConfigUserIP(s *ini.Section, defaultWhitelist string) UserIPLockConfig {
242
        return UserIPLockConfig{
243
                LockConfig: LockConfig{
244
                        Timeout:           rangeInt64(s.Key("USER_IP_LOCK_TIMEOUT"), 5, 0, 9999999) * 60,
245
                        Attempts:          rangeInt(s.Key("USER_IP_LOCK_ATTEMPTS"), 10, 0, 100),
246
                        Period:            rangeInt64(s.Key("USER_IP_LOCK_MINUTES"), 5, 0, 9999999) * 60,
247
                        WhitelistFileName: s.Key("whitelisted_user_ip_path").MustString(defaultWhitelist),
248
                },
249
                AutowhitelistTimeout: rangeInt64(s.Key("USER_IP_LOCK_AUTOWHITELIST_TIMEOUT"), 20160, 0, 9999999) * 60,
250
        }
251
}
func NewSendMessageAPI
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api.go:

40
func NewSendMessageAPI(apiURL string, agentVersion string, timeout time.Duration) *SendMessageAPI {
41
        return &SendMessageAPI{
42
                agentVersion: agentVersion,
43
                client:       &http.Client{Timeout: timeout},
44
                baseURL:      apiURL,
45
                cb: gobreaker.NewCircuitBreaker(gobreaker.Settings{
46
                        Name:     "SendMessageAPIBreaker",
47
                        Interval: timeout * 5,
48
                        Timeout:  timeout * 2,
49
                        ReadyToTrip: func(counts gobreaker.Counts) bool {
50
                                return counts.ConsecutiveFailures >= 3
51
                        },
52
                }),
53
        }
54
}
func LockConfig.IsEnabled
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

71
func (l LockConfig) IsEnabled() bool {
72
        return l.Timeout > 0 && l.Attempts > 0 && l.Period > 0
73
}
func Config.IsVerboseLoggingMode
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

55
func (cfg *Config) IsVerboseLoggingMode() bool {
56
        return cfg.IsLogfileEnabled()
57
}
func UserWhiteList.reset
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

134
func (wl *UserWhiteList) reset() {
135
        // root user is the must have default
136
        wl.users = map[string]struct{}{
137
                "root": struct{}{},
138
        }
139
}
func UserWhiteList.loadLine
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

141
func (wl *UserWhiteList) loadLine(line string) {
142
        wl.users[line] = struct{}{}
143
}
func IPWhiteList.reset
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

190
func (wl *IPWhiteList) reset() {
191
        wl.ipRanger = cidranger.NewPCTrieRanger()
192
}
func Config.IsSentryEnabled
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

51
func (cfg *Config) IsSentryEnabled() bool {
52
        return cfg.Sentry != "" && cfg.Sentry != "off"
53
}
func Config.IsLogfileEnabled
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

47
func (cfg *Config) IsLogfileEnabled() bool {
48
        return cfg.LogFilename != ""
49
}
func NewLicenseWatcher
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

99
func NewLicenseWatcher(licPath, pubKeyPath, altPubKeyPath string, interval time.Duration) *LicenseWatcher {
100
        return &LicenseWatcher{
101
                done:          make(chan struct{}),
102
                interval:      interval,
103
                licPath:       licPath,
104
                pubKeyPath:    pubKeyPath,
105
                altPubKeyPath: altPubKeyPath,
106
                subs:          make([]LicenseListener, 0, 1),
107
        }
108
}
func License.signedContent
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

60
func (lic License) signedContent() []byte {
61
        return []byte(fmt.Sprintf("%s%s%s%d%d%d", lic.ID, lic.Status, lic.Group, lic.Limit, lic.TokenCreatedUTC, lic.TokenExpireUTC))
62
}
func UserIPWhiteList.reset
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

247
func (wl *UserIPWhiteList) reset() {
248
        wl.users = make(map[string]cidranger.Ranger)
249
}
func easyjson2c6259e0Encode1
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license_proto_easyjson.go:

90
func easyjson2c6259e0Encode1(out *jwriter.Writer, in License) {
91
        out.RawByte('{')
92
        first := true
93
        _ = first
94
        {
95
                const prefix string = ",\"group\":"
96
                out.RawString(prefix[1:])
97
                out.String(string(in.Group))
98
        }
99
        {
100
                const prefix string = ",\"id\":"
101
                out.RawString(prefix)
102
                out.String(string(in.ID))
103
        }
104
        {
105
                const prefix string = ",\"limit\":"
106
                out.RawString(prefix)
107
                out.Int(int(in.Limit))
108
        }
109
        {
110
                const prefix string = ",\"message\":"
111
                out.RawString(prefix)
112
                out.String(string(in.Message))
113
        }
114
        {
115
                const prefix string = ",\"sign\":"
116
                out.RawString(prefix)
117
                out.String(string(in.Sign))
118
        }
119
        {
120
                const prefix string = ",\"signatures\":"
121
                out.RawString(prefix)
122
                if in.Signatures == nil && (out.Flags&jwriter.NilSliceAsEmpty) == 0 {
123
                        out.RawString("null")
124
                } else {
125
                        out.RawByte('[')
126
                        for v2, v3 := range in.Signatures {
127
                                if v2 > 0 {
128
                                        out.RawByte(',')
129
                                }
130
                                out.String(string(v3))
131
                        }
132
                        out.RawByte(']')
133
                }
134
        }
135
        {
136
                const prefix string = ",\"status\":"
137
                out.RawString(prefix)
138
                out.String(string(in.Status))
139
        }
140
        {
141
                const prefix string = ",\"token_created_utc\":"
142
                out.RawString(prefix)
143
                out.Int(int(in.TokenCreatedUTC))
144
        }
145
        {
146
                const prefix string = ",\"token_expire_utc\":"
147
                out.RawString(prefix)
148
                out.Int(int(in.TokenExpireUTC))
149
        }
150
        {
151
                const prefix string = ",\"upgrade_url\":"
152
                out.RawString(prefix)
153
                out.String(string(in.UpgradeURL))
154
        }
155
        out.RawByte('}')
156
}
func easyjsonD587a15Encode12
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

338
func easyjsonD587a15Encode12(out *jwriter.Writer, in License) {
339
        out.RawByte('{')
340
        first := true
341
        _ = first
342
        {
343
                const prefix string = ",\"group\":"
344
                out.RawString(prefix[1:])
345
                out.String(string(in.Group))
346
        }
347
        {
348
                const prefix string = ",\"id\":"
349
                out.RawString(prefix)
350
                out.String(string(in.ID))
351
        }
352
        {
353
                const prefix string = ",\"limit\":"
354
                out.RawString(prefix)
355
                out.Int(int(in.Limit))
356
        }
357
        {
358
                const prefix string = ",\"message\":"
359
                out.RawString(prefix)
360
                out.String(string(in.Message))
361
        }
362
        {
363
                const prefix string = ",\"sign\":"
364
                out.RawString(prefix)
365
                out.String(string(in.Sign))
366
        }
367
        {
368
                const prefix string = ",\"signatures\":"
369
                out.RawString(prefix)
370
                if in.Signatures == nil && (out.Flags&jwriter.NilSliceAsEmpty) == 0 {
371
                        out.RawString("null")
372
                } else {
373
                        out.RawByte('[')
374
                        for v5, v6 := range in.Signatures {
375
                                if v5 > 0 {
376
                                        out.RawByte(',')
377
                                }
378
                                out.String(string(v6))
379
                        }
380
                        out.RawByte(']')
381
                }
382
        }
383
        {
384
                const prefix string = ",\"status\":"
385
                out.RawString(prefix)
386
                out.String(string(in.Status))
387
        }
388
        {
389
                const prefix string = ",\"token_created_utc\":"
390
                out.RawString(prefix)
391
                out.Int(int(in.TokenCreatedUTC))
392
        }
393
        {
394
                const prefix string = ",\"token_expire_utc\":"
395
                out.RawString(prefix)
396
                out.Int(int(in.TokenExpireUTC))
397
        }
398
        {
399
                const prefix string = ",\"upgrade_url\":"
400
                out.RawString(prefix)
401
                out.String(string(in.UpgradeURL))
402
        }
403
        out.RawByte('}')
404
}
func easyjsonD587a15Encode11
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

197
func easyjsonD587a15Encode11(out *jwriter.Writer, in SendMessagesApiRequest) {
198
        out.RawByte('{')
199
        first := true
200
        _ = first
201
        {
202
                const prefix string = ",\"rpm_ver\":"
203
                out.RawString(prefix[1:])
204
                out.String(string(in.AgentVersion))
205
        }
206
        if true {
207
                const prefix string = ",\"license\":"
208
                out.RawString(prefix)
209
                easyjsonD587a15Encode12(out, in.License)
210
        }
211
        if in.Method != "" {
212
                const prefix string = ",\"method\":"
213
                out.RawString(prefix)
214
                out.String(string(in.Method))
215
        }
216
        {
217
                const prefix string = ",\"ver\":"
218
                out.RawString(prefix)
219
                out.String(string(in.ProtocolVersion))
220
        }
221
        if in.ServerID != "" {
222
                const prefix string = ",\"server_id\":"
223
                out.RawString(prefix)
224
                out.String(string(in.ServerID))
225
        }
226
        {
227
                const prefix string = ",\"payload\":"
228
                out.RawString(prefix)
229
                if in.Payload == nil && (out.Flags&jwriter.NilSliceAsEmpty) == 0 {
230
                        out.RawString("null")
231
                } else {
232
                        out.RawByte('[')
233
                        for v2, v3 := range in.Payload {
234
                                if v2 > 0 {
235
                                        out.RawByte(',')
236
                                }
237
                                (v3).MarshalEasyJSON(out)
238
                        }
239
                        out.RawByte(']')
240
                }
241
        }
242
        out.RawByte('}')
243
}
func Agent.WriteStat
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

290
func (p *Agent) WriteStat(success bool, service, ip, username, password string) {
291
        if p.cfg.SendStats == false || ip == "127.0.0.1" {
292
                return
293
        }
294
295
        now := time.Now()
296
        p.statLock.Lock()
297
        if success {
298
                message := fmt.Sprintf("%s s_ip %s - %s:e res:true", service, ip, username)
299
                record, ok := p.statSuccessfulRecords[message]
300
                if !ok {
301
                        p.statSuccessfulRecords[message] = &StatRecord{
302
                                Name:        "pam_imunify info",
303
                                AttackersIP: ip,
304
                                Rule:        77777,
305
                                Message:     message,
306
                                Severity:    1,
307
                                Retries:     1,
308
                                Timestamp:   now.Unix(),
309
                                PluginId:    "pam_imunify",
310
                        }
311
                } else {
312
                        record.Retries++
313
                }
314
315
                if p.statSuccessfulTime.IsZero() {
316
                        p.statSuccessfulTime = now
317
                } else if p.statSuccessfulTime.Add(time.Duration(p.cfg.SendStatsSuccessfulAggTime) * time.Second).Before(now) {
318
                        p.statSuccessfulTime = time.Time{}
319
                        p.statCh <- p.statSuccessfulRecords
320
                        p.statSuccessfulRecords = make(map[string]*StatRecord)
321
                }
322
        } else {
323
                message := fmt.Sprintf("%s s_ip %s - %s:%s res:false", service, ip, username, password)
324
                record, ok := p.statUnsuccessfulRecords[message]
325
                if !ok {
326
                        p.statUnsuccessfulRecords[message] = &StatRecord{
327
                                Name:        "pam_imunify info",
328
                                AttackersIP: ip,
329
                                Rule:        77777,
330
                                Message:     message,
331
                                Severity:    1,
332
                                Retries:     1,
333
                                Timestamp:   now.Unix(),
334
                                PluginId:    "pam_imunify",
335
                        }
336
                } else {
337
                        record.Retries++
338
                }
339
340
                if p.statUnsuccessfulTime.IsZero() {
341
                        p.statUnsuccessfulTime = now
342
                } else if p.statUnsuccessfulTime.Add(time.Duration(p.cfg.SendStatsUnsuccessfulAggTime) * time.Second).Before(now) {
343
                        p.statUnsuccessfulTime = time.Time{}
344
                        p.statCh <- p.statUnsuccessfulRecords
345
                        p.statUnsuccessfulRecords = make(map[string]*StatRecord)
346
                }
347
        }
348
349
        p.statLock.Unlock()
350
351
}
func Database.writeAttempt
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

345
func (db *Database) writeAttempt(batch *leveldb.Batch, key, hash string, cfg *LockConfig) error {
346
        var changed bool
347
348
        if !cfg.IsEnabled() {
349
                return nil
350
        }
351
352
        record, err := db.readRecord(key)
353
        if err != nil {
354
                return err
355
        }
356
357
        ts := time.Now().Unix()
358
359
        // Remove expired attempts first
360
        for hash, expiredAt := range record.Attempts {
361
                if expiredAt < ts {
362
                        delete(record.Attempts, hash)
363
                        changed = true
364
                }
365
        }
366
367
        // Write current attempt if not exist
368
        if _, ok := record.Attempts[hash]; !ok {
369
                if record.Attempts == nil {
370
                        record.Attempts = make(map[string]int64, 1)
371
                }
372
373
                record.Attempts[hash] = ts + cfg.Period
374
                changed = true
375
        }
376
377
        // Remove lock if expired
378
        if record.LockExpireAt != 0 && record.LockExpireAt < ts {
379
                record.LockExpireAt = 0
380
                changed = true
381
        }
382
383
        // Lock if no lock and attempts too much
384
        if record.LockExpireAt == 0 && len(record.Attempts) >= cfg.Attempts {
385
                record.LockExpireAt = ts + cfg.Timeout
386
                changed = true
387
        }
388
389
        // Write changes if needed
390
        if changed {
391
                db.writeRecord(batch, key, &record)
392
        }
393
394
        return nil
395
}
func readWhiteList
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

24
func readWhiteList(fileName string, lineHandler func(line string)) (fileModTime time.Time, err error) {
25
        var (
26
                file *os.File
27
                info os.FileInfo
28
        )
29
30
        file, err = os.Open(fileName)
31
        if err != nil {
32
                return
33
        }
34
35
        info, err = file.Stat()
36
        if err != nil {
37
                return
38
        }
39
40
        fileModTime = info.ModTime()
41
42
        sc := bufio.NewScanner(file)
43
        for sc.Scan() {
44
                if line := strings.TrimSpace(sc.Text()); line != "" {
45
                        lineHandler(line)
46
                }
47
        }
48
49
        err = sc.Err()
50
        return
51
}
func easyjson3c9d2b01EncodeGithubComUserHello1
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

175
func easyjson3c9d2b01EncodeGithubComUserHello1(out *jwriter.Writer, in Request) {
176
        out.RawByte('{')
177
        first := true
178
        _ = first
179
        {
180
                const prefix string = ",\"type\":"
181
                out.RawString(prefix[1:])
182
                out.String(string(in.Type))
183
        }
184
        {
185
                const prefix string = ",\"service\":"
186
                out.RawString(prefix)
187
                out.String(string(in.Service))
188
        }
189
        {
190
                const prefix string = ",\"user\":"
191
                out.RawString(prefix)
192
                out.String(string(in.User))
193
        }
194
        {
195
                const prefix string = ",\"host\":"
196
                out.RawString(prefix)
197
                out.String(string(in.Host))
198
        }
199
        {
200
                const prefix string = ",\"hash\":"
201
                out.RawString(prefix)
202
                if in.Hash == nil && (out.Flags&jwriter.NilSliceAsEmpty) == 0 {
203
                        out.RawString("null")
204
                } else {
205
                        out.RawByte('[')
206
                        for v2, v3 := range in.Hash {
207
                                if v2 > 0 {
208
                                        out.RawByte(',')
209
                                }
210
                                out.String(string(v3))
211
                        }
212
                        out.RawByte(']')
213
                }
214
        }
215
        {
216
                const prefix string = ",\"timestamp\":"
217
                out.RawString(prefix)
218
                if in.Timestamp == nil {
219
                        out.RawString("null")
220
                } else {
221
                        out.Int64(int64(*in.Timestamp))
222
                }
223
        }
224
        {
225
                const prefix string = ",\"timeout\":"
226
                out.RawString(prefix)
227
                if in.Timeout == nil {
228
                        out.RawString("null")
229
                } else {
230
                        out.Int64(int64(*in.Timeout))
231
                }
232
        }
233
        {
234
                const prefix string = ",\"sign\":"
235
                out.RawString(prefix)
236
                out.String(string(in.Sign))
237
        }
238
        out.RawByte('}')
239
}
func UserIPWhiteList.In
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

281
func (wl *UserIPWhiteList) In(user string, ip string) bool {
282
        if wl == nil {
283
                return false
284
        }
285
286
        wl.Update()
287
288
        ipNet := net.ParseIP(ip)
289
290
        var exist bool
291
        if wl.users != nil && ipNet != nil {
292
                wl.RLock()
293
                item, got := wl.users[user]
294
                if got {
295
                        contains, err := item.Contains(ipNet)
296
                        exist = (err == nil) && (contains == true)
297
                }
298
                wl.RUnlock()
299
        }
300
301
        return exist
302
}
func CheckRBL
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/rbl.go:

128
func CheckRBL(nameserver string, rbl []string, ip string, timeout time.Duration) (bool, error) {
129
        if ip == "" || ip == "127.0.0.1" {
130
                return false, nil
131
        }
132
133
        ctx, cancel := context.WithTimeout(context.Background(), timeout)
134
        defer cancel()
135
136
        var e error = nil
137
        for _, server := range rbl {
138
                r := rblLookupIP(ctx, nameserver, server, ip)
139
                for _, res := range r.Results {
140
                        if res.Error == false {
141
                                return true, nil
142
                        } else {
143
                                e = res.ErrorType
144
                        }
145
                }
146
        }
147
148
        return false, e
149
}
func ConnTracker.HandleActivity
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/conn_tracker.go:

41
func (ct *ConnTracker) HandleActivity() {
42
        timer := time.NewTimer(ct.Duration)
43
        defer func() {
44
                timer.Stop()
45
                close(ct.idleChan)
46
                close(ct.Done)
47
        }()
48
        for {
49
                select {
50
                case isIdle := <-ct.idleChan:
51
                        timer.Stop()
52
                        if isIdle {
53
                                timer.Reset(ct.Duration)
54
                        }
55
                case <-timer.C:
56
                        select {
57
                        case <-ct.idleChan:
58
                                timer.Reset(ct.Duration)
59
                        default:
60
                                ct.Done <- struct{}{}
61
                        }
62
                case <-ct.stop:
63
                        ct.isClosed.Store(true)
64
                        return
65
                }
66
        }
67
}
func IPWhiteList.In
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

212
func (wl *IPWhiteList) In(ipString string) bool {
213
        if wl == nil {
214
                return false
215
        }
216
217
        wl.Update()
218
219
        ip := net.ParseIP(ipString)
220
221
        var exist bool
222
        if wl.ipRanger != nil && ip != nil {
223
                wl.RLock()
224
                contains, err := wl.ipRanger.Contains(ip)
225
                exist = (err == nil) && (contains == true)
226
                wl.RUnlock()
227
        }
228
229
        return exist
230
}
func rblLookupIP
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/rbl.go:

107
func rblLookupIP(ctx context.Context, nameserver string, rbl string, targetIP string) (r RBLResults) {
108
        r.List = rbl
109
        r.Host = targetIP
110
111
        res := Result{}
112
        res.Address = targetIP
113
114
        ip := net.ParseIP(targetIP)
115
        if ip == nil {
116
                return
117
        }
118
119
        addr := ReverseIP(ip)
120
121
        query(ctx, nameserver, rbl, addr, &res)
122
123
        r.Results = append(r.Results, res)
124
125
        return
126
}
func IPWhiteList.loadLine
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

194
func (wl *IPWhiteList) loadLine(item string) {
195
        if strings.Contains(item, "/") == true {
196
                _, ipNet, err := net.ParseCIDR(item)
197
                if err == nil {
198
                        wl.ipRanger.Insert(cidranger.NewBasicRangerEntry(*ipNet))
199
                }
200
        } else {
201
                ip := net.ParseIP(item)
202
                if ip != nil {
203
                        mask := net.CIDRMask(32, 32)
204
                        if ip.To4() == nil {
205
                                mask = net.CIDRMask(128, 128)
206
                        }
207
                        wl.ipRanger.Insert(cidranger.NewBasicRangerEntry(net.IPNet{IP: ip, Mask: mask}))
208
                }
209
        }
210
}
func getOsRelease
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/sentry.go:

81
func getOsRelease() (os_release string, err error) {
82
        var f *os.File
83
        f, err = os.Open("/etc/os-release")
84
        if err != nil {
85
                return
86
        }
87
        defer f.Close()
88
89
        data, _ := ioutil.ReadAll(f)
90
91
        matches := regexp.MustCompile(`PRETTY_NAME=(.+)`).FindSubmatch(data)
92
        if len(matches) > 1 {
93
                os_release = strings.Trim(string(matches[1]), "\"")
94
        }
95
96
        return
97
}
func LicenseWatcher.rereadLicense
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

157
func (lw *LicenseWatcher) rereadLicense() *License {
158
        fi, err := os.Stat(lw.licPath)
159
        dummy := &License{}
160
        if err != nil {
161
                dummy.err = fmt.Errorf("fs.Stat(%#v) failed: %v", lw.licPath, err)
162
                return dummy
163
        }
164
        mt := fi.ModTime()
165
        if !mt.After(lw.lastModified) {
166
                return nil
167
        }
168
        f, err := os.Open(lw.licPath)
169
        if err != nil {
170
                dummy.err = fmt.Errorf("fs.Open(%#v) failed: %v", lw.licPath, err)
171
                return dummy
172
        }
173
        defer f.Close()
174
        lic, err := LoadLicense(f)
175
        if err != nil {
176
                dummy.err = fmt.Errorf("LoadLicense() failed: %v", err)
177
                return dummy
178
        }
179
        lw.lastModified = mt
180
        return &lic
181
}
func UserWhiteList.In
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

145
func (wl *UserWhiteList) In(key string) bool {
146
        if wl == nil {
147
                return false
148
        }
149
150
        wl.Update()
151
152
        var exist bool
153
        wl.RLock()
154
        if wl.users != nil {
155
                _, exist = wl.users[key]
156
        }
157
        wl.RUnlock()
158
        return exist
159
}
func CPanelFtpAuthRecv
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/cpanel.go:

18
func CPanelFtpAuthRecv(conn net.Conn) ([]byte, error) {
19
        var rb []byte
20
        reader := bufio.NewReader(conn)
21
        for {
22
                b, err := reader.ReadBytes('\n')
23
                if err != nil {
24
                        return nil, err
25
                }
26
27
                rb = append(rb, b...)
28
29
                if bytes.Equal([]byte("end\n"), b) {
30
                        return rb, nil
31
                }
32
        }
33
}
func @212:20
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/rbl.go:

212
func(key interface{}) (interface{}, *time.Duration, error) {
213
                        s, ok := key.(string)
214
                        if !ok {
215
                                return nil, nil, fmt.Errorf("LRU Cache: Bad key value type")
216
                        }
217
                        value, err := CheckRBL(r.cfg.ResolverAddr, r.cfg.RBLServers, s, r.cfg.RequestTimeout)
218
                        if value {
219
                                return value, &r.cfg.CacheInRBLTimeout, nil
220
                        }
221
                        if err == nil || strings.HasSuffix(err.Error(), "no such host") {
222
                                return false, &r.cfg.CacheNotInRBLTimeout, nil
223
                        }
224
                        return &rblError{err: err}, &r.cfg.CacheErrorTimeout, nil
225
                }
func UserIPWhiteList.loadLine
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

251
func (wl *UserIPWhiteList) loadLine(item string) {
252
        fields := strings.Fields(item)
253
        if len(fields) < 2 {
254
                return
255
        }
256
257
        user := fields[0]
258
        if _, ok := wl.users[user]; !ok {
259
                wl.users[user] = cidranger.NewPCTrieRanger()
260
        }
261
262
        for _, item := range fields[1:] {
263
                if strings.Contains(item, "/") == true {
264
                        _, ipNet, err := net.ParseCIDR(item)
265
                        if err == nil {
266
                                wl.users[user].Insert(cidranger.NewBasicRangerEntry(*ipNet))
267
                        }
268
                } else {
269
                        ip := net.ParseIP(item)
270
                        if ip != nil {
271
                                mask := net.CIDRMask(32, 32)
272
                                if ip.To4() == nil {
273
                                        mask = net.CIDRMask(128, 128)
274
                                }
275
                                wl.users[user].Insert(cidranger.NewBasicRangerEntry(net.IPNet{IP: ip, Mask: mask}))
276
                        }
277
                }
278
        }
279
}
func Database.Close
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

107
func (db *Database) Close() error {
108
        db.lock.Lock()
109
        defer db.lock.Unlock()
110
111
        if atomic.LoadInt64(&db.closed) == 0 {
112
                atomic.SwapInt64(&db.closed, 1)
113
                db.stopExpireOld <- true
114
                db.waitExpireOld.Wait()
115
                return db.db.Close()
116
        }
117
        return nil
118
}
func LicenseWatcher.watcher
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

119
func (lw *LicenseWatcher) watcher() {
120
        defer lw.wg.Done()
121
122
        ticker := time.NewTicker(lw.interval)
123
        defer ticker.Stop()
124
125
        lw.readLicenseAndNotify()
126
        for {
127
                select {
128
                case <-lw.done:
129
                        return
130
                case <-ticker.C:
131
                        lw.readLicenseAndNotify()
132
                }
133
        }
134
}
func LoadLicense
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

65
func LoadLicense(r io.Reader) (License, error) {
66
        var lic License
67
        b, err := io.ReadAll(r)
68
        if err != nil {
69
                return lic, err
70
        }
71
        err = json.Unmarshal(b, &lic)
72
        if err != nil {
73
                return lic, fmt.Errorf("%s: '%s'", err, string(b))
74
        } else {
75
                return lic, nil
76
        }
77
}
func Agent.ServeListener
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

397
func (p *Agent) ServeListener(l net.Listener, connCallback func(c net.Conn)) {
398
        defer failureWatchdog.CapturePanic()
399
        for {
400
                c, err := l.Accept()
401
                if err != nil {
402
                        if shouldLogError(err) {
403
                                log.WithError(err).Errorf("accept: %v", err)
404
                        }
405
                        break
406
                }
407
408
                p.connListLock.Lock()
409
                p.connList[c] = struct{}{}
410
                if p.Tracker != nil {
411
                        p.Tracker.TrackActivity(false)
412
                }
413
                p.connListLock.Unlock()
414
415
                p.connRoutinesWait.Add(1)
416
                //go p.ServeConn(c, connCallback)
417
                go func(c net.Conn, connCallback func(c net.Conn)) {
418
                        defer failureWatchdog.CapturePanic()
419
                        connCallback(c)
420
421
                        p.connListLock.Lock()
422
                        if _, ok := p.connList[c]; ok {
423
                                delete(p.connList, c)
424
                                err := c.Close()
425
                                if err != nil {
426
                                        log.WithError(err).Errorf("connection close: %v", err)
427
                                }
428
                        }
429
                        if len(p.connList) == 0 && p.Tracker != nil {
430
                                p.Tracker.TrackActivity(true)
431
                        }
432
                        p.connListLock.Unlock()
433
434
                        p.connRoutinesWait.Done()
435
                }(c, connCallback)
436
        }
437
        p.acceptRoutineWait.Done()
438
}
func Agent.Stop
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

444
func (p *Agent) Stop() error {
445
        // Stop accepting new connections
446
        for path := range p.acceptList {
447
                listener := p.acceptList[path]
448
                _ = listener.Close()
449
        }
450
        p.acceptRoutineWait.Wait()
451
452
        // Close all opened connections
453
        p.connListLock.Lock()
454
        for conn := range p.connList {
455
                _ = conn.Close()
456
                delete(p.connList, conn)
457
        }
458
        p.connListLock.Unlock()
459
        p.connRoutinesWait.Wait()
460
        if p.Tracker != nil {
461
                p.Tracker.Stop()
462
        }
463
464
        if p.cfg.RBLTimeout > 0 {
465
                p.statsRBLCheckStop <- struct{}{}
466
        }
467
468
        if p.cfg.SendStats {
469
                p.statLock.Lock()
470
                p.statCh <- p.statSuccessfulRecords
471
                p.statCh <- p.statUnsuccessfulRecords
472
                p.statLock.Unlock()
473
                close(p.statCh)
474
                p.statWait.Wait()
475
                p.lw.Stop()
476
        }
477
478
        err := p.db.Close()
479
        if err != nil {
480
                return fmt.Errorf("database close: %w", err)
481
        }
482
483
        if p.syslog != nil {
484
                p.syslog.Close()
485
        }
486
487
        if sentryLoggerHook != nil {
488
                sentryLoggerHook.Flush()
489
                sentryLoggerHook.SetEnabled(false)
490
        }
491
492
        log.SetLevel(log.InfoLevel)
493
        log.SetOutput(os.Stderr)
494
495
        return nil
496
}
func LoadPublicKey
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

22
func LoadPublicKey(r io.Reader) (*rsa.PublicKey, error) {
23
        p, err := io.ReadAll(r)
24
        if err != nil {
25
                return nil, err
26
        }
27
        block, _ := pem.Decode(p)
28
        if block == nil {
29
                return nil, fmt.Errorf("failed to load PEM data")
30
        }
31
        key, err := x509.ParsePKIXPublicKey(block.Bytes)
32
        if err != nil {
33
                return nil, err
34
        }
35
        pubKey, ok := key.(*rsa.PublicKey)
36
        if !ok {
37
                return nil, fmt.Errorf("public key is not RSA: %v", key)
38
        }
39
        return pubKey, nil
40
}
func @417:6
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

417
func(c net.Conn, connCallback func(c net.Conn)) {
418
                        defer failureWatchdog.CapturePanic()
419
                        connCallback(c)
420
421
                        p.connListLock.Lock()
422
                        if _, ok := p.connList[c]; ok {
423
                                delete(p.connList, c)
424
                                err := c.Close()
425
                                if err != nil {
426
                                        log.WithError(err).Errorf("connection close: %v", err)
427
                                }
428
                        }
429
                        if len(p.connList) == 0 && p.Tracker != nil {
430
                                p.Tracker.TrackActivity(true)
431
                        }
432
                        p.connListLock.Unlock()
433
434
                        p.connRoutinesWait.Done()
435
                }
func init
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

34
func init() {
35
        sentryLogger, err := NewSentryLogger(filepath.Base(os.Args[0]), PackageVersion)
36
        if err == nil {
37
                sentryLoggerHook = sentryLogger
38
                sentryLoggerHook.SetEnabled(false)
39
                log.AddHook(sentryLogger)
40
        } else {
41
                log.WithError(err).Errorf("sentry reporting will be disabled: %v", err)
42
        }
43
}
func Agent.Serve
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

386
func (p *Agent) Serve(path string, connCallback func(c net.Conn)) error {
387
        listener := p.acceptList[path]
388
        if listener == nil {
389
                return fmt.Errorf("no listener at %s ", path)
390
        }
391
392
        p.acceptRoutineWait.Add(1)
393
        go p.ServeListener(listener, connCallback)
394
        return nil
395
}
func @169:18
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

169
func(l License, valid bool) {
170
                        var lic *License
171
                        if valid {
172
                                lic = &l
173
                                log.Info("Detected a valid license.")
174
                        } else {
175
                                log.WithFields(log.Fields{
176
                                        log.ErrorKey:       l.err,
177
                                        "agent_lic_status": GetAgentLicStatus(),
178
                                }).Warnf("INVALID license has been detected.")
179
                        }
180
                        atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&p.license)), unsafe.Pointer(lic))
181
                }
func Agent.ServeSendStat
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

255
func (p *Agent) ServeSendStat() {
256
        defer failureWatchdog.CapturePanic()
257
        for statsMap := range p.statCh {
258
                if len(statsMap) == 0 {
259
                        continue
260
                }
261
                stats := make([]StatRecord, 0, len(statsMap))
262
                for _, v := range statsMap {
263
                        stats = append(stats, *v)
264
                }
265
266
                license := (*License)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&p.license))))
267
                err := p.sendMessageAPI.SendStats(license, stats)
268
                if err != nil {
269
                        if errors.Is(err, errInvalidLicense) {
270
                                log.WithFields(log.Fields{
271
                                        log.ErrorKey:       err,
272
                                        "records_num":      len(stats),
273
                                        "agent_lic_status": GetAgentLicStatus(),
274
                                }).Warnf("Send stats for %d records error: %v", len(stats), err)
275
                        } else {
276
                                log.WithFields(log.Fields{
277
                                        log.ErrorKey:       err,
278
                                        "records_num":      len(stats),
279
                                        "agent_lic_status": GetAgentLicStatus(),
280
                                }).Errorf("Send stats for %d records error: %v", len(stats), err)
281
                        }
282
                        continue
283
                }
284
                log.Infof("Send stats for %d records success", len(stats))
285
                log.WithField("records", stats).Debug("Send stats records")
286
        }
287
        p.statWait.Done()
288
}
func NewIPWhiteList
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

167
func NewIPWhiteList(file string) (*IPWhiteList, error) {
168
        if file == "" {
169
                return nil, nil
170
        }
171
172
        var (
173
                err       error
174
                fileNames []string
175
        )
176
177
        // Split file paths by ','
178
        r := csv.NewReader(strings.NewReader(file))
179
        r.Comma = ','
180
        fileNames, err = r.Read()
181
        if err != nil {
182
                return nil, err
183
        }
184
185
        wl := &IPWhiteList{}
186
        wl.WhiteList = NewWhiteList(fileNames, wl.reset, wl.loadLine)
187
        return wl, err
188
}
func NewUserIPWhiteList
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

238
func NewUserIPWhiteList(file string) *UserIPWhiteList {
239
        if file == "" {
240
                return nil
241
        }
242
        wl := &UserIPWhiteList{}
243
        wl.WhiteList = NewWhiteList([]string{file}, wl.reset, wl.loadLine)
244
        return wl
245
}
func SendMessageAPI.send
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api.go:

62
func (ca *SendMessageAPI) send(requestBody MarshalJSON) error {
63
        b, err := requestBody.MarshalJSON()
64
        if err != nil {
65
                return err
66
        }
67
68
        _, err = ca.cb.Execute(func() (interface{}, error) {
69
                res, err := ca.client.Post(ca.baseURL+sendMessageURL, sendMessageContentTypeJSON, bytes.NewReader(b))
70
                if err != nil {
71
                        return nil, err
72
                }
73
                defer res.Body.Close()
74
75
                body, err := ioutil.ReadAll(res.Body)
76
                if err != nil {
77
                        return nil, err
78
                }
79
80
                switch res.StatusCode {
81
                case http.StatusOK:
82
                        return body, nil
83
                case http.StatusUnauthorized:
84
                        if bytes.Contains(bytes.ToLower(body), invalidLicenseSlice) {
85
                                return body, fmt.Errorf("%w: %s, %s", errInvalidLicense, res.Status, string(body))
86
                        }
87
                        fallthrough
88
                default:
89
                        return body, fmt.Errorf("error response: %d, %s", res.StatusCode, string(body))
90
                }
91
        })
92
93
        return err
94
}
func loadHostPort
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

183
func loadHostPort(k *ini.Key, defaultVal string, defaultPort string) string {
184
        addr := k.MustString(defaultVal)
185
        i := strings.IndexByte(addr, ':')
186
        if i < 0 {
187
                return fmt.Sprintf("%s:%s", addr, defaultPort)
188
        }
189
        return addr
190
}
func NewUserWhiteList
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

124
func NewUserWhiteList(file string) *UserWhiteList {
125
        if file == "" {
126
                return nil
127
        }
128
129
        wl := &UserWhiteList{}
130
        wl.WhiteList = NewWhiteList([]string{file}, wl.reset, wl.loadLine)
131
        return wl
132
}
func Database.expireOld
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

228
func (db *Database) expireOld() (nextExpiration int64, err error) {
229
        if atomic.LoadInt64(&db.closed) != 0 {
230
                return 0, ErrClosed
231
        }
232
233
        ts := time.Now().Unix()
234
235
        batch := new(leveldb.Batch)
236
237
        db.lock.Lock()
238
        defer db.lock.Unlock()
239
240
        iter := db.db.NewIterator(nil, nil)
241
        for iter.Next() {
242
                var (
243
                        changed bool
244
                        record  Record
245
                )
246
247
                key := iter.Key()
248
                value := iter.Value()
249
250
                err := record.Unmarshal(value)
251
                if err != nil {
252
                        // Cleanup bad records
253
                        batch.Delete(key)
254
                        log.Tracef("---[db]->> del %v", key)
255
                }
256
257
                // Remove expired attempts
258
                for hash, expiredAt := range record.Attempts {
259
                        if expiredAt < ts {
260
                                delete(record.Attempts, hash)
261
                                changed = true
262
                                continue
263
                        }
264
                        if nextExpiration > expiredAt {
265
                                nextExpiration = expiredAt
266
                        }
267
                }
268
269
                // Remove lock if expired
270
                if record.LockExpireAt != 0 && record.LockExpireAt < ts {
271
                        record.LockExpireAt = 0
272
                        changed = true
273
                }
274
275
                if record.LockExpireAt != 0 && record.LockExpireAt < nextExpiration {
276
                        nextExpiration = record.LockExpireAt
277
                }
278
279
                if changed {
280
                        db.writeRecord(batch, string(key), &record)
281
                }
282
        }
283
        iter.Release()
284
285
        err = iter.Error()
286
        if err != nil {
287
                return 0, fmt.Errorf("iterator: %v", err)
288
        }
289
290
        if batch.Len() == 0 {
291
                return
292
        }
293
294
        err = db.db.Write(batch, nil)
295
        if err != nil {
296
                err = fmt.Errorf("batch write: %v", err)
297
        }
298
299
        return
300
}
func Database.WriteAttempts
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

302
func (db *Database) WriteAttempts(ip string, user string, hash string) error {
303
        batch := new(leveldb.Batch)
304
305
        if atomic.LoadInt64(&db.closed) != 0 {
306
                return ErrClosed
307
        }
308
309
        db.lock.Lock()
310
        defer db.lock.Unlock()
311
312
        if user != "" {
313
                err := db.writeAttempt(batch, user, hash, &db.cfg.UserLock)
314
                if err != nil {
315
                        return fmt.Errorf("USER_LOCK: %v", err)
316
                }
317
        }
318
319
        if ip != "" && ip != "127.0.0.1" {
320
                err := db.writeAttempt(batch, ip, hash, &db.cfg.IPLock)
321
                if err != nil {
322
                        return fmt.Errorf("IP_LOCK: %v", err)
323
                }
324
        }
325
326
        if user != "" && ip != "" {
327
                err := db.writeAttempt(batch, ip+"/"+user, hash, &db.cfg.UserIPLock.LockConfig)
328
                if err != nil {
329
                        return fmt.Errorf("USER_IP_LOCK: %v", err)
330
                }
331
        }
332
333
        if batch.Len() == 0 {
334
                return nil
335
        }
336
337
        err := db.db.Write(batch, nil)
338
        if err != nil {
339
                return fmt.Errorf("batch write: %v", err)
340
        }
341
342
        return nil
343
}
func FailureWatchdogRecord.ReadFromFile
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog_record.go:

23
func (r *FailureWatchdogRecord) ReadFromFile(path string) error {
24
        data, err := afero.ReadFile(appFs, path)
25
        if err != nil {
26
                return err
27
        }
28
29
        // The file is empty
30
        if len(data) < 1 {
31
                return nil
32
        }
33
34
        err = r.Unmarshal(data)
35
        if err != nil {
36
                return err
37
        }
38
39
        return nil
40
}
func getOwnIP
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/sentry.go:

45
func getOwnIP() (ip string, err error) {
46
        client := &http.Client{
47
                Timeout: 2 * time.Second,
48
        }
49
50
        resp, err := client.Get("https://api.ipify.org")
51
        if err != nil {
52
                return "", err
53
        }
54
55
        defer resp.Body.Close()
56
        body, err := ioutil.ReadAll(resp.Body)
57
        if err != nil {
58
                return "", err
59
        }
60
61
        return string(body), nil
62
}
func Agent.ProcessModuleRequest
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/module.go:

112
func (p *Agent) ProcessModuleRequest(r Request, name string) []byte {
113
        r.Host = ToIP(r.Host)
114
115
        switch r.Type {
116
        case "check":
117
                isWhitelisted, err := whitelist.Query(r.Host)
118
                if err != nil {
119
                        log.WithError(err).Errorf("failed to query wafd: %v", err)
120
                } else if isWhitelisted {
121
                        return ResponseOK
122
                }
123
124
                result, err := p.db.CheckLock(r.Host, r.User)
125
                if err != nil {
126
                        log.WithError(err).Errorf("check lock: %v", err)
127
                        return ResponseFailure
128
                }
129
130
                var response string
131
132
                if result&UserLock != NoLock {
133
                        response = fmt.Sprintf(
134
                                "[IM360_UL] The account %s has been temporarily locked by Imunify PAM(%s)",
135
                                r.User, r.Host)
136
                }
137
                if result&IPLock != NoLock {
138
                        response = fmt.Sprintf("[IM360_IPL] The IP %s has been locked by Imunify PAM", r.Host)
139
                }
140
                if result&UserIPLock != NoLock {
141
                        response = fmt.Sprintf(
142
                                "[IM360_IPUL] The account %s has been locked for the attacker IP %s",
143
                                r.User, r.Host)
144
                }
145
146
                if p.cfg.RBLTimeout > 0 && p.rbl != nil {
147
                        value, err := p.rbl.Check(r.Host)
148
                        if err != nil {
149
                                noSuchHost := strings.HasSuffix(err.Error(), "no such host")
150
                                if !noSuchHost {
151
                                        if dnsErr, isDNSErr := err.(*net.DNSError); isDNSErr && dnsErr.IsTimeout {
152
                                                atomic.AddInt64(&p.statRBLCheck.Timeout, 1)
153
                                        } else {
154
                                                atomic.AddInt64(&p.statRBLCheck.Errors, 1)
155
                                                log.WithError(err).Errorf("RBL check: %v", err)
156
                                        }
157
                                } else {
158
                                        atomic.AddInt64(&p.statRBLCheck.Success, 1)
159
                                }
160
                        } else {
161
                                atomic.AddInt64(&p.statRBLCheck.Success, 1)
162
                        }
163
                        if value {
164
                                response = fmt.Sprintf(
165
                                        "[IM360_RBL] The IP %s has been locked due to Imunify RBL", r.Host)
166
                        }
167
                }
168
169
                if len(response) > 0 {
170
                        return ModuleStringResponse(actionBlocked, response)
171
                }
172
173
                return ResponseOK
174
        case "failed":
175
                for _, hash := range r.Hash {
176
                        err := p.db.WriteAttempts(r.Host, r.User, hash)
177
                        if err != nil {
178
                                log.WithError(err).Errorf("write filed attempt: %v", err)
179
                        }
180
                        p.WriteStat(false, fmt.Sprintf("%s[%s]", r.Service, name), r.Host, r.User, hash)
181
                }
182
                return nil
183
        case "success":
184
                err := p.db.RemoveSuccess(r.Host, r.User)
185
                if err != nil {
186
                        log.WithError(err).Errorf("write filed attempt: %v", err)
187
                        return ResponseFailure
188
                }
189
                p.WriteStat(true, fmt.Sprintf("%s[%s]", r.Service, name), r.Host, r.User, "e")
190
                return nil
191
        }
192
193
        return nil
194
}
func Agent.ProcessCPanelFtpAuthRequest
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/cpanel.go:

83
func (p *Agent) ProcessCPanelFtpAuthRequest(data []byte, name string) []byte {
84
        var request CPanelAuthMsg
85
        request.Unmarshal(data)
86
        if request.Account == "" || request.Password == "" {
87
                log.WithField("data", string(data)).Warnf("parse request: No user credentials")
88
                return nil
89
        }
90
        request.Peer = ToIP(request.Peer)
91
92
        isWhitelisted, err := whitelist.Query(request.Peer)
93
        if err != nil {
94
                log.WithError(err).Errorf("failed to query wafd: %v", err)
95
        }
96
97
        if request.Peer == "" || isWhitelisted == false {
98
                result, err := p.db.CheckLock(request.Peer, request.Account)
99
                if err != nil {
100
                        log.WithError(err).Errorf("check lock: %v", err)
101
                }
102
103
                if result&UserLock != NoLock {
104
                        msg := fmt.Sprintf(
105
                                "pam_imunify(cpanel_ftp_auth:auth): [IM360_UL] The account %s has been temporarily locked by Imunify PAM(%s)",
106
                                request.Account, request.Peer)
107
                        if p.syslog != nil {
108
                                p.syslog.Err(msg)
109
                        } else {
110
                                log.WithFields(log.Fields{
111
                                        "type": "syslog",
112
                                }).Info(msg)
113
                        }
114
                        return ResponseCPanelAuthFtpdReject
115
                }
116
                if result&IPLock != NoLock {
117
                        msg := fmt.Sprintf(
118
                                "pam_imunify(cpanel_ftp_auth:auth): [IM360_IPL] The IP %s has been locked by Imunify PAM",
119
                                request.Peer)
120
                        if p.syslog != nil {
121
                                p.syslog.Err(msg)
122
                        } else {
123
                                log.WithFields(log.Fields{
124
                                        "type": "syslog",
125
                                }).Info(msg)
126
                        }
127
                        return ResponseCPanelAuthFtpdReject
128
                }
129
                if result&UserIPLock != NoLock {
130
                        msg := fmt.Sprintf(
131
                                "pam_imunify(cpanel_ftp_auth:auth): [IM360_IPUL] The account %s has been locked for the attacker IP %s",
132
                                request.Account, request.Peer)
133
                        if p.syslog != nil {
134
                                p.syslog.Err(msg)
135
                        } else {
136
                                log.WithFields(log.Fields{
137
                                        "type": "syslog",
138
                                }).Info(msg)
139
                        }
140
                        return ResponseCPanelAuthFtpdReject
141
                }
142
143
                if result&UserLock != NoLock || result&IPLock != NoLock || result&UserIPLock != NoLock {
144
145
                }
146
147
                if request.Peer != "" && p.cfg.RBLTimeout > 0 && p.rbl != nil {
148
                        value, err := p.rbl.Check(request.Peer)
149
                        if err != nil {
150
                                noSuchHost := strings.HasSuffix(err.Error(), "no such host")
151
                                if !noSuchHost {
152
                                        if dnsErr, isDNSErr := err.(*net.DNSError); isDNSErr && dnsErr.IsTimeout {
153
                                                atomic.AddInt64(&p.statRBLCheck.Timeout, 1)
154
                                        } else {
155
                                                atomic.AddInt64(&p.statRBLCheck.Errors, 1)
156
                                                log.WithError(err).Errorf("RBL check: %v", err)
157
                                        }
158
                                } else {
159
                                        atomic.AddInt64(&p.statRBLCheck.Success, 1)
160
                                }
161
                        } else {
162
                                atomic.AddInt64(&p.statRBLCheck.Success, 1)
163
                        }
164
                        if value {
165
                                msg := fmt.Sprintf(
166
                                        "pam_imunify(cpanel_ftp_auth:auth): [IM360_RBL] The IP %s has been locked due to Imunify RBL",
167
                                        request.Peer)
168
                                if p.syslog != nil {
169
                                        p.syslog.Err(msg)
170
                                } else {
171
                                        log.WithFields(log.Fields{
172
                                                "type": "syslog",
173
                                        }).Info(msg)
174
                                }
175
                                return ResponseCPanelAuthFtpdReject
176
                        }
177
                }
178
        }
179
180
        cpanelConn, err := net.DialTimeout("unix", p.cfg.CPanelFtpAuthOutSocket, time.Duration(p.cfg.CPanelFtpAuthOutTimeout)*time.Second)
181
        if err != nil {
182
                log.WithError(err).Errorf("CPanel auth ftpd connect: %v", err)
183
                return nil
184
        }
185
        defer cpanelConn.Close()
186
187
        _ = cpanelConn.SetDeadline(time.Now().Add(time.Duration(p.cfg.CPanelFtpAuthOutTimeout) * time.Second))
188
189
        _, err = cpanelConn.Write(data)
190
        if err != nil {
191
                log.WithError(err).Errorf("CPanel auth ftpd write: %v", err)
192
                return nil
193
        }
194
195
        var responseData []byte
196
        responseData, err = CPanelFtpAuthRecv(cpanelConn)
197
        if err != nil {
198
                log.WithError(err).Errorf("CPanel auth ftpd read: %v", err)
199
                return nil
200
        }
201
202
        var response CPanelAuthMsg
203
        response.Unmarshal(responseData)
204
205
        switch response.AuthOk {
206
        case "1":
207
                err := p.db.RemoveSuccess(request.Peer, request.Account)
208
                if err != nil {
209
                        log.WithError(err).Errorf("write filed attempt: %v", err)
210
                }
211
                p.WriteStat(true, fmt.Sprintf("cpanel_ftp_auth[%s]", name), request.Peer, request.Account, "e")
212
        case "-1", "0":
213
                hash := fmt.Sprintf("%x", xxh3.HashString(request.Account+request.Password))
214
                err := p.db.WriteAttempts(request.Peer, request.Account, hash)
215
                if err != nil {
216
                        log.WithError(err).Errorf("write filed attempt: %v", err)
217
                }
218
                p.WriteStat(false, fmt.Sprintf("cpanel_ftp_auth[%s]", name), request.Peer, request.Account, hash)
219
        default:
220
                log.WithFields(log.Fields{
221
                        "response_auth": response.AuthOk,
222
                        "response":      string(responseData),
223
                }).Errorf("CPanel auth ftpd: bad auth response \"%s\"", response.AuthOk)
224
        }
225
226
        return responseData
227
}
func NewSentryLogger
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/sentry.go:

118
func NewSentryLogger(pkgName string, pkgVersion string) (*logrus_sentry.SentryHook, error) {
119
        transport := sentry.NewHTTPSyncTransport()
120
        transport.Configure(sentry.ClientOptions{
121
                Dsn: SentryDsn,
122
        })
123
        client, err := sentry.NewClient(sentry.ClientOptions{
124
                Dsn:       SentryDsn,
125
                Transport: transport,
126
        })
127
        if err != nil {
128
                log.Errorf("failed to create sentry client: %v", err)
129
        }
130
131
        scope := SentryScope
132
        scope.SetTag("name", pkgName)
133
        scope.SetTag("version", pkgVersion)
134
135
        serverIP, err := getOwnIP()
136
        if err != nil {
137
                log.Errorf("failed to retrieve server IP: %v", err)
138
139
                // recording the err for more informative server_ip breakdown
140
                scope.SetTag("server_ip", fmt.Sprintf("%v", err))
141
        } else if serverIP != "" {
142
                scope.SetTag("server_ip", serverIP)
143
        }
144
145
        serverID, err := getServerId()
146
        if err != nil {
147
                log.Errorf("failed to retrieve server ID: %v", err)
148
                scope.SetUser(sentry.User{
149
                        ID: "N/A",
150
                })
151
        } else if serverID != "" {
152
                scope.SetUser(sentry.User{
153
                        ID: serverID,
154
                })
155
        } else {
156
                scope.SetUser(sentry.User{
157
                        ID: "N/A",
158
                })
159
        }
160
161
        osRelease, err := getOsRelease()
162
        if err != nil {
163
                log.Errorf("failed to retrieve OS release: %v", err)
164
        } else if osRelease != "" {
165
                scope.SetTag("os.version", osRelease)
166
        }
167
168
        errorRateLimitList := []logrus_sentry.ErrorRateLimiter{
169
                &errHasSuffixRateLimit{
170
                        err: syscall.ENOSPC,
171
                        rs:  rateSample(enospcSamplingRate),
172
                },
173
                &errHasSuffixRateLimit{
174
                        err: syscall.EPERM,
175
                        rs:  rateSample(epermSamplingRate),
176
                },
177
        }
178
179
        return logrus_sentry.NewSentryHook(client, scope, &logrus_sentry.SentryHookConfiguration{
180
                Levels:                 log.AllLevels,
181
                ReportLevels:           log.ErrorLevel,
182
                BreadcrumbLevels:       log.InfoLevel,
183
                IncludeErrorBreadcrumb: true,
184
                StacktraceEnable:       true,
185
                StacktraceLevel:        log.ErrorLevel,
186
                LimitErrors:            errorRateLimitList,
187
        })
188
}
func shouldLogError
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

77
func shouldLogError(err error) bool {
78
        if err == nil {
79
                return false
80
        }
81
82
        if err == io.EOF {
83
                return false
84
        }
85
86
        str := err.Error()
87
        if strings.Contains(str, "use of closed network connection") {
88
                return false
89
        }
90
91
        return true
92
}
func WhiteList.isNeedUpdate
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

69
func (wl *WhiteList) isNeedUpdate() bool {
70
        for fileName, fileModTime := range wl.file {
71
                info, err := os.Stat(fileName)
72
                if err != nil || info == nil {
73
                        if !fileModTime.IsZero() {
74
                                return true
75
                        }
76
                } else if !info.ModTime().Equal(fileModTime) {
77
                        return true
78
                }
79
        }
80
        return false
81
}
func Request.CheckSign
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request.go:

55
func (r Request) CheckSign(secret, key string) bool {
56
        sign, err := hex.DecodeString(r.Sign)
57
        if err != nil {
58
                return false
59
        }
60
        return bytes.Equal(r.calcSign(secret, key), sign)
61
}
func GetAgentLicStatus
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

146
func GetAgentLicStatus() string {
147
        status, err := exec.Command("/usr/bin/imunify360-agent", "rstatus").Output()
148
        if err != nil {
149
                return fmt.Sprintf("%v", err)
150
        } else {
151
                return strings.TrimSpace(string(status))
152
        }
153
}
func IsRunningSystemd
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/service.go:

14
func IsRunningSystemd() bool {
15
        fi, err := os.Lstat("/run/systemd/system")
16
        if err != nil {
17
                return false
18
        }
19
        return fi.IsDir()
20
}
func Agent.Start
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

96
func (p *Agent) Start(cfg *Config) (err error) {
97
        p.cfg = cfg
98
99
        // For tests purpose
100
        if p.apiURL == "" {
101
                p.apiURL = apiURL
102
        }
103
104
        if p.cfg.IsLogfileEnabled() {
105
                var logfile *os.File
106
                logfile, err = os.OpenFile(p.cfg.LogFilename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0660)
107
                if err != nil {
108
                        return fmt.Errorf("log open: %v", err)
109
                }
110
                log.SetOutput(logfile)
111
        }
112
113
        if sentryLoggerHook != nil {
114
                if len(p.cfg.RBL) == 0 {
115
                        SentryScope.SetTag("rbl0", "nil")
116
                } else {
117
                        for i, rbl := range p.cfg.RBL {
118
                                SentryScope.SetTag(fmt.Sprintf("rbl%d", i), rbl)
119
                        }
120
                }
121
                SentryScope.SetTag("rbl_timeout", strconv.FormatInt(p.cfg.RBLTimeout, 10))
122
                SentryScope.SetTag("rbl_cache_ttl", strconv.FormatInt(p.cfg.RBLCacheTTL, 10))
123
                SentryScope.SetTag("rbl_cache_size", strconv.Itoa(p.cfg.RBLCacheSize))
124
125
                if p.cfg.IsSentryEnabled() {
126
                        sentryLoggerHook.SetEnabled(true)
127
                        log.Info("sentry error reporting is enabled.")
128
                } else {
129
                        sentryLoggerHook.SetEnabled(false)
130
                        log.Info("sentry error reporting is disabled.")
131
                }
132
        }
133
134
        if p.cfg.IsVerboseLoggingMode() {
135
                log.SetLevel(log.TraceLevel)
136
        } else {
137
                log.SetLevel(log.InfoLevel)
138
        }
139
140
        p.syslog, err = syslog.New(syslog.LOG_AUTHPRIV, "pam_imunify")
141
        if err != nil {
142
                log.WithError(err).Errorf("new syslog instance: %v", err)
143
        }
144
145
        p.db, err = DatabaseOpen(p.cfg)
146
        if err != nil {
147
                dbOpenErr := err
148
149
                // Plan B: start from scratch
150
                err = DatabaseDrop(p.cfg)
151
                if err == nil {
152
                        p.db, err = DatabaseOpen(p.cfg)
153
                }
154
                if err != nil {
155
                        return fmt.Errorf("database failover: %v", err)
156
                } else {
157
                        log.WithError(dbOpenErr).Warnf("database failover success: %v", dbOpenErr)
158
                }
159
        }
160
161
        if p.cfg.SendStats {
162
                p.statSuccessfulRecords = make(map[string]*StatRecord)
163
                p.statUnsuccessfulRecords = make(map[string]*StatRecord)
164
                p.statCh = make(chan map[string]*StatRecord)
165
166
                p.sendMessageAPI = NewSendMessageAPI(apiURL, PackageVersion, sendMessageAPITimeout)
167
168
                p.lw = NewLicenseWatcher(p.cfg.LicensePath, p.cfg.PublicKeyPath, p.cfg.AltPublicKeyPath, licenseReadInterval)
169
                p.lw.Subscribe(func(l License, valid bool) {
170
                        var lic *License
171
                        if valid {
172
                                lic = &l
173
                                log.Info("Detected a valid license.")
174
                        } else {
175
                                log.WithFields(log.Fields{
176
                                        log.ErrorKey:       l.err,
177
                                        "agent_lic_status": GetAgentLicStatus(),
178
                                }).Warnf("INVALID license has been detected.")
179
                        }
180
                        atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&p.license)), unsafe.Pointer(lic))
181
                })
182
                p.lw.Subscribe(func(l License, valid bool) {
183
                        if valid {
184
                                // Leave a chance to flip sentry reporting back.
185
                                sentryLoggerHook.SetEnabled(p.cfg.IsSentryEnabled())
186
                        } else {
187
                                if l.err != nil {
188
                                        sentryLoggerHook.SetEnabled(false)
189
                                        if p.cfg.IsSentryEnabled() {
190
                                                log.WithFields(log.Fields{
191
                                                        log.ErrorKey:       l.err,
192
                                                        "agent_lic_status": GetAgentLicStatus(),
193
                                                }).Errorf("sentry error reporting is disabled (because of INVALID license error)")
194
                                        }
195
                                }
196
                        }
197
                })
198
                p.lw.Start()
199
200
                p.statWait.Add(1)
201
                go p.ServeSendStat()
202
        }
203
204
        p.wlUser = NewUserWhiteList(p.cfg.UserLock.WhitelistFileName)
205
        p.wlUserIP = NewUserIPWhiteList(p.cfg.UserIPLock.LockConfig.WhitelistFileName)
206
207
        p.db.WithUserWhitelist(p.wlUser).WithUserIPWhitelist(p.wlUserIP)
208
209
        if p.cfg.RBLTimeout > 0 {
210
                p.rbl = NewRBL(RBLConfig{
211
                        ResolverAddr:         p.cfg.ResolvConf,
212
                        RBLServers:           p.cfg.RBL,
213
                        RequestTimeout:       time.Duration(p.cfg.RBLTimeout) * time.Second,
214
                        CacheSize:            p.cfg.RBLCacheSize,
215
                        CacheInRBLTimeout:    time.Duration(p.cfg.RBLCacheTTL) * time.Second,
216
                        CacheNotInRBLTimeout: 1 * time.Minute,
217
                        CacheErrorTimeout:    1 * time.Minute,
218
                })
219
                p.statsRBLCheckStop = make(chan struct{})
220
                go p.ServeLogRBLStat()
221
        }
222
223
        p.connList = make(map[net.Conn]struct{})
224
225
        listeners, err := GetListeners(p.cfg.Socket, p.cfg.CPanelFtpAuthInSocket)
226
        if err != nil {
227
                return fmt.Errorf("failed to listen on sockets: %w", err)
228
        }
229
        if err := ModifyDovecotSocket(p.cfg.Socket); err != nil {
230
                return fmt.Errorf("failed to modify dovecot socket %s: %w", p.cfg.Socket, err)
231
        }
232
233
        p.acceptList = listeners
234
235
        idleTimeout := cfg.IdleTimeout
236
        if idleTimeout > 0 && IsRunningSystemd() {
237
                p.Tracker = NewConnTracker(time.Duration(idleTimeout) * time.Second)
238
                go p.Tracker.HandleActivity()
239
        }
240
241
        err = p.Serve(p.cfg.Socket, p.ProcessModuleConn)
242
        if err != nil {
243
                return fmt.Errorf("listen: %v", err)
244
        }
245
246
        if p.cfg.CPanelFtpAuthInSocket != "" && p.cfg.CPanelFtpAuthOutSocket != "" && p.cfg.CPanelFtpAuthOutTimeout > 0 {
247
                err = p.Serve(p.cfg.CPanelFtpAuthInSocket, p.ProcessCPanelFtpAuthConn)
248
                if err != nil {
249
                        return fmt.Errorf("listen: %v", err)
250
                }
251
        }
252
        return
253
}
func DatabaseOpen
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

30
func DatabaseOpen(cfg *Config) (db *Database, err error) {
31
        var database *leveldb.DB
32
33
        path := filepath.Join(cfg.Database, "/leveldb")
34
        database, err = leveldb.OpenFile(path, nil)
35
        if err != nil {
36
                return
37
        }
38
39
        db = &Database{
40
                cfg:           cfg,
41
                path:          path,
42
                db:            database,
43
                stopExpireOld: make(chan bool, 1),
44
        }
45
46
        var nextExpire int64
47
        nextExpire, err = db.expireOld()
48
        if err == nil {
49
                db.waitExpireOld.Add(1)
50
                go db.serveExpireOld(nextExpire)
51
                return
52
        }
53
54
        err = fmt.Errorf("expire old: %v", err)
55
        _ = db.db.Close()
56
        return nil, err
57
}
func Database.readRecord
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

397
func (db Database) readRecord(key string) (record Record, err error) {
398
        var data []byte
399
        data, err = db.db.Get([]byte(key), nil)
400
        if err == leveldb.ErrNotFound {
401
                err = nil
402
                log.WithField("record", "nil").Tracef("<--[db]--- %v", key)
403
                return
404
        }
405
        if err != nil {
406
                err = fmt.Errorf("get record: %v", err)
407
                return
408
        }
409
410
        err = record.Unmarshal(data)
411
        if err != nil {
412
                err = fmt.Errorf("unmarshal: %v", err)
413
                return
414
        }
415
416
        log.WithField("record", record).Tracef("<--[db]--- %v", key)
417
        return
418
}
func easyjson2c6259e0Decode1
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license_proto_easyjson.go:

20
func easyjson2c6259e0Decode1(in *jlexer.Lexer, out *License) {
21
        isTopLevel := in.IsStart()
22
        if in.IsNull() {
23
                if isTopLevel {
24
                        in.Consumed()
25
                }
26
                in.Skip()
27
                return
28
        }
29
        in.Delim('{')
30
        for !in.IsDelim('}') {
31
                key := in.UnsafeFieldName(false)
32
                in.WantColon()
33
                if in.IsNull() {
34
                        in.Skip()
35
                        in.WantComma()
36
                        continue
37
                }
38
                switch key {
39
                case "group":
40
                        out.Group = string(in.String())
41
                case "id":
42
                        out.ID = string(in.String())
43
                case "limit":
44
                        out.Limit = int(in.Int())
45
                case "message":
46
                        out.Message = string(in.String())
47
                case "sign":
48
                        out.Sign = string(in.String())
49
                case "signatures":
50
                        if in.IsNull() {
51
                                in.Skip()
52
                                out.Signatures = nil
53
                        } else {
54
                                in.Delim('[')
55
                                if out.Signatures == nil {
56
                                        if !in.IsDelim(']') {
57
                                                out.Signatures = make([]string, 0, 4)
58
                                        } else {
59
                                                out.Signatures = []string{}
60
                                        }
61
                                } else {
62
                                        out.Signatures = (out.Signatures)[:0]
63
                                }
64
                                for !in.IsDelim(']') {
65
                                        var v1 string
66
                                        v1 = string(in.String())
67
                                        out.Signatures = append(out.Signatures, v1)
68
                                        in.WantComma()
69
                                }
70
                                in.Delim(']')
71
                        }
72
                case "status":
73
                        out.Status = string(in.String())
74
                case "token_created_utc":
75
                        out.TokenCreatedUTC = int(in.Int())
76
                case "token_expire_utc":
77
                        out.TokenExpireUTC = int(in.Int())
78
                case "upgrade_url":
79
                        out.UpgradeURL = string(in.String())
80
                default:
81
                        in.SkipRecursive()
82
                }
83
                in.WantComma()
84
        }
85
        in.Delim('}')
86
        if isTopLevel {
87
                in.Consumed()
88
        }
89
}
func Database.RemoveSuccess
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

185
func (db *Database) RemoveSuccess(ip string, user string) error {
186
        batch := new(leveldb.Batch)
187
        userIPLockAutowhitelist := false // to keep USER_LOCK and IP_LOCK as is
188
189
        if user != "" && ip != "" && db.cfg.UserIPLock.IsAutowhitelistEnabled() {
190
                record, err := db.readRecord(ip + "/" + user + "|SUCCESS")
191
                if err != nil {
192
                        return fmt.Errorf("read user/ip autowhitelist record: %v", err)
193
                }
194
                if record.LockExpireAt >= time.Now().Unix() {
195
                        userIPLockAutowhitelist = true
196
                }
197
        }
198
199
        if user != "" && !userIPLockAutowhitelist {
200
                batch.Delete([]byte(user))
201
                log.Tracef("---[db]->> del %v", user)
202
        }
203
        if user != "" && ip != "" {
204
                if !userIPLockAutowhitelist {
205
                        batch.Delete([]byte(ip + "/" + user))
206
                        log.Tracef("---[db]->> del %v", ip+"/"+user)
207
                }
208
209
                var cfg LockConfig = db.cfg.UserIPLock.ForgeAutowhitelistLockConfig()
210
                db.writeAttempt(batch, ip+"/"+user+"|SUCCESS", "", &cfg)
211
        }
212
213
        if batch.Len() == 0 {
214
                return nil
215
        }
216
217
        db.lock.Lock()
218
        defer db.lock.Unlock()
219
220
        err := db.db.Write(batch, nil)
221
        if err != nil {
222
                return fmt.Errorf("batch write: %v", err)
223
        }
224
225
        return nil
226
}
func easyjsonD587a15Decode1
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

20
func easyjsonD587a15Decode1(in *jlexer.Lexer, out *StatRecord) {
21
        isTopLevel := in.IsStart()
22
        if in.IsNull() {
23
                if isTopLevel {
24
                        in.Consumed()
25
                }
26
                in.Skip()
27
                return
28
        }
29
        in.Delim('{')
30
        for !in.IsDelim('}') {
31
                key := in.UnsafeFieldName(false)
32
                in.WantColon()
33
                if in.IsNull() {
34
                        in.Skip()
35
                        in.WantComma()
36
                        continue
37
                }
38
                switch key {
39
                case "name":
40
                        out.Name = string(in.String())
41
                case "attackers_ip":
42
                        out.AttackersIP = string(in.String())
43
                case "rule":
44
                        out.Rule = int(in.Int())
45
                case "message":
46
                        out.Message = string(in.String())
47
                case "severity":
48
                        out.Severity = int(in.Int())
49
                case "retries":
50
                        out.Retries = int(in.Int())
51
                case "timestamp":
52
                        out.Timestamp = int64(in.Int64())
53
                case "plugin_id":
54
                        out.PluginId = string(in.String())
55
                default:
56
                        in.SkipRecursive()
57
                }
58
                in.WantComma()
59
        }
60
        in.Delim('}')
61
        if isTopLevel {
62
                in.Consumed()
63
        }
64
}
func Database.serveExpireOld
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

80
func (db *Database) serveExpireOld(nextExpire int64) {
81
        defer failureWatchdog.CapturePanic()
82
        defer db.waitExpireOld.Done()
83
        var err error
84
        for {
85
                ts := time.Now().Unix()
86
87
                if nextExpire < ts+60 {
88
                        nextExpire = 60
89
                } else {
90
                        nextExpire -= ts
91
                }
92
93
                timer := time.NewTimer(time.Duration(nextExpire) * time.Second)
94
95
                select {
96
                case <-db.stopExpireOld:
97
                        return
98
                case <-timer.C:
99
                        nextExpire, err = db.expireOld()
100
                        if err != nil {
101
                                return
102
                        }
103
                }
104
        }
105
}
func ConnProcess
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/utils.go:

39
func ConnProcess(conn net.Conn) (*process.Process, error) {
40
        pid, err := connProcessPid(conn)
41
        if err != nil {
42
                return nil, err
43
        }
44
45
        proc, err := process.NewProcess(pid)
46
        if err != nil {
47
                return nil, err
48
        }
49
50
        return proc, nil
51
}
func ConfigLoad
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

87
func ConfigLoad(path string) (cfg *Config, err error) {
88
        var i *ini.File
89
90
        i, err = ini.Load(path)
91
        if err != nil {
92
                err = fmt.Errorf("fail to read config: %v", err)
93
                return
94
        }
95
96
        cfg = &Config{
97
                LogFilename: i.Section("").
98
                        Key("log").
99
                        MustString(""),
100
101
                Sentry: i.Section("").
102
                        Key("sentry").
103
                        MustString("https://sentry.cloudlinux.com/sentry/i360-pam-imunify/"),
104
105
                Database: i.Section("").
106
                        Key("mod_db_path").
107
                        MustString("/opt/i360_pam_imunify/db"),
108
109
                Socket: i.Section("").
110
                        Key("socket").
111
                        MustString("/opt/i360_pam_imunify/pam_imunify360.sock"),
112
113
                ResolvConf: loadHostPort(i.Section("").Key("RBL_nameserver"),
114
                        "ns1-rbl.imunify.com:53", "53"),
115
116
                SharedKey: loadKeyFile(i.Section("").
117
                        Key("shared_key_file").
118
                        MustString("/opt/i360_pam_imunify/key"), "7raXUdtFcBSr2Bes"),
119
120
                PublicKeyPath: i.Section("").
121
                        Key("public_key_path").
122
                        MustString("/usr/share/imunify360/cln-pub.key"),
123
                AltPublicKeyPath: i.Section("").
124
                        Key("alt_public_key_path").
125
                        MustString("/usr/share/imunify360/alt-license-pub.key"),
126
127
                LicensePath: i.Section("").
128
                        Key("license_path").
129
                        MustString("/var/imunify360/license.json"),
130
131
                SendStats: i.Section("").
132
                        Key("send_stats").MustBool(true),
133
134
                SendStatsSuccessfulAggTime: i.Section("").
135
                        Key("send_stats_success_agg_time").MustInt64(30 * 60),
136
137
                SendStatsUnsuccessfulAggTime: i.Section("").
138
                        Key("send_stats_unsuccess_agg_time").MustInt64(60),
139
140
                RBL: func() []string {
141
                        rbl := i.Section("").Key("rbl").Strings(",")
142
                        if len(rbl) > 0 {
143
                                return rbl
144
                        }
145
                        return []string{"net-brute.rbl.imunify.com"}
146
                }(),
147
                RBLTimeout: i.Section("").
148
                        Key("RBL_timeout").MustInt64(1),
149
                RBLCacheTTL: i.Section("").
150
                        Key("RBL_cache_ttl").MustInt64(600),
151
                RBLCacheSize: i.Section("").
152
                        Key("RBL_cache_size").MustInt(65535),
153
                UserLock: loadLockConfigUser(i.Section(""), "/var/i360_pam_imunify/users/users.txt"),
154
                IPLock: loadLockConfigIP(i.Section(""),
155
                        "/var/i360_pam_imunify/wl/ips.txt",
156
                        "/etc/apache2/conf.d/modsec_vendor_configs/imunify360_full_apache/rbl_whitelist,"+
157
                                "/etc/httpd/conf/modsecurity.d/rules/custom/rbl_whitelist"),
158
                UserIPLock: loadLockConfigUserIP(i.Section(""), ""),
159
160
                CPanelFtpAuthInSocket: i.Section("").
161
                        Key("cpanel_ftp_auth_in_socket").
162
                        MustString("/var/run/ftpd.imunify360.sock"),
163
                CPanelFtpAuthOutSocket: i.Section("").
164
                        Key("cpanel_ftp_auth_out_socket").
165
                        MustString("/var/run/ftpd.sock"),
166
                CPanelFtpAuthOutTimeout: i.Section("").
167
                        Key("cpanel_ftp_auth_out_timeout").MustInt64(15),
168
169
                IdleTimeout: i.Section("").
170
                        Key("idle_timeout").MustInt64(10 * 60),
171
172
                FailureWatchdogEnabled: i.Section("").
173
                        Key("failure_watchdog_enabled").MustBool(true),
174
                FailureWatchdogLimit: i.Section("").
175
                        Key("failure_watchdog_limit").MustInt(10),
176
                FailureWatchdogPeriod: i.Section("").
177
                        Key("failure_watchdog_period").MustInt64(3600),
178
        }
179
180
        return
181
}
func easyjsonD587a15Decode12
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

268
func easyjsonD587a15Decode12(in *jlexer.Lexer, out *License) {
269
        isTopLevel := in.IsStart()
270
        if in.IsNull() {
271
                if isTopLevel {
272
                        in.Consumed()
273
                }
274
                in.Skip()
275
                return
276
        }
277
        in.Delim('{')
278
        for !in.IsDelim('}') {
279
                key := in.UnsafeFieldName(false)
280
                in.WantColon()
281
                if in.IsNull() {
282
                        in.Skip()
283
                        in.WantComma()
284
                        continue
285
                }
286
                switch key {
287
                case "group":
288
                        out.Group = string(in.String())
289
                case "id":
290
                        out.ID = string(in.String())
291
                case "limit":
292
                        out.Limit = int(in.Int())
293
                case "message":
294
                        out.Message = string(in.String())
295
                case "sign":
296
                        out.Sign = string(in.String())
297
                case "signatures":
298
                        if in.IsNull() {
299
                                in.Skip()
300
                                out.Signatures = nil
301
                        } else {
302
                                in.Delim('[')
303
                                if out.Signatures == nil {
304
                                        if !in.IsDelim(']') {
305
                                                out.Signatures = make([]string, 0, 4)
306
                                        } else {
307
                                                out.Signatures = []string{}
308
                                        }
309
                                } else {
310
                                        out.Signatures = (out.Signatures)[:0]
311
                                }
312
                                for !in.IsDelim(']') {
313
                                        var v4 string
314
                                        v4 = string(in.String())
315
                                        out.Signatures = append(out.Signatures, v4)
316
                                        in.WantComma()
317
                                }
318
                                in.Delim(']')
319
                        }
320
                case "status":
321
                        out.Status = string(in.String())
322
                case "token_created_utc":
323
                        out.TokenCreatedUTC = int(in.Int())
324
                case "token_expire_utc":
325
                        out.TokenExpireUTC = int(in.Int())
326
                case "upgrade_url":
327
                        out.UpgradeURL = string(in.String())
328
                default:
329
                        in.SkipRecursive()
330
                }
331
                in.WantComma()
332
        }
333
        in.Delim('}')
334
        if isTopLevel {
335
                in.Consumed()
336
        }
337
}
func easyjsonD587a15Decode11
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

135
func easyjsonD587a15Decode11(in *jlexer.Lexer, out *SendMessagesApiRequest) {
136
        isTopLevel := in.IsStart()
137
        if in.IsNull() {
138
                if isTopLevel {
139
                        in.Consumed()
140
                }
141
                in.Skip()
142
                return
143
        }
144
        in.Delim('{')
145
        for !in.IsDelim('}') {
146
                key := in.UnsafeFieldName(false)
147
                in.WantColon()
148
                if in.IsNull() {
149
                        in.Skip()
150
                        in.WantComma()
151
                        continue
152
                }
153
                switch key {
154
                case "rpm_ver":
155
                        out.AgentVersion = string(in.String())
156
                case "license":
157
                        easyjsonD587a15Decode12(in, &out.License)
158
                case "method":
159
                        out.Method = string(in.String())
160
                case "ver":
161
                        out.ProtocolVersion = string(in.String())
162
                case "server_id":
163
                        out.ServerID = string(in.String())
164
                case "payload":
165
                        if in.IsNull() {
166
                                in.Skip()
167
                                out.Payload = nil
168
                        } else {
169
                                in.Delim('[')
170
                                if out.Payload == nil {
171
                                        if !in.IsDelim(']') {
172
                                                out.Payload = make([]StatRecord, 0, 0)
173
                                        } else {
174
                                                out.Payload = []StatRecord{}
175
                                        }
176
                                } else {
177
                                        out.Payload = (out.Payload)[:0]
178
                                }
179
                                for !in.IsDelim(']') {
180
                                        var v1 StatRecord
181
                                        (v1).UnmarshalEasyJSON(in)
182
                                        out.Payload = append(out.Payload, v1)
183
                                        in.WantComma()
184
                                }
185
                                in.Delim(']')
186
                        }
187
                default:
188
                        in.SkipRecursive()
189
                }
190
                in.WantComma()
191
        }
192
        in.Delim('}')
193
        if isTopLevel {
194
                in.Consumed()
195
        }
196
}
func Database.CheckLock
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

129
func (db *Database) CheckLock(ip string, user string) (LockStatus, error) {
130
        if atomic.LoadInt64(&db.closed) != 0 {
131
                return NoLock, ErrClosed
132
        }
133
134
        ts := time.Now().Unix()
135
136
        var (
137
                record     Record
138
                err        error
139
                lockStatus LockStatus
140
        )
141
142
        if db.cfg.UserIPLock.IsAutowhitelistEnabled() {
143
                record, err = db.readRecord(ip + "/" + user + "|SUCCESS")
144
                if err != nil {
145
                        return NoLock, fmt.Errorf("read user/ip autowhitelist record: %v", err)
146
                }
147
                if record.LockExpireAt >= ts {
148
                        return lockStatus, nil
149
                }
150
        }
151
152
        if db.cfg.UserLock.IsEnabled() && !db.usersWhitelist.In(user) {
153
                record, err = db.readRecord(user)
154
                if err != nil {
155
                        return NoLock, fmt.Errorf("read user record: %v", err)
156
                }
157
                if record.LockExpireAt >= ts {
158
                        lockStatus |= UserLock
159
                }
160
        }
161
162
        if db.cfg.IPLock.IsEnabled() && ip != "" {
163
                record, err = db.readRecord(ip)
164
                if err != nil {
165
                        return NoLock, fmt.Errorf("read ip record: %v", err)
166
                }
167
                if record.LockExpireAt >= ts {
168
                        lockStatus |= IPLock
169
                }
170
        }
171
172
        if db.cfg.UserIPLock.LockConfig.IsEnabled() && ip != "" && !db.userIPWhitelist.In(user, ip) {
173
                record, err = db.readRecord(ip + "/" + user)
174
                if err != nil {
175
                        return NoLock, fmt.Errorf("read user/ip record: %v", err)
176
                }
177
                if record.LockExpireAt >= ts {
178
                        lockStatus |= UserIPLock
179
                }
180
        }
181
182
        return lockStatus, nil
183
}
func Request.calcSign
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request.go:

63
func (r Request) calcSign(secret, key string) []byte {
64
        hash := sha256.New()
65
        hash.Write([]byte(secret))
66
        hash.Write([]byte(r.Type))
67
        hash.Write([]byte(r.Service))
68
        hash.Write([]byte(r.User))
69
        hash.Write([]byte(r.Host))
70
        for _, v := range r.Hash {
71
                hash.Write([]byte(v))
72
        }
73
        if r.Timestamp != nil {
74
                a := make([]byte, 8)
75
                binary.LittleEndian.PutUint64(a, uint64(*r.Timestamp))
76
                hash.Write(a)
77
        }
78
        if r.Timeout != nil {
79
                a := make([]byte, 8)
80
                binary.LittleEndian.PutUint64(a, uint64(*r.Timeout))
81
                hash.Write(a)
82
        }
83
        hash.Write([]byte(key))
84
        return hash.Sum(nil)
85
}
func connProcessPid
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/utils.go:

11
func connProcessPid(conn net.Conn) (int32, error) {
12
        sock, ok := conn.(*net.UnixConn)
13
        if !ok {
14
                return 0, fmt.Errorf("pointer cast error: %#v", conn)
15
        }
16
17
        raw, err := sock.SyscallConn()
18
        if err != nil {
19
                return 0, err
20
        }
21
22
        var cred *syscall.Ucred
23
        err = raw.Control(func(fd uintptr) {
24
                cred, err = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
25
        })
26
        if err != nil {
27
                return 0, fmt.Errorf("GetsockoptUcred: %v", err)
28
        }
29
        if cred == nil {
30
                return 0, fmt.Errorf("Something went wrong: cred = nil")
31
        }
32
        if cred.Pid == 0 {
33
                return 0, fmt.Errorf("Something went wrong: cred.Pid = 0")
34
        }
35
36
        return cred.Pid, nil
37
}
func WhiteList.Update
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/whitelist.go:

95
func (wl *WhiteList) Update() {
96
        select {
97
        case lastCheckTime := <-wl.lastCheckTime:
98
                timeNow := time.Now()
99
                if timeNow.Before(lastCheckTime.Add(1 * time.Second)) {
100
                        wl.lastCheckTime <- lastCheckTime
101
                        return
102
                }
103
104
                if !wl.isNeedUpdate() {
105
                        wl.lastCheckTime <- timeNow
106
                        return
107
                }
108
109
                wl.Lock()
110
                wl.reload()
111
                wl.Unlock()
112
113
                wl.lastCheckTime <- timeNow
114
        default:
115
        }
116
}
func NewRBL
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/rbl.go:

197
func NewRBL(config RBLConfig) RBL {
198
        r := &rbl{
199
                cfg: config,
200
        }
201
        if config.CacheSize <= 0 || config.CacheInRBLTimeout <= 0 {
202
                return r
203
        }
204
        if r.cfg.CacheNotInRBLTimeout <= 0 {
205
                r.cfg.CacheNotInRBLTimeout = 1 * time.Minute
206
        }
207
        if r.cfg.CacheErrorTimeout <= 0 {
208
                r.cfg.CacheErrorTimeout = 1 * time.Minute
209
        }
210
        r.cache = gcache.New(config.CacheSize).
211
                Expiration(config.CacheInRBLTimeout).ARC().
212
                LoaderExpireFunc(func(key interface{}) (interface{}, *time.Duration, error) {
213
                        s, ok := key.(string)
214
                        if !ok {
215
                                return nil, nil, fmt.Errorf("LRU Cache: Bad key value type")
216
                        }
217
                        value, err := CheckRBL(r.cfg.ResolverAddr, r.cfg.RBLServers, s, r.cfg.RequestTimeout)
218
                        if value {
219
                                return value, &r.cfg.CacheInRBLTimeout, nil
220
                        }
221
                        if err == nil || strings.HasSuffix(err.Error(), "no such host") {
222
                                return false, &r.cfg.CacheNotInRBLTimeout, nil
223
                        }
224
                        return &rblError{err: err}, &r.cfg.CacheErrorTimeout, nil
225
                }).Build()
226
        return r
227
}
func SendMessageAPI.SendStats
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api.go:

97
func (ca *SendMessageAPI) SendStats(license *License, messages []StatRecord) error {
98
        if license == nil {
99
                return errInvalidLicense
100
        }
101
102
        if len(messages) == 0 {
103
                return errNoPayload
104
        }
105
106
        r := SendMessagesApiRequest{
107
                AgentVersion:    ca.agentVersion,
108
                ServerID:        license.ID,
109
                Method:          sendMessageMethod,
110
                License:         *license,
111
                Payload:         messages,
112
                ProtocolVersion: sendMessageProtocolVersion,
113
        }
114
115
        return ca.send(r)
116
}
func GetListeners
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/socket.go:

50
func GetListeners(paths ...string) (map[string]net.Listener, error) {
51
        listenerMap := make(map[string]net.Listener, len(paths))
52
53
        listeners, err := activation.Listeners()
54
55
        switch {
56
        case err != nil:
57
                log.Debugf("failed to listen on activation sockets %v", err)
58
        case !IsRunningSystemd():
59
                log.Debugf("running on non-systemd booted OS")
60
        case len(listeners) != len(paths):
61
                log.Debugf("activation sockets and paths mismatch. paths %v: listeners: %v", paths, listeners)
62
        default:
63
                for i, path := range paths {
64
                        listenerMap[path] = listeners[i]
65
                }
66
                return listenerMap, nil
67
        }
68
69
        listenerMap = make(map[string]net.Listener, len(paths))
70
        for _, path := range paths {
71
                _ = os.Remove(path)
72
73
                l, err := net.Listen("unix", path)
74
                if err != nil {
75
                        return listenerMap, fmt.Errorf("failed to listen on unix domain socket: %w", err)
76
                }
77
78
                listenerMap[path] = l
79
        }
80
81
        return listenerMap, nil
82
}
func FailureWatchdogRecord.UnmarshalMsg
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog_record_gen.go:

94
func (z *FailureWatchdogRecord) UnmarshalMsg(bts []byte) (o []byte, err error) {
95
        var field []byte
96
        _ = field
97
        var zb0001 uint32
98
        zb0001, bts, err = msgp.ReadMapHeaderBytes(bts)
99
        if err != nil {
100
                err = msgp.WrapError(err)
101
                return
102
        }
103
        for zb0001 > 0 {
104
                zb0001--
105
                field, bts, err = msgp.ReadMapKeyZC(bts)
106
                if err != nil {
107
                        err = msgp.WrapError(err)
108
                        return
109
                }
110
                switch msgp.UnsafeString(field) {
111
                case "timestamps":
112
                        var zb0002 uint32
113
                        zb0002, bts, err = msgp.ReadArrayHeaderBytes(bts)
114
                        if err != nil {
115
                                err = msgp.WrapError(err, "Timestamps")
116
                                return
117
                        }
118
                        if cap(z.Timestamps) >= int(zb0002) {
119
                                z.Timestamps = (z.Timestamps)[:zb0002]
120
                        } else {
121
                                z.Timestamps = make([]int64, zb0002)
122
                        }
123
                        for za0001 := range z.Timestamps {
124
                                z.Timestamps[za0001], bts, err = msgp.ReadInt64Bytes(bts)
125
                                if err != nil {
126
                                        err = msgp.WrapError(err, "Timestamps", za0001)
127
                                        return
128
                                }
129
                        }
130
                default:
131
                        bts, err = msgp.Skip(bts)
132
                        if err != nil {
133
                                err = msgp.WrapError(err)
134
                                return
135
                        }
136
                }
137
        }
138
        o = bts
139
        return
140
}
func easyjson3c9d2b01DecodeGithubComUserHello
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

20
func easyjson3c9d2b01DecodeGithubComUserHello(in *jlexer.Lexer, out *Response) {
21
        isTopLevel := in.IsStart()
22
        if in.IsNull() {
23
                if isTopLevel {
24
                        in.Consumed()
25
                }
26
                in.Skip()
27
                return
28
        }
29
        in.Delim('{')
30
        for !in.IsDelim('}') {
31
                key := in.UnsafeFieldName(false)
32
                in.WantColon()
33
                if in.IsNull() {
34
                        in.Skip()
35
                        in.WantComma()
36
                        continue
37
                }
38
                switch key {
39
                case "action":
40
                        out.Action = string(in.String())
41
                case "message":
42
                        out.Message = string(in.String())
43
                default:
44
                        in.SkipRecursive()
45
                }
46
                in.WantComma()
47
        }
48
        in.Delim('}')
49
        if isTopLevel {
50
                in.Consumed()
51
        }
52
}
func Agent.ProcessCPanelFtpAuthConn
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/cpanel.go:

35
func (p *Agent) ProcessCPanelFtpAuthConn(c net.Conn) {
36
        proc, err := ConnProcess(c)
37
        var processName string
38
        if err != nil {
39
                processName = fmt.Sprintf("<procNameErr: %v>", err)
40
        } else {
41
                processName, err = proc.Name()
42
                if err != nil {
43
                        processName = fmt.Sprintf("<procNameErr: %v>", err)
44
                }
45
        }
46
47
        b, err := CPanelFtpAuthRecv(c)
48
        if err != nil {
49
                if shouldLogError(err) {
50
                        log.WithError(err).Errorf("read: %v", err)
51
                }
52
                return
53
        }
54
55
        requestId := p.RequestId()
56
57
        log.WithFields(log.Fields{
58
                "request_id": requestId,
59
                "request":    string(b),
60
        }).Debugf("--[svc:%d]->>\n%v", requestId, string(b))
61
62
        resp := p.ProcessCPanelFtpAuthRequest(b, processName)
63
        if resp == nil {
64
                return
65
        }
66
67
        log.WithFields(log.Fields{
68
                "request_id": requestId,
69
                "response":   string(resp),
70
        }).Debugf("<-[svc:%d]---\n%v", requestId, string(resp))
71
72
        _, err = c.Write(resp)
73
        if err != nil {
74
                log.WithError(err).Errorf("connection serve: %v", err)
75
                return
76
        }
77
}
func rbl.Check
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/rbl.go:

176
func (r rbl) Check(ip string) (bool, error) {
177
        if r.cache == nil {
178
                return CheckRBL(r.cfg.ResolverAddr, r.cfg.RBLServers, ip, r.cfg.RequestTimeout)
179
        }
180
        v, err := r.cache.Get(ip)
181
        switch value := v.(type) {
182
        case bool:
183
                return value, err
184
        case *rblError:
185
                err = nil
186
                value.once.Do(func() {
187
                        err = value.err
188
                })
189
                return false, err
190
        }
191
        if err != nil {
192
                return false, err
193
        }
194
        return false, fmt.Errorf("unknown type of cached value: type=%s, values=%v", reflect.TypeOf(v).String(), v)
195
}
func @68:25
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api.go:

68
func() (interface{}, error) {
69
                res, err := ca.client.Post(ca.baseURL+sendMessageURL, sendMessageContentTypeJSON, bytes.NewReader(b))
70
                if err != nil {
71
                        return nil, err
72
                }
73
                defer res.Body.Close()
74
75
                body, err := ioutil.ReadAll(res.Body)
76
                if err != nil {
77
                        return nil, err
78
                }
79
80
                switch res.StatusCode {
81
                case http.StatusOK:
82
                        return body, nil
83
                case http.StatusUnauthorized:
84
                        if bytes.Contains(bytes.ToLower(body), invalidLicenseSlice) {
85
                                return body, fmt.Errorf("%w: %s, %s", errInvalidLicense, res.Status, string(body))
86
                        }
87
                        fallthrough
88
                default:
89
                        return body, fmt.Errorf("error response: %d, %s", res.StatusCode, string(body))
90
                }
91
        }
func rangeInt
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

262
func rangeInt(k *ini.Key, defaultVal, min, max int) int {
263
        val := k.MustInt(defaultVal)
264
        if val < min || val > max {
265
                log.Warnf("Value in config file is out of range %d", val)
266
                return defaultVal
267
        }
268
        return val
269
}
func rangeInt64
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

253
func rangeInt64(k *ini.Key, defaultVal, min, max int64) int64 {
254
        val := k.MustInt64(defaultVal)
255
        if val < min || val > max {
256
                log.Warnf("Value in config file is out of range %d", val)
257
                return defaultVal
258
        }
259
        return val
260
}
func easyjson3c9d2b01DecodeGithubComUserHello1
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

93
func easyjson3c9d2b01DecodeGithubComUserHello1(in *jlexer.Lexer, out *Request) {
94
        isTopLevel := in.IsStart()
95
        if in.IsNull() {
96
                if isTopLevel {
97
                        in.Consumed()
98
                }
99
                in.Skip()
100
                return
101
        }
102
        in.Delim('{')
103
        for !in.IsDelim('}') {
104
                key := in.UnsafeFieldName(false)
105
                in.WantColon()
106
                if in.IsNull() {
107
                        in.Skip()
108
                        in.WantComma()
109
                        continue
110
                }
111
                switch key {
112
                case "type":
113
                        out.Type = string(in.String())
114
                case "service":
115
                        out.Service = string(in.String())
116
                case "user":
117
                        out.User = string(in.String())
118
                case "host":
119
                        out.Host = string(in.String())
120
                case "hash":
121
                        if in.IsNull() {
122
                                in.Skip()
123
                                out.Hash = nil
124
                        } else {
125
                                in.Delim('[')
126
                                if out.Hash == nil {
127
                                        if !in.IsDelim(']') {
128
                                                out.Hash = make([]string, 0, 4)
129
                                        } else {
130
                                                out.Hash = []string{}
131
                                        }
132
                                } else {
133
                                        out.Hash = (out.Hash)[:0]
134
                                }
135
                                for !in.IsDelim(']') {
136
                                        var v1 string
137
                                        v1 = string(in.String())
138
                                        out.Hash = append(out.Hash, v1)
139
                                        in.WantComma()
140
                                }
141
                                in.Delim(']')
142
                        }
143
                case "timestamp":
144
                        if in.IsNull() {
145
                                in.Skip()
146
                                out.Timestamp = nil
147
                        } else {
148
                                if out.Timestamp == nil {
149
                                        out.Timestamp = new(TimestampMS)
150
                                }
151
                                *out.Timestamp = TimestampMS(in.Int64())
152
                        }
153
                case "timeout":
154
                        if in.IsNull() {
155
                                in.Skip()
156
                                out.Timeout = nil
157
                        } else {
158
                                if out.Timeout == nil {
159
                                        out.Timeout = new(TimeoutMS)
160
                                }
161
                                *out.Timeout = TimeoutMS(in.Int64())
162
                        }
163
                case "sign":
164
                        out.Sign = string(in.String())
165
                default:
166
                        in.SkipRecursive()
167
                }
168
                in.WantComma()
169
        }
170
        in.Delim('}')
171
        if isTopLevel {
172
                in.Consumed()
173
        }
174
}
func Record.UnmarshalMsg
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/record_msgp.go:

27
func (z *Record) UnmarshalMsg(bts []byte) (o []byte, err error) {
28
        var field []byte
29
        _ = field
30
        var zb0001 uint32
31
        zb0001, bts, err = msgp.ReadMapHeaderBytes(bts)
32
        if err != nil {
33
                err = msgp.WrapError(err)
34
                return
35
        }
36
        for zb0001 > 0 {
37
                zb0001--
38
                field, bts, err = msgp.ReadMapKeyZC(bts)
39
                if err != nil {
40
                        err = msgp.WrapError(err)
41
                        return
42
                }
43
                switch msgp.UnsafeString(field) {
44
                case "e":
45
                        z.LockExpireAt, bts, err = msgp.ReadInt64Bytes(bts)
46
                        if err != nil {
47
                                err = msgp.WrapError(err, "LockExpireAt")
48
                                return
49
                        }
50
                case "a":
51
                        var zb0002 uint32
52
                        zb0002, bts, err = msgp.ReadMapHeaderBytes(bts)
53
                        if err != nil {
54
                                err = msgp.WrapError(err, "Attempts")
55
                                return
56
                        }
57
                        if z.Attempts == nil {
58
                                z.Attempts = make(map[string]int64, zb0002)
59
                        } else if len(z.Attempts) > 0 {
60
                                for key := range z.Attempts {
61
                                        delete(z.Attempts, key)
62
                                }
63
                        }
64
                        for zb0002 > 0 {
65
                                var za0001 string
66
                                var za0002 int64
67
                                zb0002--
68
                                za0001, bts, err = msgp.ReadStringBytes(bts)
69
                                if err != nil {
70
                                        err = msgp.WrapError(err, "Attempts")
71
                                        return
72
                                }
73
                                za0002, bts, err = msgp.ReadInt64Bytes(bts)
74
                                if err != nil {
75
                                        err = msgp.WrapError(err, "Attempts", za0001)
76
                                        return
77
                                }
78
                                z.Attempts[za0001] = za0002
79
                        }
80
                default:
81
                        bts, err = msgp.Skip(bts)
82
                        if err != nil {
83
                                err = msgp.WrapError(err)
84
                                return
85
                        }
86
                }
87
        }
88
        o = bts
89
        return
90
}
func Agent.ProcessModuleConn
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/module.go:

15
func (p *Agent) ProcessModuleConn(c net.Conn) {
16
        b := make([]byte, 2048)
17
        for {
18
                n, err := c.Read(b)
19
                if err != nil {
20
                        if shouldLogError(err) {
21
                                log.WithError(err).Errorf("read: %v", err)
22
                        }
23
                        break
24
                }
25
26
                var processName, processPath string
27
                requestId := p.RequestId()
28
                proc, procErr := ConnProcess(c)
29
                if procErr != nil {
30
                        processName = fmt.Sprintf("%v", procErr)
31
                        processPath = fmt.Sprintf("ConnProcessError: %v", err)
32
                } else {
33
                        processName, procErr = proc.Name()
34
                        if procErr != nil {
35
                                processName = fmt.Sprintf("ProcessNameError: %v", err)
36
                        }
37
38
                        processPath, procErr = proc.Exe()
39
                        if procErr != nil {
40
                                processPath = fmt.Sprintf("ProcessPathError: %v", procErr)
41
                        }
42
                }
43
                log.WithField("process_name", processName).Debugf("--[svc:%d]->> %v", requestId, string(b[:n]))
44
45
                var r Request
46
                err = r.UnmarshalJSON(b[:n])
47
                if err != nil {
48
                        log.WithFields(log.Fields{
49
                                log.ErrorKey: err,
50
                                "data":       string(b[:n]),
51
                                "len":        n,
52
                        }).Errorf("parse request: %v", err)
53
                        break
54
                }
55
56
                if !r.CheckSign(Secret, p.cfg.SharedKey) {
57
                        log.WithFields(log.Fields{
58
                                "data":         string(b[:n]),
59
                                "request":      r,
60
                                "process_name": processName,
61
                                "process_path": processPath,
62
                        }).Errorf("Incorrect signature")
63
                        break
64
                }
65
66
                resp := p.ProcessModuleRequest(r, processName)
67
                if resp == nil {
68
                        break
69
                }
70
71
                log.WithField("process_name", processName).Debugf("<-[svc:%d]--- %v", requestId, string(resp))
72
                _, err = c.Write(resp)
73
                if err != nil {
74
                        var processIsRunning bool
75
                        if proc != nil {
76
                                processIsRunning, _ = proc.IsRunning()
77
                        }
78
                        fields := log.Fields{
79
                                log.ErrorKey:    err,
80
                                "overdue_by":    r.GetOverdueBy().Milliseconds(),
81
                                "process_name":  processName,
82
                                "process_path":  processPath,
83
                                "process_exist": processIsRunning,
84
                        }
85
86
                        if errors.Is(err, syscall.EPIPE) {
87
                                log.WithFields(fields).Debugf("connection serve: %v", err)
88
                        } else {
89
                                log.WithFields(fields).Errorf("connection serve: %v", err)
90
                        }
91
                        break
92
                }
93
        }
94
}
func FailureWatchdogRecord.DecodeMsg
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog_record_gen.go:

10
func (z *FailureWatchdogRecord) DecodeMsg(dc *msgp.Reader) (err error) {
11
        var field []byte
12
        _ = field
13
        var zb0001 uint32
14
        zb0001, err = dc.ReadMapHeader()
15
        if err != nil {
16
                err = msgp.WrapError(err)
17
                return
18
        }
19
        for zb0001 > 0 {
20
                zb0001--
21
                field, err = dc.ReadMapKeyPtr()
22
                if err != nil {
23
                        err = msgp.WrapError(err)
24
                        return
25
                }
26
                switch msgp.UnsafeString(field) {
27
                case "timestamps":
28
                        var zb0002 uint32
29
                        zb0002, err = dc.ReadArrayHeader()
30
                        if err != nil {
31
                                err = msgp.WrapError(err, "Timestamps")
32
                                return
33
                        }
34
                        if cap(z.Timestamps) >= int(zb0002) {
35
                                z.Timestamps = (z.Timestamps)[:zb0002]
36
                        } else {
37
                                z.Timestamps = make([]int64, zb0002)
38
                        }
39
                        for za0001 := range z.Timestamps {
40
                                z.Timestamps[za0001], err = dc.ReadInt64()
41
                                if err != nil {
42
                                        err = msgp.WrapError(err, "Timestamps", za0001)
43
                                        return
44
                                }
45
                        }
46
                default:
47
                        err = dc.Skip()
48
                        if err != nil {
49
                                err = msgp.WrapError(err)
50
                                return
51
                        }
52
                }
53
        }
54
        return
55
}
func FailureWatchdog.CapturePanic
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog.go:

103
func (w *FailureWatchdog) CapturePanic() {
104
        r := recover()
105
        if r == nil || !w.Enabled {
106
                return
107
        }
108
109
        log.Debugf("Failure: %v", r)
110
        w.RecordFailure(time.Now())
111
112
        // Propagate panic
113
        panic(r)
114
}
func @91:9
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog.go:

91
func() {
92
                        if err := w.cb(); err != nil {
93
                                log.WithError(err).Errorf("failed to execute callback: %v", err)
94
                        }
95
                }
func ReverseIP
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/rbl.go:

48
func ReverseIP(ip net.IP) string {
49
        if ip.To4() != nil {
50
                splitAddress := strings.Split(ip.String(), ".")
51
52
                for i, j := 0, len(splitAddress)-1; i < len(splitAddress)/2; i, j = i+1, j-1 {
53
                        splitAddress[i], splitAddress[j] = splitAddress[j], splitAddress[i]
54
                }
55
56
                return strings.Join(splitAddress, ".")
57
        } else if ip.To16() != nil {
58
                ipv6 := ip.To16()
59
                hexDigit := "0123456789abcdef"
60
61
                s := make([]string, len(ipv6)*2)
62
                for i := 0; i < net.IPv6len; i += 1 {
63
                        s[i*2], s[i*2+1] = string(hexDigit[ipv6[i]>>4]), string(hexDigit[ipv6[i]&0xf])
64
                }
65
                for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
66
                        s[i], s[j] = s[j], s[i]
67
                }
68
                return strings.Join(s, ".")
69
        }
70
        return ""
71
}
func FailureWatchdogRecord.EncodeMsg
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog_record_gen.go:

58
func (z *FailureWatchdogRecord) EncodeMsg(en *msgp.Writer) (err error) {
59
        // map header, size 1
60
        // write "timestamps"
61
        err = en.Append(0x81, 0xaa, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x73)
62
        if err != nil {
63
                return
64
        }
65
        err = en.WriteArrayHeader(uint32(len(z.Timestamps)))
66
        if err != nil {
67
                err = msgp.WrapError(err, "Timestamps")
68
                return
69
        }
70
        for za0001 := range z.Timestamps {
71
                err = en.WriteInt64(z.Timestamps[za0001])
72
                if err != nil {
73
                        err = msgp.WrapError(err, "Timestamps", za0001)
74
                        return
75
                }
76
        }
77
        return
78
}
func loadKeyFile
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

192
func loadKeyFile(filename, defaultKey string) string {
193
        b, err := os.ReadFile(filename)
194
        if err != nil {
195
                log.WithFields(log.Fields{
196
                        log.ErrorKey: err,
197
                        "filename":   filename,
198
                }).Warnf("Key file %s read error (default value used): %v", filename, err)
199
                return defaultKey
200
        }
201
202
        b = bytes.TrimSpace(b)
203
        if len(b) == 0 {
204
                log.WithFields(log.Fields{
205
                        log.ErrorKey: err,
206
                        "filename":   filename,
207
                }).Warnf("Key file %s read error (default value used): empty", filename)
208
                return defaultKey
209
        }
210
211
        return string(b)
212
}
func getServerId
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/sentry.go:

64
func getServerId() (id string, err error) {
65
        var f *os.File
66
        f, err = os.Open("/var/imunify360/license.json")
67
        if err != nil {
68
                return
69
        }
70
        defer f.Close()
71
72
        data, _ := ioutil.ReadAll(f)
73
74
        var license Im360License
75
        json.Unmarshal(data, &license)
76
77
        id = license.Id
78
        return
79
}
func @182:18
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

182
func(l License, valid bool) {
183
                        if valid {
184
                                // Leave a chance to flip sentry reporting back.
185
                                sentryLoggerHook.SetEnabled(p.cfg.IsSentryEnabled())
186
                        } else {
187
                                if l.err != nil {
188
                                        sentryLoggerHook.SetEnabled(false)
189
                                        if p.cfg.IsSentryEnabled() {
190
                                                log.WithFields(log.Fields{
191
                                                        log.ErrorKey:       l.err,
192
                                                        "agent_lic_status": GetAgentLicStatus(),
193
                                                }).Errorf("sentry error reporting is disabled (because of INVALID license error)")
194
                                        }
195
                                }
196
                        }
197
                }
func ToIP
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/agent.go:

498
func ToIP(host string) string {
499
        if host == "" || net.ParseIP(host) != nil {
500
                return host
501
        }
502
503
        ips, err := net.LookupIP(host)
504
        if err != nil || len(ips) == 0 {
505
                return ""
506
        }
507
508
        return ips[0].String()
509
}
func ModifyDovecotSocket
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/socket.go:

14
func ModifyDovecotSocket(path string) error {
15
        grp, err := user.LookupGroup("dovecot")
16
        if err != nil {
17
                return nil
18
        }
19
20
        gid, err := strconv.Atoi(grp.Gid)
21
        if err != nil {
22
                return fmt.Errorf("failed to get 'dovecot' group id sock '%s': %w", path, err)
23
        }
24
25
        err = os.Chown(path, -1, gid)
26
        if err != nil {
27
                return fmt.Errorf("failed to set 'dovecot' group for sock '%s': %w", path, err)
28
        }
29
30
        info, err := os.Stat(path)
31
        if err != nil {
32
                return fmt.Errorf("failed to get file info for sock '%s': %w", path, err)
33
        }
34
35
        err = os.Chmod(path, info.Mode().Perm()|0060)
36
        if err != nil {
37
                return fmt.Errorf("failed to set group perms for sock '%s': %w", path, err)
38
        }
39
40
        return nil
41
}
func main
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/main.go:

20
func main() {
21
        defer failureWatchdog.CapturePanic()
22
23
        var (
24
                done    bool
25
                cfgPath string
26
        )
27
28
        flag.StringVar(&cfgPath, "f", DefaultIniPath, "ini file path")
29
        flag.Parse()
30
31
        sigs := make(chan os.Signal, 1)
32
        signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
33
34
        for !done {
35
                cfg, err := ConfigLoad(cfgPath)
36
                if err != nil {
37
                        failureWatchdog.RecordFailure(time.Now())
38
                        log.WithError(err).Fatalf("start: %v", err)
39
                }
40
41
                failureWatchdog.Limit = cfg.FailureWatchdogLimit
42
                failureWatchdog.Period = time.Second * time.Duration(cfg.FailureWatchdogPeriod)
43
                failureWatchdog.Enabled = cfg.FailureWatchdogEnabled
44
45
                p := new(Agent)
46
47
                err = p.Start(cfg)
48
                if err != nil {
49
                        failureWatchdog.RecordFailure(time.Now())
50
                        log.WithError(err).Fatalf("start: %v", err)
51
                }
52
53
                // Listen for idle alerts from ConnTracker
54
                idleDone := make(chan struct{})
55
                if p.Tracker != nil {
56
                        idleDone = p.Tracker.Done
57
                }
58
59
                log.Debug("Starting imunify360-pam")
60
                select {
61
                case sig := <-sigs:
62
                        if sig == syscall.SIGINT || sig == syscall.SIGTERM {
63
                                log.Debugf("Stopping imunify360-pam due to signal %v", sig)
64
                                done = true
65
                        }
66
                        if sig == syscall.SIGHUP {
67
                                log.Debug("Received SIGHUP, rereading config file")
68
                        }
69
                case <-idleDone:
70
                        log.Debug("Stopping imunify360-pam due to idleness")
71
                        done = true
72
                }
73
74
                if err := p.Stop(); err != nil {
75
                        failureWatchdog.RecordFailure(time.Now())
76
                        log.WithError(err).Fatalf("stop: %v", err)
77
                }
78
79
                p = nil
80
                runtime.GC()
81
        }
82
}
func Request.GetOverdueBy
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request.go:

43
func (r Request) GetOverdueBy() time.Duration {
44
        if r.Timestamp == nil || r.Timeout == nil {
45
                return 0
46
        }
47
        now := time.Now()
48
        timeout := r.Timestamp.Time().Add(r.Timeout.Duration())
49
        if now.After(timeout) {
50
                return now.Sub(timeout)
51
        }
52
        return 0
53
}
func rateSample.sample
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/sentry.go:

99
func (s rateSample) sample() bool {
100
        if s < 0 || s > 1.0 {
101
                return false
102
        }
103
        if rand.Float64() < float64(s) {
104
                return true
105
        }
106
        return false
107
}
func disableFtpIntegration
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/watchdog.go:

53
func disableFtpIntegration() error {
54
        log.Debugf("Disabling ftp integration")
55
56
        ctx, cancel := context.WithTimeout(context.Background(), agentBinTimeout)
57
        defer cancel()
58
59
        cmd := exec.CommandContext(ctx, "/usr/bin/imunify360-agent", "config", "update", "{\"PAM\": {\"ftp_protection\": false}}")
60
        return cmd.Run()
61
}
func DatabaseDrop
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/database.go:

59
func DatabaseDrop(cfg *Config) error {
60
        path := filepath.Join(cfg.Database, "/leveldb")
61
62
        err := os.RemoveAll(path)
63
        if err != nil {
64
                return fmt.Errorf("rm -rf %s: %v", path, err)
65
        }
66
67
        return nil
68
}
func serviceCmd
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/service.go:

27
func serviceCmd(name, action string) error {
28
        var cmd *exec.Cmd
29
        if systemd() {
30
                cmd = exec.Command(systemctlPath, action, name)
31
        } else {
32
                cmd = exec.Command("service", name, action)
33
        }
34
        return cmd.Run()
35
}
func errHasSuffixRateLimit.IsLimited
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/sentry.go:

109
func (e *errHasSuffixRateLimit) IsLimited(err error) bool {
110
        if strings.HasSuffix(err.Error(), e.err.Error()) {
111
                if e.rs.sample() {
112
                        return true
113
                }
114
        }
115
        return false
116
}
func systemd
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/service.go:

22
func systemd() bool {
23
        _, err := os.Stat(systemctlPath)
24
        return err == nil
25
}
func TimeoutMS.Duration
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request.go:

39
func (ts TimeoutMS) Duration() time.Duration {
40
        return time.Duration(int64(ts) * (1000 * 1000))
41
}
func loadLockConfig
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/config.go:

214
func loadLockConfig(s *ini.Section, defaultWhitelist string) LockConfig {
215
        return LockConfig{
216
                Timeout:           rangeInt64(s.Key("timeout"), 300, 0, 9999999),
217
                Attempts:          rangeInt(s.Key("attempts"), 10, 0, 100),
218
                Period:            rangeInt64(s.Key("period"), 300, 0, 9999999),
219
                WhitelistFileName: s.Key("whitelist").MustString(defaultWhitelist),
220
        }
221
}
func Response.MarshalEasyJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

78
func (v Response) MarshalEasyJSON(w *jwriter.Writer) {
79
        easyjson3c9d2b01EncodeGithubComUserHello(w, v)
80
}
func TimestampMS.Time
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request.go:

33
func (ts TimestampMS) Time() time.Time {
34
        return time.Unix(int64(ts)/1000, (int64(ts)%1000)*(1000*1000))
35
}
func SendMessagesApiRequest.MarshalEasyJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

253
func (v SendMessagesApiRequest) MarshalEasyJSON(w *jwriter.Writer) {
254
        easyjsonD587a15Encode11(w, v)
255
}
func Response.UnmarshalEasyJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

90
func (v *Response) UnmarshalEasyJSON(l *jlexer.Lexer) {
91
        easyjson3c9d2b01DecodeGithubComUserHello(l, v)
92
}
func ServiceStart
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/service.go:

37
func ServiceStart(name string) error {
38
        return serviceCmd(name, "start")
39
}
func SendMessagesApiRequest.UnmarshalEasyJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/api_proto_easyjson.go:

265
func (v *SendMessagesApiRequest) UnmarshalEasyJSON(l *jlexer.Lexer) {
266
        easyjsonD587a15Decode11(l, v)
267
}
func ServiceStop
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/service.go:

41
func ServiceStop(name string) error {
42
        return serviceCmd(name, "stop")
43
}
func ServiceRestart
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/service.go:

45
func ServiceRestart(name string) error {
46
        return serviceCmd(name, "restart")
47
}
func Request.MarshalEasyJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

249
func (v Request) MarshalEasyJSON(w *jwriter.Writer) {
250
        easyjson3c9d2b01EncodeGithubComUserHello1(w, v)
251
}
func License.UnmarshalEasyJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license_proto_easyjson.go:

178
func (v *License) UnmarshalEasyJSON(l *jlexer.Lexer) {
179
        easyjson2c6259e0Decode1(l, v)
180
}
func License.MarshalEasyJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license_proto_easyjson.go:

166
func (v License) MarshalEasyJSON(w *jwriter.Writer) {
167
        easyjson2c6259e0Encode1(w, v)
168
}
func Request.UnmarshalEasyJSON
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/request_easyjson.go:

261
func (v *Request) UnmarshalEasyJSON(l *jlexer.Lexer) {
262
        easyjson3c9d2b01DecodeGithubComUserHello1(l, v)
263
}
func @137:32
Back

In /builddir/build/BUILD/imunify360-pam-6.4.15/src/agent/license.go:

137
func() {}
agent
75.10%