From 916468d7aa0da6cacd978beb905a9a39df9c2916 Mon Sep 17 00:00:00 2001 From: zhyale Date: Thu, 22 Apr 2021 22:08:36 +0800 Subject: [PATCH] add operation log --- backend/application.go | 6 ++-- backend/init.go | 16 ++++----- backend/vip_app.go | 2 +- backend/vip_target.go | 4 +-- data/backend_application.go | 8 ++--- data/backend_appuser.go | 14 ++++---- data/backend_certificate.go | 10 +++--- data/backend_destination.go | 17 ++++------ data/backend_domain.go | 10 +++--- data/backend_node.go | 6 ++-- data/backend_setting.go | 13 +++---- data/data.go | 5 +-- data/data_config.go | 2 +- data/db_crypt.go | 8 ++--- data/firewall_cc.go | 18 ++++------ data/firewall_group_policy.go | 9 ++--- data/firewall_vuln.go | 5 +-- data/setting.go | 64 +++++++++++++++++++---------------- firewall/cc.go | 36 +++++++++++--------- firewall/check_item.go | 2 +- firewall/firewall.go | 62 ++++++++++++++++----------------- firewall/group_policy.go | 34 +++++++++++-------- firewall/init.go | 2 +- firewall/ip_policy.go | 16 +++++---- firewall/nftables.go | 6 ++-- firewall/vuln.go | 2 +- gateway/api.go | 30 ++++++++-------- go.mod | 5 +-- go.sum | 4 +++ janusec.go | 4 +-- usermgmt/ldap.go | 5 ++- usermgmt/usermgmt.go | 17 ++++++---- 32 files changed, 224 insertions(+), 218 deletions(-) diff --git a/backend/application.go b/backend/application.go index 7be4576..7646b09 100644 --- a/backend/application.go +++ b/backend/application.go @@ -298,11 +298,11 @@ func UpdateDestinations(app *models.Application, destinations []interface{}) { // UpdateAppDomains ... func UpdateAppDomains(app *models.Application, appDomains []interface{}) { newAppDomains := []*models.Domain{} - newDomainNames := []string{} + //newDomainNames := []string{} for _, domainMap := range appDomains { domain := UpdateDomain(app, domainMap) newAppDomains = append(newAppDomains, domain) - newDomainNames = append(newDomainNames, domain.Name) + //newDomainNames = append(newDomainNames, domain.Name) } for _, oldDomain := range app.Domains { if !InterfaceContainsDomainID(appDomains, oldDomain.ID) { @@ -419,7 +419,7 @@ func DeleteApplicationByID(appID int64, clientIP string, authUser *models.AuthUs } DeleteDomainsByApp(app) DeleteDestinationsByApp(appID) - err = firewall.DeleteCCPolicyByAppID(appID, authUser, false) + err = firewall.DeleteCCPolicyByAppID(appID, clientIP, authUser, false) if err != nil { utils.DebugPrintln("DeleteApplicationByID DeleteCCPolicyByAppID", err) } diff --git a/backend/init.go b/backend/init.go index c60b17e..8555906 100644 --- a/backend/init.go +++ b/backend/init.go @@ -112,15 +112,15 @@ func InitDatabase() { } } // 0.9.13 alter column ccpolicies type - err = dal.ExecSQL(`ALTER TABLE "ccpolicies" ALTER COLUMN "interval_milliseconds" TYPE double precision`) - if err != nil { - //utils.DebugPrintln("InitDatabase ALTER TABLE ccpolicies ALTER COLUMN interval_milliseconds", err) - } + _ = dal.ExecSQL(`ALTER TABLE "ccpolicies" ALTER COLUMN "interval_milliseconds" TYPE double precision`) + //if err != nil { + //utils.DebugPrintln("InitDatabase ALTER TABLE ccpolicies ALTER COLUMN interval_milliseconds", err) + //} // 0.9.13 alter column block_seconds type - err = dal.ExecSQL(`ALTER TABLE "ccpolicies" ALTER COLUMN "block_seconds" TYPE double precision`) - if err != nil { - //utils.DebugPrintln("InitDatabase ALTER TABLE ccpolicies ALTER COLUMN block_seconds", err) - } + _ = dal.ExecSQL(`ALTER TABLE "ccpolicies" ALTER COLUMN "block_seconds" TYPE double precision`) + //if err != nil { + //utils.DebugPrintln("InitDatabase ALTER TABLE ccpolicies ALTER COLUMN block_seconds", err) + //} } // LoadAppConfiguration ... diff --git a/backend/vip_app.go b/backend/vip_app.go index 54bbbcc..18d5d38 100644 --- a/backend/vip_app.go +++ b/backend/vip_app.go @@ -112,7 +112,7 @@ func UDPForwarding(vipApp *models.VipApp, udpListenConn *net.UDPConn) { } if vipTarget != nil { vipTarget.CheckTime = time.Now().Unix() - targetAddr, err := net.ResolveUDPAddr("udp", vipTarget.Destination) + targetAddr, _ := net.ResolveUDPAddr("udp", vipTarget.Destination) udpTargetConn, err := net.DialUDP("udp", nil, targetAddr) if err != nil { utils.DebugPrintln("UDPForwarding DialUDP could not connect to target", vipTarget.Destination, err) diff --git a/backend/vip_target.go b/backend/vip_target.go index 8dae81a..1200e6e 100644 --- a/backend/vip_target.go +++ b/backend/vip_target.go @@ -27,7 +27,7 @@ func DeleteVipTargetsByAppID(id int64) { func CheckOfflineVipTargets(nowTimeStamp int64) { for _, vipApp := range VipApps { for _, target := range vipApp.Targets { - if target.Online == false { + if !target.Online { go func(vApp *models.VipApp, vTarget *models.VipTarget) { var conn net.Conn var err error @@ -39,7 +39,7 @@ func CheckOfflineVipTargets(nowTimeStamp int64) { vTarget.CheckTime = nowTimeStamp } } else { - targetAddr, err := net.ResolveUDPAddr("udp", vTarget.Destination) + targetAddr, _ := net.ResolveUDPAddr("udp", vTarget.Destination) udpTargetConn, err := net.DialUDP("udp", nil, targetAddr) if err != nil { vTarget.Online = false diff --git a/data/backend_application.go b/data/backend_application.go index 8b9e497..0afbc47 100644 --- a/data/backend_application.go +++ b/data/backend_application.go @@ -61,9 +61,9 @@ func (dal *MyDAL) InsertApplication(appName string, internalScheme string, redir // UpdateApplication update an Application func (dal *MyDAL) UpdateApplication(appName string, internalScheme string, redirectHTTPS bool, hstsEnabled bool, wafEnabled bool, ipMethod models.IPMethod, description string, oauthRequired bool, sessionSeconds int64, owner string, cspEnabled bool, csp string, appID int64) error { const sqlUpdateApplication = `UPDATE "applications" SET "name"=$1,"internal_scheme"=$2,"redirect_https"=$3,"hsts_enabled"=$4,"waf_enabled"=$5,"ip_method"=$6,"description"=$7,"oauth_required"=$8,"session_seconds"=$9,"owner"=$10,"csp_enabled"=$11,"csp"=$12 WHERE "id"=$13` - stmt, err := dal.db.Prepare(sqlUpdateApplication) + stmt, _ := dal.db.Prepare(sqlUpdateApplication) defer stmt.Close() - _, err = stmt.Exec(appName, internalScheme, redirectHTTPS, hstsEnabled, wafEnabled, ipMethod, description, oauthRequired, sessionSeconds, owner, cspEnabled, csp, appID) + _, err := stmt.Exec(appName, internalScheme, redirectHTTPS, hstsEnabled, wafEnabled, ipMethod, description, oauthRequired, sessionSeconds, owner, cspEnabled, csp, appID) utils.CheckError("UpdateApplication", err) return err } @@ -71,9 +71,9 @@ func (dal *MyDAL) UpdateApplication(appName string, internalScheme string, redir // DeleteApplication delete an Application func (dal *MyDAL) DeleteApplication(appID int64) error { const sqlDeleteApplication = `DELETE FROM "applications" WHERE "id"=$1` - stmt, err := dal.db.Prepare(sqlDeleteApplication) + stmt, _ := dal.db.Prepare(sqlDeleteApplication) defer stmt.Close() - _, err = stmt.Exec(appID) + _, err := stmt.Exec(appID) utils.CheckError("DeleteApplication", err) return err } diff --git a/data/backend_appuser.go b/data/backend_appuser.go index 71d24ba..53be624 100644 --- a/data/backend_appuser.go +++ b/data/backend_appuser.go @@ -93,7 +93,7 @@ func (dal *MyDAL) SelectAppUsers() []*models.QueryAppUser { var queryUsers = []*models.QueryAppUser{} for rows.Next() { queryUser := &models.QueryAppUser{} - err = rows.Scan(&queryUser.ID, &queryUser.Username, &queryUser.Email, &queryUser.IsSuperAdmin, &queryUser.IsCertAdmin, &queryUser.IsAppAdmin) + _ = rows.Scan(&queryUser.ID, &queryUser.Username, &queryUser.Email, &queryUser.IsSuperAdmin, &queryUser.IsCertAdmin, &queryUser.IsAppAdmin) queryUsers = append(queryUsers, queryUser) } return queryUsers @@ -111,27 +111,27 @@ func (dal *MyDAL) SelectAppUserByID(userID int64) *models.QueryAppUser { // UpdateAppUserWithPwd ... func (dal *MyDAL) UpdateAppUserWithPwd(username string, hashpwd string, salt string, email string, isSuperAdmin, isCertAdmin, isAppAdmin bool, needModifyPwd bool, userID int64) error { - stmt, err := dal.db.Prepare(sqlUpdateAppUserWithPwd) + stmt, _ := dal.db.Prepare(sqlUpdateAppUserWithPwd) defer stmt.Close() - _, err = stmt.Exec(username, hashpwd, salt, email, isSuperAdmin, isCertAdmin, isAppAdmin, needModifyPwd, userID) + _, err := stmt.Exec(username, hashpwd, salt, email, isSuperAdmin, isCertAdmin, isAppAdmin, needModifyPwd, userID) utils.CheckError("UpdateAppUserWithPwd", err) return err } // UpdateAppUserNoPwd ... func (dal *MyDAL) UpdateAppUserNoPwd(username string, email string, isSuperAdmin, isCertAdmin, isAppAdmin bool, userID int64) error { - stmt, err := dal.db.Prepare(sqlUpdateAppUserNoPwd) + stmt, _ := dal.db.Prepare(sqlUpdateAppUserNoPwd) defer stmt.Close() - _, err = stmt.Exec(username, email, isSuperAdmin, isCertAdmin, isAppAdmin, userID) + _, err := stmt.Exec(username, email, isSuperAdmin, isCertAdmin, isAppAdmin, userID) utils.CheckError("UpdateAppUserNoPwd", err) return err } // DeleteAppUser ... func (dal *MyDAL) DeleteAppUser(userID int64) error { - stmt, err := dal.db.Prepare(sqlDeleteAppUser) + stmt, _ := dal.db.Prepare(sqlDeleteAppUser) defer stmt.Close() - _, err = stmt.Exec(userID) + _, err := stmt.Exec(userID) utils.CheckError("DeleteAppUser", err) return err } diff --git a/data/backend_certificate.go b/data/backend_certificate.go index ca1a095..78e906f 100644 --- a/data/backend_certificate.go +++ b/data/backend_certificate.go @@ -37,7 +37,7 @@ func (dal *MyDAL) SelectCertificates() []*models.DBCertItem { var dbCerts = []*models.DBCertItem{} for rows.Next() { dbCert := &models.DBCertItem{} - err = rows.Scan(&dbCert.ID, &dbCert.CommonName, + _ = rows.Scan(&dbCert.ID, &dbCert.CommonName, &dbCert.CertContent, &dbCert.EncryptedPrivKey, &dbCert.ExpireTime, &dbCert.Description) dbCerts = append(dbCerts, dbCert) @@ -54,18 +54,18 @@ func (dal *MyDAL) InsertCertificate(commonName string, certContent string, encry // UpdateCertificate ... func (dal *MyDAL) UpdateCertificate(commonName string, certContent string, encryptedPrivKey []byte, expireTime int64, description string, id int64) error { - stmt, err := dal.db.Prepare(sqlUpdateCertificate) + stmt, _ := dal.db.Prepare(sqlUpdateCertificate) defer stmt.Close() - _, err = stmt.Exec(commonName, certContent, encryptedPrivKey, expireTime, description, id) + _, err := stmt.Exec(commonName, certContent, encryptedPrivKey, expireTime, description, id) utils.CheckError("UpdateCertificate", err) return err } // DeleteCertificate by id func (dal *MyDAL) DeleteCertificate(certID int64) error { - stmt, err := dal.db.Prepare(sqlDeleteCertificate) + stmt, _ := dal.db.Prepare(sqlDeleteCertificate) defer stmt.Close() - _, err = stmt.Exec(certID) + _, err := stmt.Exec(certID) utils.CheckError("DeleteCertificate", err) return err } diff --git a/data/backend_destination.go b/data/backend_destination.go index ed58f2f..a9e8e06 100644 --- a/data/backend_destination.go +++ b/data/backend_destination.go @@ -15,9 +15,9 @@ import ( // UpdateDestinationNode ... func (dal *MyDAL) UpdateDestinationNode(routeType int64, requestRoute string, backendRoute string, destination string, appID int64, nodeID int64, id int64) error { const sqlUpdateDestinationNode = `UPDATE "destinations" SET "route_type"=$1,"request_route"=$2,"backend_route"=$3,"destination"=$4,"app_id"=$5,"node_id"=$6 WHERE "id"=$7` - stmt, err := dal.db.Prepare(sqlUpdateDestinationNode) + stmt, _ := dal.db.Prepare(sqlUpdateDestinationNode) defer stmt.Close() - _, err = stmt.Exec(routeType, requestRoute, backendRoute, destination, appID, nodeID, id) + _, err := stmt.Exec(routeType, requestRoute, backendRoute, destination, appID, nodeID, id) utils.CheckError("UpdateDestinationNode", err) return err } @@ -28,10 +28,7 @@ func (dal *MyDAL) ExistsDestinationID(id int64) bool { const sqlExistsDestinationID = `SELECT COALESCE((SELECT 1 FROM "destinations" WHERE "id"=$1 limit 1),0)` err := dal.db.QueryRow(sqlExistsDestinationID, id).Scan(&exist) utils.CheckError("ExistsDestinationID", err) - if exist == 0 { - return false - } - return true + return exist != 0 } // CreateTableIfNotExistsDestinations ... @@ -73,9 +70,9 @@ func (dal *MyDAL) InsertDestination(routeType int64, requestRoute string, backen // DeleteDestinationByID ... func (dal *MyDAL) DeleteDestinationByID(id int64) error { const sqlDeleteDestinationByID = `DELETE FROM "destinations" WHERE "id"=$1` - stmt, err := dal.db.Prepare(sqlDeleteDestinationByID) + stmt, _ := dal.db.Prepare(sqlDeleteDestinationByID) defer stmt.Close() - _, err = stmt.Exec(id) + _, err := stmt.Exec(id) utils.CheckError("DeleteDestinationByID", err) return err } @@ -83,9 +80,9 @@ func (dal *MyDAL) DeleteDestinationByID(id int64) error { // DeleteDestinationsByAppID ... func (dal *MyDAL) DeleteDestinationsByAppID(appID int64) error { const sqlDeleteDestinationsByAppID = `DELETE FROM "destinations" WHERE "app_id"=$1` - stmt, err := dal.db.Prepare(sqlDeleteDestinationsByAppID) + stmt, _ := dal.db.Prepare(sqlDeleteDestinationsByAppID) defer stmt.Close() - _, err = stmt.Exec(appID) + _, err := stmt.Exec(appID) utils.CheckError("DeleteDestinationsByAppID", err) return err } diff --git a/data/backend_domain.go b/data/backend_domain.go index c8b5fce..e11a6a9 100644 --- a/data/backend_domain.go +++ b/data/backend_domain.go @@ -36,7 +36,7 @@ func (dal *MyDAL) SelectDomains() []*models.DBDomain { dbDomains := []*models.DBDomain{} for rows.Next() { dbDomain := &models.DBDomain{} - err = rows.Scan(&dbDomain.ID, &dbDomain.Name, &dbDomain.AppID, &dbDomain.CertID, &dbDomain.Redirect, &dbDomain.Location) + _ = rows.Scan(&dbDomain.ID, &dbDomain.Name, &dbDomain.AppID, &dbDomain.CertID, &dbDomain.Redirect, &dbDomain.Location) dbDomains = append(dbDomains, dbDomain) } return dbDomains @@ -66,18 +66,18 @@ func (dal *MyDAL) UpdateDomain(name string, appID int64, certID int64, redirect // DeleteDomainByDomainID ... func (dal *MyDAL) DeleteDomainByDomainID(domainID int64) error { - stmt, err := dal.db.Prepare(sqlDeleteDomainByDomainID) + stmt, _ := dal.db.Prepare(sqlDeleteDomainByDomainID) defer stmt.Close() - _, err = stmt.Exec(domainID) + _, err := stmt.Exec(domainID) utils.CheckError("DeleteDomainByDomainID", err) return err } // DeleteDomainByAppID ... func (dal *MyDAL) DeleteDomainByAppID(appID int64) error { - stmt, err := dal.db.Prepare(sqlDeleteDomainByAppID) + stmt, _ := dal.db.Prepare(sqlDeleteDomainByAppID) defer stmt.Close() - _, err = stmt.Exec(appID) + _, err := stmt.Exec(appID) utils.CheckError("DeleteDomainByAppID", err) return err } diff --git a/data/backend_node.go b/data/backend_node.go index f7254dd..93ad44a 100644 --- a/data/backend_node.go +++ b/data/backend_node.go @@ -34,7 +34,7 @@ func (dal *MyDAL) SelectAllNodes() []*models.DBNode { dbNodes := []*models.DBNode{} for rows.Next() { dbNode := &models.DBNode{} - err = rows.Scan(&dbNode.ID, &dbNode.Version, &dbNode.LastIP, &dbNode.LastRequestTime) + _ = rows.Scan(&dbNode.ID, &dbNode.Version, &dbNode.LastIP, &dbNode.LastRequestTime) dbNodes = append(dbNodes, dbNode) } return dbNodes @@ -55,9 +55,9 @@ func (dal *MyDAL) InsertNode(version string, lastIP string, lastReqTime int64) ( // UpdateNodeLastInfo ... func (dal *MyDAL) UpdateNodeLastInfo(version string, lastIP string, lastReqTime int64, id int64) error { - stmt, err := dal.db.Prepare(sqlUpdateNodeLastInfo) + stmt, _ := dal.db.Prepare(sqlUpdateNodeLastInfo) defer stmt.Close() - _, err = stmt.Exec(version, lastIP, lastReqTime, id) + _, err := stmt.Exec(version, lastIP, lastReqTime, id) utils.CheckError("UpdateNodeLastInfo", err) return err } diff --git a/data/backend_setting.go b/data/backend_setting.go index 6daeb21..85b064f 100644 --- a/data/backend_setting.go +++ b/data/backend_setting.go @@ -34,10 +34,7 @@ func (dal *MyDAL) ExistsSetting(name string) bool { var exist int err := dal.db.QueryRow(sqlExistsSetting, name).Scan(&exist) utils.CheckError("ExistsSetting", err) - if exist == 0 { - return false - } - return true + return exist != 0 } // SelectBoolSetting ... @@ -66,7 +63,7 @@ func (dal *MyDAL) SelectStringSetting(name string) (value string, err error) { // SaveBoolSetting ... func (dal *MyDAL) SaveBoolSetting(name string, value bool) (err error) { - if dal.ExistsSetting(name) == true { + if dal.ExistsSetting(name) { _, err = dal.db.Exec(sqlUpdateBoolSetting, value, name) } else { _, err = dal.db.Exec(sqlInsertBoolSetting, name, value) @@ -76,7 +73,7 @@ func (dal *MyDAL) SaveBoolSetting(name string, value bool) (err error) { // SaveIntSetting ... func (dal *MyDAL) SaveIntSetting(name string, value int64) (err error) { - if dal.ExistsSetting(name) == true { + if dal.ExistsSetting(name) { _, err = dal.db.Exec(sqlUpdateIntSetting, value, name) } else { _, err = dal.db.Exec(sqlInsertIntSetting, name, value) @@ -87,7 +84,7 @@ func (dal *MyDAL) SaveIntSetting(name string, value int64) (err error) { // SaveFloatSetting ... func (dal *MyDAL) SaveFloatSetting(name string, value float64) (err error) { - if dal.ExistsSetting(name) == true { + if dal.ExistsSetting(name) { _, err = dal.db.Exec(sqlUpdateFloatSetting, value, name) } else { _, err = dal.db.Exec(sqlInsertFloatSetting, name, value) @@ -97,7 +94,7 @@ func (dal *MyDAL) SaveFloatSetting(name string, value float64) (err error) { // SaveStringSetting ... func (dal *MyDAL) SaveStringSetting(name string, value string) (err error) { - if dal.ExistsSetting(name) == true { + if dal.ExistsSetting(name) { _, err = dal.db.Exec(sqlUpdateStringSetting, value, name) } else { _, err = dal.db.Exec(sqlInsertStringSetting, name, value) diff --git a/data/data.go b/data/data.go index eb645c7..8099b1a 100644 --- a/data/data.go +++ b/data/data.go @@ -93,8 +93,5 @@ func (dal *MyDAL) ExistColumnInTable(tableName string, columnName string) bool { const sql = `select count(1) from information_schema.columns where table_name=$1 and column_name=$2` err := dal.db.QueryRow(sql, tableName, columnName).Scan(&count) utils.CheckError("ExistColumnInTable QueryRow", err) - if count > 0 { - return true - } - return false + return count > 0 } diff --git a/data/data_config.go b/data/data_config.go index 3b613f8..12b9f66 100644 --- a/data/data_config.go +++ b/data/data_config.go @@ -38,7 +38,7 @@ func NewConfig(filename string) (*models.Config, error) { encryptedConfig := models.EncryptedConfig(*config) encryptedConfig.PrimaryNode.Database.Password = encryptedPassword encryptedConfigBytes, _ := json.MarshalIndent(encryptedConfig, "", "\t") - err = ioutil.WriteFile(filename, encryptedConfigBytes, 0600) + _ = ioutil.WriteFile(filename, encryptedConfigBytes, 0600) } else { // Decrypt password encryptedPassword, err := hex.DecodeString(dbPassword) diff --git a/data/db_crypt.go b/data/db_crypt.go index 20e0ae0..51105de 100644 --- a/data/db_crypt.go +++ b/data/db_crypt.go @@ -32,7 +32,7 @@ var ( // LoadInstanceKey ... func (dal *MyDAL) LoadInstanceKey() { - if dal.ExistsSetting("instance_key") == false { + if !dal.ExistsSetting("instance_key") { instanceKey = GenRandomAES256Key() encryptedInstanceKey := AES256Encrypt(instanceKey, true) hexInstanceKey := hex.EncodeToString(encryptedInstanceKey) @@ -51,7 +51,7 @@ func (dal *MyDAL) LoadInstanceKey() { // LoadNodesKey ... func (dal *MyDAL) LoadNodesKey() { - if dal.ExistsSetting("nodes_key") == false { + if !dal.ExistsSetting("nodes_key") { NodesKey = GenRandomAES256Key() encryptedNodesKey := AES256Encrypt(NodesKey, true) HexEncryptedNodesKey = hex.EncodeToString(encryptedNodesKey) @@ -100,7 +100,7 @@ func EncryptWithKey(plaintext []byte, key []byte) []byte { // AES256Encrypt ... func AES256Encrypt(plaintext []byte, useRootkey bool) []byte { key := instanceKey - if useRootkey == true { + if useRootkey { key = RootKey } ciphertext := EncryptWithKey(plaintext, key) @@ -133,7 +133,7 @@ func DecryptWithKey(ciphertext []byte, key []byte) ([]byte, error) { // AES256Decrypt ... func AES256Decrypt(ciphertext []byte, useRootkey bool) ([]byte, error) { key := instanceKey - if useRootkey == true { + if useRootkey { key = RootKey } plaintext, err := DecryptWithKey(ciphertext, key) diff --git a/data/firewall_cc.go b/data/firewall_cc.go index 678985c..a7458e1 100644 --- a/data/firewall_cc.go +++ b/data/firewall_cc.go @@ -30,9 +30,9 @@ func (dal *MyDAL) CreateTableIfNotExistsCCPolicy() error { // DeleteCCPolicy ... func (dal *MyDAL) DeleteCCPolicy(appID int64) error { - stmt, err := dal.db.Prepare(sqlDeleteCCPolicy) + stmt, _ := dal.db.Prepare(sqlDeleteCCPolicy) defer stmt.Close() - _, err = stmt.Exec(appID) + _, err := stmt.Exec(appID) utils.CheckError("DeleteCCPolicy", err) return err } @@ -40,9 +40,9 @@ func (dal *MyDAL) DeleteCCPolicy(appID int64) error { // UpdateCCPolicy ... func (dal *MyDAL) UpdateCCPolicy(IntervalMilliSeconds float64, maxCount int64, blockSeconds float64, action models.PolicyAction, statByURL bool, statByUA bool, statByCookie bool, isEnabled bool, appID int64) error { - stmt, err := dal.db.Prepare(sqlUpdateCCPolicy) + stmt, _ := dal.db.Prepare(sqlUpdateCCPolicy) defer stmt.Close() - _, err = stmt.Exec(IntervalMilliSeconds, maxCount, blockSeconds, action, + _, err := stmt.Exec(IntervalMilliSeconds, maxCount, blockSeconds, action, statByURL, statByUA, statByCookie, isEnabled, appID) utils.CheckError("UpdateCCPolicy", err) return err @@ -53,10 +53,7 @@ func (dal *MyDAL) ExistsCCPolicy() bool { var existCCPolicy int err := dal.db.QueryRow(sqlExistsCCPolicy).Scan(&existCCPolicy) utils.CheckError("ExistsCCPolicy", err) - if existCCPolicy == 0 { - return false - } - return true + return existCCPolicy != 0 } // ExistsCCPolicyByAppID ... @@ -64,10 +61,7 @@ func (dal *MyDAL) ExistsCCPolicyByAppID(appID int64) bool { var existCCPolicy int err := dal.db.QueryRow(sqlExistsCCPolicyByAppID, appID).Scan(&existCCPolicy) utils.CheckError("ExistsCCPolicyByAppID", err) - if existCCPolicy == 0 { - return false - } - return true + return existCCPolicy != 0 } // InsertCCPolicy ... diff --git a/data/firewall_group_policy.go b/data/firewall_group_policy.go index 236e5d0..2101e4e 100644 --- a/data/firewall_group_policy.go +++ b/data/firewall_group_policy.go @@ -38,9 +38,9 @@ func (dal *MyDAL) DeleteGroupPolicyByID(id int64) error { // UpdateGroupPolicy ... func (dal *MyDAL) UpdateGroupPolicy(description string, appID int64, vulnID int64, hitValue int64, action models.PolicyAction, isEnabled bool, userID int64, updateTime int64, id int64) error { - stmt, err := dal.db.Prepare(sqlUpdateGroupPolicy) + stmt, _ := dal.db.Prepare(sqlUpdateGroupPolicy) defer stmt.Close() - _, err = stmt.Exec(description, appID, vulnID, hitValue, action, isEnabled, userID, updateTime, id) + _, err := stmt.Exec(description, appID, vulnID, hitValue, action, isEnabled, userID, updateTime, id) utils.CheckError("UpdateGroupPolicy", err) return err } @@ -96,8 +96,5 @@ func (dal *MyDAL) ExistsGroupPolicy() bool { var exist int err := dal.db.QueryRow(sqlExistsGroupPolicy).Scan(&exist) utils.CheckError("ExistsGroupPolicy", err) - if exist == 0 { - return false - } - return true + return exist != 0 } diff --git a/data/firewall_vuln.go b/data/firewall_vuln.go index a496f7a..4c79a8d 100644 --- a/data/firewall_vuln.go +++ b/data/firewall_vuln.go @@ -30,10 +30,7 @@ func (dal *MyDAL) ExistsVulnType() bool { var exist int err := dal.db.QueryRow(sqlExistsVulnType).Scan(&exist) utils.CheckError("ExistsVulnType", err) - if exist == 0 { - return false - } - return true + return exist != 0 } // SelectVulnTypes ... diff --git a/data/setting.go b/data/setting.go index b24252b..d6c247e 100644 --- a/data/setting.go +++ b/data/setting.go @@ -95,25 +95,25 @@ func InitDefaultSettings() { DAL.LoadInstanceKey() DAL.LoadNodesKey() var err error - if DAL.ExistsSetting("backend_last_modified") == false { + if !DAL.ExistsSetting("backend_last_modified") { err = DAL.SaveIntSetting("backend_last_modified", 0) } - if DAL.ExistsSetting("firewall_last_modified") == false { + if !DAL.ExistsSetting("firewall_last_modified") { err = DAL.SaveIntSetting("firewall_last_modified", 0) } - if DAL.ExistsSetting("sync_seconds") == false { + if !DAL.ExistsSetting("sync_seconds") { err = DAL.SaveIntSetting("sync_seconds", 600) } - if DAL.ExistsSetting("waf_log_days") == false { + if !DAL.ExistsSetting("waf_log_days") { err = DAL.SaveIntSetting("waf_log_days", 7) } - if DAL.ExistsSetting("cc_log_days") == false { + if !DAL.ExistsSetting("cc_log_days") { err = DAL.SaveIntSetting("cc_log_days", 7) } - if DAL.ExistsSetting("access_log_days") == false { + if !DAL.ExistsSetting("access_log_days") { err = DAL.SaveIntSetting("access_log_days", 180) } - if DAL.ExistsSetting("init_time") == false { + if !DAL.ExistsSetting("init_time") { // 0.9.13 + err = DAL.SaveIntSetting("init_time", time.Now().Unix()) } @@ -180,8 +180,8 @@ func GetSettings() ([]*models.Setting, error) { // GetGlobalSettings for admin configuration func GetGlobalSettings(authUser *models.AuthUser) (*models.GlobalSettings, error) { - if authUser.IsSuperAdmin == false { - return nil, errors.New("Only super administrators can perform this operation") + if !authUser.IsSuperAdmin { + return nil, errors.New("only super administrators can perform this operation") } return GlobalSettings, nil } @@ -224,9 +224,9 @@ func GetWxworkConfig() *models.WxworkConfig { } // UpdateWxworkConfig ... -func UpdateWxworkConfig(param map[string]interface{}, authUser *models.AuthUser) (*models.WxworkConfig, error) { - if authUser.IsSuperAdmin == false { - return nil, errors.New("Only super administrators can perform this operation") +func UpdateWxworkConfig(param map[string]interface{}, clientIP string, authUser *models.AuthUser) (*models.WxworkConfig, error) { + if !authUser.IsSuperAdmin { + return nil, errors.New("only super administrators can perform this operation") } wxworkConfig := param["object"].(map[string]interface{}) displayName := wxworkConfig["display_name"].(string) @@ -247,6 +247,7 @@ func UpdateWxworkConfig(param map[string]interface{}, authUser *models.AuthUser) CorpSecret: corpsecret, } AuthConfig.Wxwork = newWxworkConfig + go utils.OperationLog(clientIP, authUser.Username, "Update Wxwork Config", displayName) return newWxworkConfig, nil } @@ -278,9 +279,9 @@ func GetDingtalkConfig() *models.DingtalkConfig { } // UpdateDingtalkConfig ... -func UpdateDingtalkConfig(param map[string]interface{}, authUser *models.AuthUser) (*models.DingtalkConfig, error) { - if authUser.IsSuperAdmin == false { - return nil, errors.New("Only super administrators can perform this operation") +func UpdateDingtalkConfig(param map[string]interface{}, clientIP string, authUser *models.AuthUser) (*models.DingtalkConfig, error) { + if !authUser.IsSuperAdmin { + return nil, errors.New("only super administrators can perform this operation") } dingtalkConfig := param["object"].(map[string]interface{}) displayName := dingtalkConfig["display_name"].(string) @@ -298,6 +299,7 @@ func UpdateDingtalkConfig(param map[string]interface{}, authUser *models.AuthUse AppSecret: appsecret, } AuthConfig.Dingtalk = newDingtalkConfig + go utils.OperationLog(clientIP, authUser.Username, "Update Dingtalk Config", displayName) return newDingtalkConfig, nil } @@ -329,9 +331,9 @@ func GetFeishuConfig() *models.FeishuConfig { } // UpdateFeishuConfig ... -func UpdateFeishuConfig(param map[string]interface{}, authUser *models.AuthUser) (*models.FeishuConfig, error) { - if authUser.IsSuperAdmin == false { - return nil, errors.New("Only super administrators can perform this operation") +func UpdateFeishuConfig(param map[string]interface{}, clientIP string, authUser *models.AuthUser) (*models.FeishuConfig, error) { + if !authUser.IsSuperAdmin { + return nil, errors.New("only super administrators can perform this operation") } feishuConfig := param["object"].(map[string]interface{}) displayName := feishuConfig["display_name"].(string) @@ -349,6 +351,7 @@ func UpdateFeishuConfig(param map[string]interface{}, authUser *models.AuthUser) AppSecret: appsecret, } AuthConfig.Feishu = newFeishuConfig + go utils.OperationLog(clientIP, authUser.Username, "Update Feishu Config", displayName) return newFeishuConfig, nil } @@ -380,9 +383,9 @@ func GetLarkConfig() *models.LarkConfig { } // UpdateLarkConfig ... -func UpdateLarkConfig(param map[string]interface{}, authUser *models.AuthUser) (*models.LarkConfig, error) { - if authUser.IsSuperAdmin == false { - return nil, errors.New("Only super administrators can perform this operation") +func UpdateLarkConfig(param map[string]interface{}, clientIP string, authUser *models.AuthUser) (*models.LarkConfig, error) { + if !authUser.IsSuperAdmin { + return nil, errors.New("only super administrators can perform this operation") } larkConfig := param["object"].(map[string]interface{}) displayName := larkConfig["display_name"].(string) @@ -400,6 +403,7 @@ func UpdateLarkConfig(param map[string]interface{}, authUser *models.AuthUser) ( AppSecret: appsecret, } AuthConfig.Lark = newLarkConfig + go utils.OperationLog(clientIP, authUser.Username, "Update Lark Config", displayName) return newLarkConfig, nil } @@ -436,9 +440,9 @@ func GetLDAPConfig() *models.LDAPConfig { } // UpdateLDAPConfig ... -func UpdateLDAPConfig(param map[string]interface{}, authUser *models.AuthUser) (*models.LDAPConfig, error) { - if authUser.IsSuperAdmin == false { - return nil, errors.New("Only super administrators can perform this operation") +func UpdateLDAPConfig(param map[string]interface{}, clientIP string, authUser *models.AuthUser) (*models.LDAPConfig, error) { + if !authUser.IsSuperAdmin { + return nil, errors.New("only super administrators can perform this operation") } ldapConfig := param["object"].(map[string]interface{}) displayName := ldapConfig["display_name"].(string) @@ -462,6 +466,7 @@ func UpdateLDAPConfig(param map[string]interface{}, authUser *models.AuthUser) ( AuthenticatorEnabled: authenticatorEnabled, } AuthConfig.LDAP = newLDAPConfig + go utils.OperationLog(clientIP, authUser.Username, "Update LDAP Config", displayName) return newLDAPConfig, nil } @@ -488,9 +493,9 @@ func GetCAS2Config() *models.CAS2Config { } // UpdateCAS2Config ... -func UpdateCAS2Config(param map[string]interface{}, authUser *models.AuthUser) (*models.CAS2Config, error) { - if authUser.IsSuperAdmin == false { - return nil, errors.New("Only super administrators can perform this operation") +func UpdateCAS2Config(param map[string]interface{}, clientIP string, authUser *models.AuthUser) (*models.CAS2Config, error) { + if !authUser.IsSuperAdmin { + return nil, errors.New("only super administrators can perform this operation") } cas2Config := param["object"].(map[string]interface{}) displayName := cas2Config["display_name"].(string) @@ -505,13 +510,14 @@ func UpdateCAS2Config(param map[string]interface{}, authUser *models.AuthUser) ( Callback: callback, } AuthConfig.CAS2 = newCAS2Config + go utils.OperationLog(clientIP, authUser.Username, "Update CAS2 Config", displayName) return newCAS2Config, nil } // UpdateGlobalSettings ... func UpdateGlobalSettings(param map[string]interface{}, authUser *models.AuthUser) (*models.GlobalSettings, error) { - if authUser.IsSuperAdmin == false { - return nil, errors.New("Only super administrators can perform this operation") + if !authUser.IsSuperAdmin { + return nil, errors.New("only super administrators can perform this operation") } settings := param["object"].(map[string]interface{}) authEnabled := settings["auth_enabled"].(bool) diff --git a/firewall/cc.go b/firewall/cc.go index 4edb9f2..d7d5335 100644 --- a/firewall/cc.go +++ b/firewall/cc.go @@ -10,6 +10,7 @@ package firewall import ( "errors" "net/http" + "strconv" "sync" "time" @@ -52,7 +53,7 @@ func CCAttackTick(appID int64) { clientID := key.(string) stat := value.(*models.ClientStat) //fmt.Println("CCAttackTick:", appID, clientID, stat) - if stat.IsBadIP == true { + if stat.IsBadIP { stat.RemainSeconds -= ccPolicy.IntervalMilliSeconds / 1000.0 if stat.RemainSeconds <= 0 { appCCCount.Delete(clientID) @@ -124,7 +125,7 @@ func IsCCAttack(r *http.Request, app *models.Application, srcIP string) (bool, * } } ccPolicy := GetCCPolicyByAppID(app.ID) - if ccPolicy.IsEnabled == false { + if !ccPolicy.IsEnabled { return false, nil, "", false } if isCC { @@ -138,21 +139,21 @@ func IsCCAttack(r *http.Request, app *models.Application, srcIP string) (bool, * ccCount, _ := ccCounts.LoadOrStore(ccAppID, &sync.Map{}) appCCCount := ccCount.(*sync.Map) preHashContent := srcIP - if ccPolicy.StatByURL == true { + if ccPolicy.StatByURL { preHashContent += r.URL.Path } - if ccPolicy.StatByUserAgent == true { + if ccPolicy.StatByUserAgent { ua := r.Header.Get("User-Agent") preHashContent += ua } - if ccPolicy.StatByCookie == true { + if ccPolicy.StatByCookie { cookie := r.Header.Get("Cookie") preHashContent += cookie } clientID := data.SHA256Hash(preHashContent) clientIDStat, _ := appCCCount.LoadOrStore(clientID, &models.ClientStat{QuickCount: 0, SlowCount: 0, TimeFrameCount: 0, IsBadIP: false, RemainSeconds: 0}) clientStat := clientIDStat.(*models.ClientStat) - if clientStat.IsBadIP == true { + if clientStat.IsBadIP { needLog := false if clientStat.QuickCount == 0 { clientStat.QuickCount++ @@ -173,7 +174,7 @@ func InitCCPolicy() { utils.DebugPrintln("InitCCPolicy CreateTableIfNotExistsCCPolicy", err) } existCCPolicy := data.DAL.ExistsCCPolicy() - if existCCPolicy == false { + if !existCCPolicy { err = data.DAL.InsertCCPolicy(0, 100, 6, 900, models.Action_Block_100, true, false, false, true) if err != nil { utils.DebugPrintln("InitCCPolicy InsertCCPolicy", err) @@ -190,9 +191,9 @@ func InitCCPolicy() { } // UpdateCCPolicy update CC policy -func UpdateCCPolicy(param map[string]interface{}, authUser *models.AuthUser) error { - if authUser.IsSuperAdmin == false { - return errors.New("Only super administrators can perform this operation") +func UpdateCCPolicy(param map[string]interface{}, clientIP string, authUser *models.AuthUser) error { + if !authUser.IsSuperAdmin { + return errors.New("only super administrators can perform this operation") } ccPolicyMap := param["object"].(map[string]interface{}) appID := int64(param["id"].(float64)) @@ -205,7 +206,7 @@ func UpdateCCPolicy(param map[string]interface{}, authUser *models.AuthUser) err statByCookie := ccPolicyMap["stat_by_cookie"].(bool) isEnabled := ccPolicyMap["is_enabled"].(bool) existAppID := data.DAL.ExistsCCPolicyByAppID(appID) - if existAppID == false { + if !existAppID { // new policy err := data.DAL.InsertCCPolicy(appID, intervalMilliSeconds, maxCount, blockSeconds, action, statByURL, statByUA, statByCookie, isEnabled) if err != nil { @@ -217,9 +218,10 @@ func UpdateCCPolicy(param map[string]interface{}, authUser *models.AuthUser) err Action: action, StatByURL: statByURL, StatByUserAgent: statByUA, StatByCookie: statByCookie, IsEnabled: isEnabled} ccPolicies.Store(appID, ccPolicy) - if ccPolicy.IsEnabled == true { + if ccPolicy.IsEnabled { go CCAttackTick(appID) } + go utils.OperationLog(clientIP, authUser.Username, "Add CC Policy", strconv.FormatInt(appID, 10)) } else { // update policy err := data.DAL.UpdateCCPolicy(intervalMilliSeconds, maxCount, blockSeconds, action, statByURL, statByUA, statByCookie, isEnabled, appID) @@ -240,21 +242,22 @@ func UpdateCCPolicy(param map[string]interface{}, authUser *models.AuthUser) err ccPolicy.StatByCookie = statByCookie ccPolicy.Action = action ccPolicy.IsEnabled = isEnabled - if ccPolicy.IsEnabled == true { + if ccPolicy.IsEnabled { go CCAttackTick(appID) } + go utils.OperationLog(clientIP, authUser.Username, "Update CC Policy", strconv.FormatInt(appID, 10)) } data.UpdateFirewallLastModified() return nil } // DeleteCCPolicyByAppID delete CC policy by app id -func DeleteCCPolicyByAppID(appID int64, authUser *models.AuthUser, adminRequired bool) error { - if adminRequired && authUser.IsSuperAdmin == false { +func DeleteCCPolicyByAppID(appID int64, clientIP string, authUser *models.AuthUser, adminRequired bool) error { + if adminRequired && !authUser.IsSuperAdmin { return errors.New("only super admin can delete CC policy") } if appID == 0 { - return errors.New("Global CC policy cannot be deleted") + return errors.New("global CC policy cannot be deleted") } err := data.DAL.DeleteCCPolicy(appID) if err != nil { @@ -267,6 +270,7 @@ func DeleteCCPolicyByAppID(appID int64, authUser *models.AuthUser, adminRequired ccTicker.Stop() } } + go utils.OperationLog(clientIP, authUser.Username, "Delete CC Policy by AppID", strconv.FormatInt(appID, 10)) data.UpdateFirewallLastModified() return nil } diff --git a/firewall/check_item.go b/firewall/check_item.go index 2b4c7ea..8c1b20e 100644 --- a/firewall/check_item.go +++ b/firewall/check_item.go @@ -218,7 +218,7 @@ func DeleteCheckItemsByGroupPolicy(groupPolicy *models.GroupPolicy) error { // DebugTranverseCheckItems ... func DebugTranverseCheckItems() { - if utils.Debug == false { + if !utils.Debug { return } checkPointCheckItemsMap.Range(func(key, value interface{}) bool { diff --git a/firewall/firewall.go b/firewall/firewall.go index 6325621..3dffba2 100644 --- a/firewall/firewall.go +++ b/firewall/firewall.go @@ -28,8 +28,6 @@ import ( "janusec/utils" ) -type policyKey string - var dynamicSuffix = []string{".html", ".htm", ".shtml", ".php", ".jsp", ".aspx", ".asp", ".do", ".cgi", ".cfm"} //var staticSuffix = []string{".js", ".css", ".png", ".jpg", ".gif", ".ico", ".bmp", ".zip", ".rar", ".tar.gz", ".mp3", ".avi"} @@ -108,25 +106,25 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode // ChkPoint_Host matched, policy := IsMatchGroupPolicy(ctxMap, appID, r.Host, models.ChkPointHost, "", false) - if matched == true { + if matched { return matched, policy } // ChkPoint_IPAddress matched, policy = IsMatchGroupPolicy(ctxMap, appID, srcIP, models.ChkPointIPAddress, "", false) - if matched == true { + if matched { return matched, policy } // ChkPoint_Method matched, policy = IsMatchGroupPolicy(ctxMap, appID, r.Method, models.ChkPointMethod, "", false) - if matched == true { + if matched { return matched, policy } // ChkPoint_URLPath matched, policy = IsMatchGroupPolicy(ctxMap, appID, r.URL.Path, models.ChkPointURLPath, "", false) - if matched == true { + if matched { return matched, policy } // ChkPoint_URLQuery @@ -134,7 +132,7 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode //decode_query := UnEscapeRawValue(r.URL.RawQuery) //fmt.Println("decode_query:", decode_query) matched, policy = IsMatchGroupPolicy(ctxMap, appID, r.URL.RawQuery, models.ChkPointURLQuery, "", true) - if matched == true { + if matched { return matched, policy } } @@ -143,7 +141,7 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode ext := filepath.Ext(r.URL.Path) if ext != "" { matched, policy = IsMatchGroupPolicy(ctxMap, appID, ext, models.ChkPointFileExt, "", false) - if matched == true { + if matched { return matched, policy } } @@ -164,7 +162,7 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode for _, fileHeader := range filesHeader { fileExtension := filepath.Ext(fileHeader.Filename) // .php matched, policy = IsMatchGroupPolicy(ctxMap, appID, fileExtension, models.ChkPointUploadFileExt, "", false) - if matched == true { + if matched { return matched, policy } } @@ -178,10 +176,10 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode if err == io.EOF { break } - partContent, err := ioutil.ReadAll(p) + partContent, _ := ioutil.ReadAll(p) //fmt.Println("part_content=", string(part_content)) matched, policy = IsMatchGroupPolicy(ctxMap, appID, string(partContent), models.ChkPointGetPostValue, "", true) - if matched == true { + if matched { return matched, policy } } @@ -195,7 +193,7 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode utils.DebugPrintln("IsRequestHitPolicy Unmarshal", err) } matched, policy := IsJSONValueHitPolicy(ctxMap, appID, params) - if matched == true { + if matched { return matched, policy } } @@ -214,7 +212,7 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode //fmt.Println("IsRequestHitPolicy param", key, ":", values) // ChkPoint_GetPostKey matched, policy = IsMatchGroupPolicy(ctxMap, appID, key, models.ChkPointGetPostKey, "", false) - if matched == true { + if matched { return matched, policy } @@ -228,7 +226,7 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode /* valueLength := strconv.Itoa(len(value)) matched, policy = IsMatchGroupPolicy(ctxMap, appID, valueLength, models.ChkPointValueLength, "", false) - if matched == true { + if matched { return matched, policy } */ @@ -236,7 +234,7 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode // ChkPoint_GetPostValue matched, policy = IsMatchGroupPolicy(ctxMap, appID, value, models.ChkPointGetPostValue, "", true) //fmt.Println("ChkPoint_GetPostValue:", value2, matched) - if matched == true { + if matched { return matched, policy } } @@ -245,7 +243,7 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode // ChkPoint_Referer added v1.1.0 matched, policy = IsMatchGroupPolicy(ctxMap, appID, r.Referer(), models.ChkPointReferer, "", false) - if matched == true { + if matched { return matched, policy } @@ -254,27 +252,27 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode for _, cookie := range cookies { // ChkPoint_CookieKey matched, policy = IsMatchGroupPolicy(ctxMap, appID, cookie.Name, models.ChkPointCookieKey, "", false) - if matched == true { + if matched { return matched, policy } // ChkPoint_CookieValue //value := UnEscapeRawValue(cookie.Value) //fmt.Println("CookieValue:", value) matched, policy = IsMatchGroupPolicy(ctxMap, appID, cookie.Value, models.ChkPointCookieValue, "", true) - if matched == true { + if matched { return matched, policy } } // ChkPoint_UserAgent matched, policy = IsMatchGroupPolicy(ctxMap, appID, r.UserAgent(), models.ChkPointUserAgent, "", false) - if matched == true { + if matched { return matched, policy } // ChkPoint_ContentType media_type matched, policy = IsMatchGroupPolicy(ctxMap, appID, mediaType, models.ChkPointContentType, "", false) - if matched == true { + if matched { return matched, policy } @@ -282,14 +280,14 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode for headerKey, headerValues := range r.Header { // ChkPoint_HeaderKey matched, policy = IsMatchGroupPolicy(ctxMap, appID, headerKey, models.ChkPointHeaderKey, "", false) - if matched == true { + if matched { return matched, policy } // ChkPoint_HeaderValue for _, headerValue := range headerValues { matched, policy = IsMatchGroupPolicy(ctxMap, appID, headerValue, models.ChkPointHeaderValue, headerKey, false) //fmt.Println("ChkPoint_HeaderValue", headerKey, headerValue, matched) - if matched == true { + if matched { return matched, policy } } @@ -297,7 +295,7 @@ func IsRequestHitPolicy(r *http.Request, appID int64, srcIP string) (bool, *mode // ChkPoint_Proto matched, policy = IsMatchGroupPolicy(ctxMap, appID, r.Proto, models.ChkPointUserAgent, "", false) - if matched == true { + if matched { return matched, policy } @@ -316,21 +314,21 @@ func IsResponseHitPolicy(resp *http.Response, appID int64) (bool, *models.GroupP // ChkPoint_ResponseStatusCode matched, policy := IsMatchGroupPolicy(ctxMap, appID, strconv.Itoa(resp.StatusCode), models.ChkPointResponseStatusCode, "", false) //fmt.Println("IsResponseHitPolicy ResponseStatusCode", matched) - if matched == true { + if matched { return matched, policy } // ChkPoint_ResponseHeaderKey for headerKey, headerValues := range resp.Header { // ChkPoint_ResponseHeaderKey matched, policy = IsMatchGroupPolicy(ctxMap, appID, headerKey, models.ChkPointResponseHeaderKey, "", false) - if matched == true { + if matched { return matched, policy } // ChkPoint_ResponseHeaderValue for _, headerValue := range headerValues { matched, policy = IsMatchGroupPolicy(ctxMap, appID, headerValue, models.ChkPointResponseHeaderValue, headerKey, false) //fmt.Println("ChkPoint_ResponseHeaderValue", headerKey, headerValue, matched) - if matched == true { + if matched { return matched, policy } } @@ -341,7 +339,7 @@ func IsResponseHitPolicy(resp *http.Response, appID int64) (bool, *models.GroupP bodyLength := strconv.FormatInt(resp.ContentLength, 10) matched, policy = IsMatchGroupPolicy(ctxMap, appID, bodyLength, models.ChkPointResponseBodyLength, "", false) //fmt.Println("IsResponseHitPolicy ChkPoint_ResponseBodyLength", matched) - if matched == true { + if matched { return matched, policy } */ @@ -352,7 +350,7 @@ func IsResponseHitPolicy(resp *http.Response, appID int64) (bool, *models.GroupP contentEncoding := resp.Header.Get("Content-Encoding") var body1 string if contentEncoding == "gzip" { - reader, err := gzip.NewReader(bytes.NewBuffer(bodyBuf)) + reader, _ := gzip.NewReader(bytes.NewBuffer(bodyBuf)) defer reader.Close() decompressedBodyBuf, err := ioutil.ReadAll(reader) if err != nil { @@ -365,7 +363,7 @@ func IsResponseHitPolicy(resp *http.Response, appID int64) (bool, *models.GroupP resp.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBuf)) matched, policy = IsMatchGroupPolicy(ctxMap, appID, body1, models.ChkPointResponseBody, "", false) //fmt.Println("IsResponseHitPolicy ChkPoint_ResponseBody", matched, resp.ContentLength, bodyLength, "000", body1) - if matched == true { + if matched { return matched, policy } @@ -383,14 +381,14 @@ func IsJSONValueHitPolicy(ctxMap *sync.Map, appID int64, value interface{}) (boo case reflect.String: value2 := value.(string) matched, policy := IsMatchGroupPolicy(ctxMap, appID, value2, models.ChkPointGetPostValue, "", true) - if matched == true { + if matched { return matched, policy } case reflect.Map: value2 := value.(map[string]interface{}) for _, subValue := range value2 { matched, policy := IsJSONValueHitPolicy(ctxMap, appID, subValue) - if matched == true { + if matched { return matched, policy } } @@ -398,7 +396,7 @@ func IsJSONValueHitPolicy(ctxMap *sync.Map, appID int64, value interface{}) (boo value2 := value.([]interface{}) for _, subValue := range value2 { matched, policy := IsJSONValueHitPolicy(ctxMap, appID, subValue) - if matched == true { + if matched { return matched, policy } } diff --git a/firewall/group_policy.go b/firewall/group_policy.go index c88cb4c..ebf90a9 100644 --- a/firewall/group_policy.go +++ b/firewall/group_policy.go @@ -40,7 +40,7 @@ func InitGroupPolicy() { utils.DebugPrintln("CreateTableIfNotExistCheckItems error", err) } existRegexPolicy := data.DAL.ExistsGroupPolicy() - if existRegexPolicy == false { + if !existRegexPolicy { err := data.DAL.SetIDSeqStartWith("group_policies", 10101) if err != nil { utils.DebugPrintln("InitGroupPolicy SetIDSeqStartWith error", err) @@ -174,7 +174,7 @@ func GetGroupPolicyByID(id int64) (*models.GroupPolicy, error) { return groupPolicy, nil } } - return nil, errors.New("Not found") + return nil, errors.New("not found") } // GetGroupPolicyIndex ... @@ -188,9 +188,9 @@ func GetGroupPolicyIndex(id int64) int { } // DeleteGroupPolicyByID ... -func DeleteGroupPolicyByID(id int64, authUser *models.AuthUser) error { - if authUser.IsSuperAdmin == false { - return errors.New("Only super administrators can perform this operation") +func DeleteGroupPolicyByID(id int64, clientIP string, authUser *models.AuthUser) error { + if !authUser.IsSuperAdmin { + return errors.New("only super administrators can perform this operation") } groupPolicy, err := GetGroupPolicyByID(id) if err != nil { @@ -206,24 +206,28 @@ func DeleteGroupPolicyByID(id int64, authUser *models.AuthUser) error { } i := GetGroupPolicyIndex(id) groupPolicies = append(groupPolicies[:i], groupPolicies[i+1:]...) + go utils.OperationLog(clientIP, authUser.Username, "Delete Group Policy", strconv.FormatInt(id, 10)) data.UpdateFirewallLastModified() return nil } // UpdateGroupPolicy ... -func UpdateGroupPolicy(r *http.Request, userID int64, authUser *models.AuthUser) (*models.GroupPolicy, error) { - if authUser.IsSuperAdmin == false { - return nil, errors.New("Only super administrators can perform this operation") +func UpdateGroupPolicy(r *http.Request, userID int64, clientIP string, authUser *models.AuthUser) (*models.GroupPolicy, error) { + if !authUser.IsSuperAdmin { + return nil, errors.New("only super administrators can perform this operation") } var setGroupPolicyRequest models.RPCSetGroupPolicy err := json.NewDecoder(r.Body).Decode(&setGroupPolicyRequest) + if err != nil { + return nil, errors.New("decode body error") + } defer r.Body.Close() utils.CheckError("UpdateGroupPolicy Decode", err) curGroupPolicy := setGroupPolicyRequest.Object - curGroupPolicy.UpdateTime = time.Now().Unix() if curGroupPolicy == nil { - return nil, errors.New("UpdateGroupPolicy parse body null") + return nil, errors.New("updateGroupPolicy parse body null") } + curGroupPolicy.UpdateTime = time.Now().Unix() checkItems := curGroupPolicy.CheckItems curGroupPolicy.HitValue = 0 for _, checkItem := range checkItems { @@ -243,10 +247,11 @@ func UpdateGroupPolicy(r *http.Request, userID int64, authUser *models.AuthUser) if err != nil { utils.DebugPrintln("UpdateGroupPolicy UpdateCheckItems error", err) } + go utils.OperationLog(clientIP, authUser.Username, "Add Group Policy", curGroupPolicy.Description) } else { groupPolicy, err := GetGroupPolicyByID(curGroupPolicy.ID) utils.CheckError("UpdateGroupPolicy GetGroupPolicyByID", err) - err = data.DAL.UpdateGroupPolicy(curGroupPolicy.Description, curGroupPolicy.AppID, curGroupPolicy.VulnID, curGroupPolicy.HitValue, curGroupPolicy.Action, curGroupPolicy.IsEnabled, curGroupPolicy.UserID, curTime, groupPolicy.ID) + _ = data.DAL.UpdateGroupPolicy(curGroupPolicy.Description, curGroupPolicy.AppID, curGroupPolicy.VulnID, curGroupPolicy.HitValue, curGroupPolicy.Action, curGroupPolicy.IsEnabled, curGroupPolicy.UserID, curTime, groupPolicy.ID) groupPolicy.Description = curGroupPolicy.Description groupPolicy.AppID = curGroupPolicy.AppID groupPolicy.VulnID = curGroupPolicy.VulnID @@ -259,6 +264,7 @@ func UpdateGroupPolicy(r *http.Request, userID int64, authUser *models.AuthUser) if err != nil { utils.DebugPrintln("UpdateGroupPolicy UpdateCheckItems error", err) } + go utils.OperationLog(clientIP, authUser.Username, "Update Group Policy", curGroupPolicy.Description) } return curGroupPolicy, nil } @@ -280,7 +286,7 @@ func IsMatchGroupPolicy(hitValueMap *sync.Map, appID int64, value string, checkP } for _, checkItem := range checkItems { groupPolicy := checkItem.GroupPolicy - if groupPolicy.IsEnabled == false { + if !groupPolicy.IsEnabled { continue } if groupPolicy.AppID == 0 || groupPolicy.AppID == appID { @@ -294,7 +300,7 @@ func IsMatchGroupPolicy(hitValueMap *sync.Map, appID int64, value string, checkP hit, err = regexp.MatchString(checkItem.RegexPolicy, value) utils.CheckError("IsMatchGroupPolicy MatchString", err) case models.OperationEqualsStringCaseInsensitive: - if strings.ToLower(checkItem.RegexPolicy) == strings.ToLower(value) { + if strings.EqualFold(checkItem.RegexPolicy, value) { hit = true } case models.OperationGreaterThanInteger: @@ -324,7 +330,7 @@ func IsMatchGroupPolicy(hitValueMap *sync.Map, appID int64, value string, checkP hit = !notHit utils.CheckError("IsMatchGroupPolicy NotMatchString", err) } - if hit == true { + if hit { hitValueInterface, _ := hitValueMap.LoadOrStore(groupPolicy.ID, int64(0)) hitValue := hitValueInterface.(int64) hitValue += int64(checkItem.CheckPoint) diff --git a/firewall/init.go b/firewall/init.go index 9180889..8accac1 100644 --- a/firewall/init.go +++ b/firewall/init.go @@ -19,7 +19,7 @@ func InitFirewall() { ccPolicies.Range(func(key, value interface{}) bool { appID := key.(int64) ccPolicy := value.(*models.CCPolicy) - if ccPolicy.IsEnabled == true { + if ccPolicy.IsEnabled { go CCAttackTick(appID) } return true diff --git a/firewall/ip_policy.go b/firewall/ip_policy.go index f92ca0c..48d5fd7 100644 --- a/firewall/ip_policy.go +++ b/firewall/ip_policy.go @@ -13,6 +13,7 @@ import ( "janusec/data" "janusec/models" "janusec/utils" + "strconv" "strings" ) @@ -35,9 +36,9 @@ func GetIPPolicies() ([]*models.IPPolicy, error) { } // UpdateIPPolicy update IP policy -func UpdateIPPolicy(param map[string]interface{}, authUser *models.AuthUser) (*models.IPPolicy, error) { - if authUser.IsSuperAdmin == false { - return nil, errors.New("Only super administrators can perform this operation") +func UpdateIPPolicy(param map[string]interface{}, clientIP string, authUser *models.AuthUser) (*models.IPPolicy, error) { + if !authUser.IsSuperAdmin { + return nil, errors.New("only super administrators can perform this operation") } ipPolicyI := param["object"].(map[string]interface{}) id := int64(ipPolicyI["id"].(float64)) @@ -57,6 +58,7 @@ func UpdateIPPolicy(param map[string]interface{}, authUser *models.AuthUser) (*m ApplyToCC: applyToCC, } globalIPPolicies = append(globalIPPolicies, ipPolicy) + go utils.OperationLog(clientIP, authUser.Username, "Add IP Policy", ipAddr) data.UpdateFirewallLastModified() return ipPolicy, nil } @@ -73,14 +75,15 @@ func UpdateIPPolicy(param map[string]interface{}, authUser *models.AuthUser) (*m if err != nil { return nil, err } + go utils.OperationLog(clientIP, authUser.Username, "Update IP Policy", ipAddr) data.UpdateFirewallLastModified() return ipPolicy, nil } // DeleteIPPolicyByID ... -func DeleteIPPolicyByID(id int64, authUser *models.AuthUser) error { - if authUser.IsSuperAdmin == false { - return errors.New("Only super administrators can perform this operation") +func DeleteIPPolicyByID(id int64, clientIP string, authUser *models.AuthUser) error { + if !authUser.IsSuperAdmin { + return errors.New("only super administrators can perform this operation") } for i, ipPolicy := range globalIPPolicies { if ipPolicy.ID == id { @@ -89,6 +92,7 @@ func DeleteIPPolicyByID(id int64, authUser *models.AuthUser) error { } } err := data.DAL.DeleteIPPolicyByID(id) + go utils.OperationLog(clientIP, authUser.Username, "Delete IP Policy by ID", strconv.FormatInt(id, 10)) data.UpdateFirewallLastModified() return err } diff --git a/firewall/nftables.go b/firewall/nftables.go index fb83442..db5b1d3 100644 --- a/firewall/nftables.go +++ b/firewall/nftables.go @@ -53,7 +53,7 @@ func InitNFTables() { utils.DebugPrintln("InitNFTables AddSet error", err) return } - rules, err := conn.GetRule(table, chain) + rules, _ := conn.GetRule(table, chain) if len(rules) == 0 { conn.AddRule(&nftables.Rule{ Table: table, @@ -84,11 +84,11 @@ func InitNFTables() { // nft add element inet janusec blocklist { 192.168.100.1 timeout 300s } func AddIP2NFTables(ip string, blockSeconds float64) { //fmt.Println("AddIP2NFTables", ip) - rules, err := conn.GetRule(table, chain) + rules, _ := conn.GetRule(table, chain) if len(rules) == 0 { InitNFTables() } - err = conn.SetAddElements(set, []nftables.SetElement{ + err := conn.SetAddElements(set, []nftables.SetElement{ {Key: []byte(net.ParseIP(ip).To4()), Timeout: time.Duration(blockSeconds) * time.Second}, }) if err != nil { diff --git a/firewall/vuln.go b/firewall/vuln.go index 589eff2..2471dc1 100644 --- a/firewall/vuln.go +++ b/firewall/vuln.go @@ -32,7 +32,7 @@ func InitVulnType() { os.Exit(1) } existVuln := data.DAL.ExistsVulnType() - if existVuln == false { + if !existVuln { err := data.DAL.InsertVulnType(001, "None") if err != nil { utils.DebugPrintln("InsertVulnType error", err) diff --git a/gateway/api.go b/gateway/api.go index 1a4b1a3..e0a34c7 100644 --- a/gateway/api.go +++ b/gateway/api.go @@ -115,21 +115,21 @@ func AdminAPIHandlerFunc(w http.ResponseWriter, r *http.Request) { case "get_app_user": obj, err = usermgmt.GetAdmin(param) case "update_app_user": - obj, err = usermgmt.UpdateUser(w, r, param, authUser) + obj, err = usermgmt.UpdateUser(w, r, param, clientIP, authUser) case "del_app_user": id := int64(param["id"].(float64)) obj = nil - err = usermgmt.DeleteUser(id, authUser) + err = usermgmt.DeleteUser(id, clientIP, authUser) case "get_cc_policy": id := int64(param["id"].(float64)) obj, err = firewall.GetCCPolicyRespByAppID(id) case "del_cc_policy": id := int64(param["id"].(float64)) obj = nil - err = firewall.DeleteCCPolicyByAppID(id, authUser, true) + err = firewall.DeleteCCPolicyByAppID(id, clientIP, authUser, true) case "update_cc_policy": obj = nil - err = firewall.UpdateCCPolicy(param, authUser) + err = firewall.UpdateCCPolicy(param, clientIP, authUser) case "get_group_policies": appID := int64(param["id"].(float64)) obj, err = firewall.GetGroupPolicies(appID) @@ -137,25 +137,25 @@ func AdminAPIHandlerFunc(w http.ResponseWriter, r *http.Request) { id := int64(param["id"].(float64)) obj, err = firewall.GetGroupPolicyByID(id) case "update_group_policy": - obj, err = firewall.UpdateGroupPolicy(r, userID, authUser) + obj, err = firewall.UpdateGroupPolicy(r, userID, clientIP, authUser) case "get_ip_policies": obj, err = firewall.GetIPPolicies() case "update_ip_policy": - obj, err = firewall.UpdateIPPolicy(param, authUser) + obj, err = firewall.UpdateIPPolicy(param, clientIP, authUser) case "del_ip_policy": id := int64(param["id"].(float64)) obj = nil - err = firewall.DeleteIPPolicyByID(id, authUser) + err = firewall.DeleteIPPolicyByID(id, clientIP, authUser) case "del_group_policy": id := int64(param["id"].(float64)) obj = nil - err = firewall.DeleteGroupPolicyByID(id, authUser) + err = firewall.DeleteGroupPolicyByID(id, clientIP, authUser) case "test_regex": obj, err = firewall.TestRegex(param) case "get_vuln_types": obj, err = firewall.GetVulnTypes() case "login": - obj, err = usermgmt.Login(w, r, param) + obj, err = usermgmt.Login(w, r, param, clientIP) case "logout": obj = nil err = usermgmt.Logout(w, r) @@ -195,32 +195,32 @@ func AdminAPIHandlerFunc(w http.ResponseWriter, r *http.Request) { obj = data.GetWxworkConfig() err = nil case "update_wxwork_config": - obj, err = data.UpdateWxworkConfig(param, authUser) + obj, err = data.UpdateWxworkConfig(param, clientIP, authUser) case "get_dingtalk_config": obj = data.GetDingtalkConfig() err = nil case "update_dingtalk_config": - obj, err = data.UpdateDingtalkConfig(param, authUser) + obj, err = data.UpdateDingtalkConfig(param, clientIP, authUser) case "get_feishu_config": obj = data.GetFeishuConfig() err = nil case "update_feishu_config": - obj, err = data.UpdateFeishuConfig(param, authUser) + obj, err = data.UpdateFeishuConfig(param, clientIP, authUser) case "get_lark_config": obj = data.GetLarkConfig() err = nil case "update_lark_config": - obj, err = data.UpdateLarkConfig(param, authUser) + obj, err = data.UpdateLarkConfig(param, clientIP, authUser) case "get_ldap_config": obj = data.GetLDAPConfig() err = nil case "update_ldap_config": - obj, err = data.UpdateLDAPConfig(param, authUser) + obj, err = data.UpdateLDAPConfig(param, clientIP, authUser) case "get_cas2_config": obj = data.GetCAS2Config() err = nil case "update_cas2_config": - obj, err = data.UpdateCAS2Config(param, authUser) + obj, err = data.UpdateCAS2Config(param, clientIP, authUser) case "get_license": obj, err = nil, nil default: diff --git a/go.mod b/go.mod index aaf1966..38ceabe 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( github.com/gorilla/websocket v1.4.2 github.com/josharian/native v0.0.0-20200817173448-b6b71def0850 // indirect github.com/lib/pq v1.10.0 + github.com/mdlayher/ethtool v0.0.0-20210210192532-2b88debcdd43 // indirect github.com/mdlayher/genetlink v1.0.0 // indirect github.com/mdlayher/netlink v1.4.0 // indirect github.com/patrickmn/go-cache v2.1.0+incompatible @@ -29,9 +30,9 @@ require ( github.com/yookoala/gofast v0.6.0 github.com/yuin/goldmark v1.2.1 // indirect golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 - golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1 + golang.org/x/net v0.0.0-20210421230115-4e50805a0758 golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 // indirect - golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe // indirect + golang.org/x/sys v0.0.0-20210421221651-33663a62ff08 // indirect golang.org/x/tools/gopls v0.6.10 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect diff --git a/go.sum b/go.sum index 47ab384..5454aa0 100644 --- a/go.sum +++ b/go.sum @@ -560,6 +560,8 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 h1:4nGaVu0QrbjT/AK2PRLuQfQuh golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1 h1:4qWs8cYYH6PoEFy4dfhDFgoMGkwAcETd+MmPdCPMzUc= golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8= +golang.org/x/net v0.0.0-20210421230115-4e50805a0758 h1:aEpZnXcAmXkd6AvLb2OPt+EN1Zu/8Ne3pCqPjja5PXY= +golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -655,6 +657,8 @@ golang.org/x/sys v0.0.0-20210414055047-fe65e336abe0 h1:g9s1Ppvvun/fI+BptTMj909BB golang.org/x/sys v0.0.0-20210414055047-fe65e336abe0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe h1:WdX7u8s3yOigWAhHEaDl8r9G+4XwFQEQFtBMYyN+kXQ= golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210421221651-33663a62ff08 h1:qyN5bV+96OX8pL78eXDuz6YlDPzCYgdW74H5yE9BoSU= +golang.org/x/sys v0.0.0-20210421221651-33663a62ff08/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= diff --git a/janusec.go b/janusec.go index bb6670f..e4980b1 100644 --- a/janusec.go +++ b/janusec.go @@ -61,7 +61,7 @@ func main() { backend.LoadAppConfiguration() firewall.InitFirewall() data.LoadSettings() - if data.IsPrimary == false { + if !data.IsPrimary { go gateway.UpdateTimeTick() } go gateway.InitAccessStat() @@ -95,7 +95,7 @@ func main() { gateMux := http.NewServeMux() if data.IsPrimary { admin := data.CFG.PrimaryNode.Admin - if admin.Listen == true { + if admin.Listen { adminMux := http.NewServeMux() LoadAPIRoute(adminMux) if len(admin.ListenHTTP) > 0 { diff --git a/usermgmt/ldap.go b/usermgmt/ldap.go index 006a7e5..b5e97e0 100644 --- a/usermgmt/ldap.go +++ b/usermgmt/ldap.go @@ -74,7 +74,7 @@ func LDAPAuthFunc(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/oauth/code/register?uid="+username, http.StatusFound) return } - if totpItem.TOTPVerified == false { + if !totpItem.TOTPVerified { // TOTP Not Verified, redirect to register http.Redirect(w, r, "/oauth/code/register?uid="+username, http.StatusFound) return @@ -83,7 +83,7 @@ func LDAPAuthFunc(w http.ResponseWriter, r *http.Request) { totpCode := r.FormValue("code") totpCodeInt, _ := strconv.ParseUint(totpCode, 10, 32) verifyOK := VerifyCode(totpItem.TOTPKey, uint32(totpCodeInt)) - if verifyOK == false { + if !verifyOK { http.Redirect(w, r, "/ldap/login", http.StatusFound) return } @@ -130,5 +130,4 @@ func LDAPAuthFunc(w http.ResponseWriter, r *http.Request) { return } http.Redirect(w, r, "/", http.StatusFound) - return } diff --git a/usermgmt/usermgmt.go b/usermgmt/usermgmt.go index 463dd46..7c0d69f 100644 --- a/usermgmt/usermgmt.go +++ b/usermgmt/usermgmt.go @@ -10,6 +10,7 @@ package usermgmt import ( "errors" "net/http" + "strconv" "janusec/data" "janusec/models" @@ -39,10 +40,10 @@ func GetAuthUser(w http.ResponseWriter, r *http.Request) (*models.AuthUser, erro authUser := authUserI.(models.AuthUser) return &authUser, nil } - return nil, errors.New("Please login") + return nil, errors.New("please login") } -func Login(w http.ResponseWriter, r *http.Request, param map[string]interface{}) (*models.AuthUser, error) { +func Login(w http.ResponseWriter, r *http.Request, param map[string]interface{}, clientIP string) (*models.AuthUser, error) { obj := param["object"].(map[string]interface{}) username := obj["username"].(string) password := obj["passwd"].(string) @@ -65,9 +66,10 @@ func Login(w http.ResponseWriter, r *http.Request, param map[string]interface{}) if err != nil { utils.DebugPrintln("session save error", err) } + go utils.AuthLog(clientIP, username, "JANUSEC", "/janusec-admin/") return authUser, nil } - return nil, errors.New("Login failed.") + return nil, errors.New("login failed") } func Logout(w http.ResponseWriter, r *http.Request) error { @@ -130,7 +132,7 @@ func GetAppUserByID(userID int64) (*models.AppUser, error) { } } -func UpdateUser(w http.ResponseWriter, r *http.Request, param map[string]interface{}, authUser *models.AuthUser) (*models.AppUser, error) { +func UpdateUser(w http.ResponseWriter, r *http.Request, param map[string]interface{}, clientIP string, authUser *models.AuthUser) (*models.AppUser, error) { var user = param["object"].(map[string]interface{}) var userID = int64(user["id"].(float64)) var username = user["username"].(string) @@ -162,6 +164,7 @@ func UpdateUser(w http.ResponseWriter, r *http.Request, param map[string]interfa return nil, err } appUser.ID = newID + go utils.OperationLog(clientIP, authUser.Username, "Add User", username) } else { // update existed user if len(password) > 0 { @@ -185,6 +188,7 @@ func UpdateUser(w http.ResponseWriter, r *http.Request, param map[string]interfa } } appUser.ID = userID + go utils.OperationLog(clientIP, authUser.Username, "Update User", username) } appUser.Username = username appUser.Email = email @@ -194,11 +198,12 @@ func UpdateUser(w http.ResponseWriter, r *http.Request, param map[string]interfa return appUser, nil } -func DeleteUser(userID int64, authUser *models.AuthUser) error { - if authUser.IsSuperAdmin == false && userID != authUser.UserID { +func DeleteUser(userID int64, clientIP string, authUser *models.AuthUser) error { + if !authUser.IsSuperAdmin && userID != authUser.UserID { return errors.New("delete others is not permitted") } err := data.DAL.DeleteAppUser(userID) + go utils.OperationLog(clientIP, authUser.Username, "Delete User", strconv.FormatInt(userID, 10)) return err }