github-code-scanning[bot] commented on code in PR #6510:
URL: https://github.com/apache/trafficcontrol/pull/6510#discussion_r896772594
##########
traffic_ops/app/bin/checks/ToDSCPCheck.go:
##########
@@ -0,0 +1,646 @@
+package main
+
+import (
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "flag"
+ "io"
+ "io/ioutil"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/apache/trafficcontrol/lib/go-log"
+ tc "github.com/apache/trafficcontrol/lib/go-tc"
+ toclient "github.com/apache/trafficcontrol/traffic_ops/v3-client"
+ "github.com/google/gopacket"
+ "github.com/google/gopacket/layers"
+ "github.com/google/gopacket/pcap"
+)
+
+// Traffic Ops connection params
+const AllowInsecureConnections = false
+const UserAgent = "go/tc-dscp-monitor"
+const UseClientCache = false
+const TrafficOpsRequestTimeout = time.Second * time.Duration(10)
+
+var (
+ protocol int
+ sslflag bool
+ host_header string
+ confInt *string
+ http4 *http.Transport
+ http6 *http.Transport
+ https4 *http.Transport
+ https6 *http.Transport
+ httpClient4 *http.Client
+ httpClient6 *http.Client
+ httpsClient4 *http.Client
+ httpsClient6 *http.Client
+ http_port string
+ https_port string
+ eth_layer layers.Ethernet
+ ip4_layer layers.IPv4
+ ip6_layer layers.IPv6
+ tcp_layer layers.TCP
+ tls_layer layers.TLS
+ payload gopacket.Payload
+)
+
+var connect_timeout = 2000 * time.Millisecond
+var http_timeout = 1500 * time.Millisecond
+var pcap_timeout = 250 * time.Millisecond
+
+var parser *gopacket.DecodingLayerParser =
gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð_layer,
&tcp_layer, &tls_layer, &ip4_layer, &ip6_layer, &payload)
+
+type Config struct {
+ URL string `json:"to_url"`
+ User string `json:"user"`
+ Passwd string `json:"passwd"`
+}
+
+type Server struct {
+ id int
+ cdn string
+ name string
+ fqdn string
+ ip4 string
+ ip6 string
+ httpPort string
+ httpsPort string
+ failcount int
+ status string
+}
+
+func NewServer(id int, name string, status string, f int) Server {
+ server := Server{}
+ server.id = id
+ server.name = name
+ server.status = status
+ server.failcount = f
+ return server
+}
+
+func LoadConfig(file string) (Config, error) {
+ var config Config
+ configFile, err := os.Open(file)
+ defer configFile.Close()
+ if err != nil {
+ return config, err
+ }
+ jsonParser := json.NewDecoder(configFile)
+ jsonParser.Decode(&config)
+ return config, err
+}
+
+func capture(ctx context.Context, s Server, iface *string, ch_dscp chan uint8,
ch_ready chan uint8, ip string, ssl bool) {
+ var pcap_port string
+ if ssl {
+ pcap_port = s.httpsPort
+ } else {
+ pcap_port = s.httpPort
+ }
+
+ pcap_filter := "tcp and src " + ip + " and port " + pcap_port + " and
(tcp[tcpflags] & tcp-push != 0 or ip6[53] & 8 != 0)"
+ log.Debugf("capture() filter='%s'", pcap_filter)
+ if handle, err := pcap.OpenLive(*iface, 1400, false, pcap_timeout); err
!= nil {
+ log.Errorf("capture() pcap.OpenLive() error:", err)
+ } else if err := handle.SetBPFFilter(pcap_filter); err != nil {
+ log.Errorf("capture() handle.SetBPFFilter() error:", err)
+ } else if err := handle.SetDirection(pcap.DirectionIn); err != nil {
+ log.Errorf("capture() handle.SetDirection() error:", err)
+ } else {
+ defer handle.Close()
+ decodedLayers := []gopacket.LayerType{}
+ packetSource := gopacket.NewPacketSource(handle,
handle.LinkType())
+ timer := time.NewTimer(2000 * time.Millisecond)
+ ch_ready <- 1 // signal that capture is ready to proceed
+ pktCount := 0
+ for {
+ select {
+ case <-ctx.Done():
+ handle.Close() // without this, serious fh leak
+ log.Debugf("capture() context cancelled")
+ return
+ case <-timer.C:
+ log.Debugf("capture() timed out before packets
received")
+ ch_dscp <- 254
+ return
+ default:
+ pktCount++
+ packet, err := packetSource.NextPacket()
+ if err == io.EOF {
+ break
+ } else if err != nil {
+ log.Errorf("capture() Error:", err)
+ continue
+ }
+ if sslflag == true && pktCount < 6 {
+ // skip the TLS handshake packets -
they may not provide real DSCP value
+ log.Debugf("Packet #%d: %s", pktCount,
packet)
+ continue
+ }
+ log.Debugf("Packet #%d: %s", pktCount, packet)
+ err = parser.DecodeLayers(packet.Data(),
&decodedLayers)
+ if err != nil {
+ log.Warnf("%s", err)
+ }
+ for _, typ := range decodedLayers {
+ switch typ {
+ case layers.LayerTypeIPv4:
+ ch_dscp <- ip4_layer.TOS
+ return
+ case layers.LayerTypeIPv6:
+ ch_dscp <-
ip6_layer.TrafficClass
+ return
+ }
+ }
+ }
+ }
+ }
+}
+
+func protocol_picker(s Server, check_ip string, host_header string, check_path
string, v6flag bool) (cap_dscp string) {
+ if protocol == 0 || protocol == 2 {
+ // if prot is HTTP and HTTPS, just check HTTP - both is overkill
+ // do HTTP stuff
+ sslflag = false
+ }
+ if protocol == 1 || protocol == 3 {
+ // if a DS is HTTPS *only*...
+ // do HTTPS stuff
+ sslflag = true
+ }
+ log.Debugf("protocol_picker() ssl=%t", sslflag)
+ cap_dscp = request(confInt, s, host_header, check_ip, check_path,
v6flag, sslflag)
+ return
+}
+
+func request(iface *string, s Server, host_header string, ip string,
check_path string, v6 bool, ssl bool) string {
+ var cap_dscp uint8
+ var cap_dscp2 string
+ var url string
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel() // make sure all paths cancel the context to avoid
context leak
+ ch_dscp := make(chan uint8)
+ ch_ready := make(chan uint8)
+ go capture(ctx, s, iface, ch_dscp, ch_ready, ip, ssl)
+ if ssl {
+ url = "https://" + host_header + check_path
+ } else {
+ url = "http://" + host_header + check_path
+ }
+ log.Infof("request() url=%s ip=%s", url, ip)
+ req, err := http.NewRequest("GET", url, nil)
+ if err != nil {
+ log.Errorf("request() http.NewRequest() error:", err)
+ }
+ req.Close = true
+ req.Header.Add("Cache-Control", "only-if-cached")
+ req.Header.Add("User-Agent", UserAgent)
+ ready := <-ch_ready
+ if ready == 1 {
+ log.Debugf("request() received go signal from capture()")
+ }
+ if v6 && ssl == false {
+ resp, err := httpClient6.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient6.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else if v6 == false && ssl == false {
+ resp, err := httpClient4.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient4.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else if v6 && ssl {
+ resp, err := httpsClient6.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient6.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else {
+ resp, err := httpsClient4.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient4.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ }
+ cap_tos, more := <-ch_dscp
+ if more {
+ log.Debugf("request() received tos=%d", cap_tos)
+ cancel() // cancel context to prevent goroutine leak!
+ } else {
+ log.Debugf("request() received all dscp values")
+ cancel() // cancel context to prevent goroutine leak!
+ }
+ if cap_tos == 254 {
+ log.Errorf("request() no valid DSCP mark received")
+ cap_dscp2 = "-1"
+ } else {
+ cap_dscp = cap_tos >> 2
+ cap_dscp2 = strconv.Itoa(int(cap_dscp))
+ log.Debugf("request() received ipv6=%t dscp=%s", v6, cap_dscp2)
+ }
+ return cap_dscp2
+}
+
+func check_result(want string, have string) bool {
+ if want == have {
+ log.Debugf("check_result() success want=%s got=%s", want, have)
+ return true
+ } else if have == "-1" {
+ log.Debugf("check_result() undetermined (ignoring) want=%s
got=CAPTURE_TIMEOUT", want)
+ return true
+ } else {
+ log.Debugf("check_result() failure want=%s got=%s", want, have)
+ return false
+ }
+}
+
+func main() {
+ var (
+ cpath_new string
+ cap_dscp string
+ conf_dscp string
+ xmlID string
+ check_ip4 string
+ check_ip6 string
+ dialer_ip4 string
+ dialer_ip6 string
+ )
+
+ jobStart := time.Now()
+
+ // define default config file path
+ cpath, err := filepath.Abs(filepath.Dir(os.Args[0]))
+ if err != nil {
+ log.Errorf("Config error:", err)
+ os.Exit(1)
+ }
+ cpath_new = strings.Replace(cpath, "/bin/checks",
"/conf/check-config.json", 1)
+
+ // command-line flags
+ confPtr := flag.String("conf", cpath_new, "Config file path")
+ confInt = flag.String("iface", "undef", "Network interface for packet
capture")
+ confName := flag.String("name", "DSCP", "Check name to pass to TO, e.g.
'DSCP'")
+ confInclude := flag.String("host", "undef", "Specific host or regex to
include (optional)")
+ confCdn := flag.String("cdn", "all", "Check specific CDN by name")
+ confExclude := flag.String("exclude", "undef", "Hostname regex to
exclude")
+ confReset := flag.Bool("reset", false, "Reset check values in TO to
'blank' state")
+ confQuiet := flag.Bool("q", false, "Do not send updates to TO")
+ flag.Parse()
+
+ if *confInt == "undef" {
+ log.Errorf("Must specify network interface for packet capture")
+ os.Exit(1)
+ }
+ if *confName == "undef" {
+ log.Errorf("Must specify check name for update to send to TO")
+ os.Exit(1)
+ }
+
+ // load config json
+ config, err := LoadConfig(*confPtr)
+ if err != nil {
+ log.Errorf("Error loading config:", err)
+ os.Exit(1)
+ }
+
+ // connect to TO
+ session, _, err := toclient.LoginWithAgent(
+ config.URL,
+ config.User,
+ config.Passwd,
+ AllowInsecureConnections,
+ UserAgent,
+ UseClientCache,
+ TrafficOpsRequestTimeout)
+ if err != nil {
+ log.Errorf("An error occurred while logging in: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for server details
+ var servers tc.ServersV3Response
+ servers, _, err = session.GetServersWithHdr(nil, nil)
+ if err != nil {
+ log.Errorf("An error occurred while getting servers: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for delivery service details
+ var deliveryservices []tc.DeliveryServiceNullableV30
+ deliveryservices, _, err = session.GetDeliveryServicesV30WithHdr(nil,
nil)
+ if err != nil {
+ log.Errorf("An error occurred while getting delivery services:
%v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for cdn details
+ var cdns []tc.CDN
+ cdns, _, err = session.GetCDNs()
+ if err != nil {
+ log.Errorf("An error occurred while getting cdns: %v\n", err)
+ os.Exit(1)
+ }
+
+ // map cdn to domain name
+ cdn_map := make(map[string]string)
+ for _, cdn := range cdns {
+ cdn_map[cdn.Name] = cdn.DomainName
+ }
+
+ // map ds info
+ ds_matchlist := make(map[string][]tc.DeliveryServiceMatch)
+ ds_types := make(map[string]tc.DSType)
+ for _, ds := range deliveryservices {
+ ds_matchlist[*ds.XMLID] = *ds.MatchList
+ ds_types[*ds.XMLID] = *ds.Type
+ }
+
+ for _, server := range servers.Response {
+ re, err := regexp.Compile("^EDGE.*")
+ if err != nil {
+ log.Errorf("supplied exclusion regex does not
compile:", err)
+ os.Exit(1)
+ }
+ if re.Match([]byte(server.Type)) {
+ serverStart := time.Now()
+ if *confInclude != "undef" {
+ re_inc, err := regexp.Compile(*confInclude)
+ if err != nil {
+ log.Errorf("supplied exclusion regex
does not compile:", err)
+ os.Exit(1)
+ }
+ if !re_inc.MatchString(*server.HostName) {
+ log.Debugf("%s does not match the
provided include regex, skipping", server.HostName)
+ continue
+ }
+ }
+ if *confCdn != "all" && *confCdn != *server.CDNName {
+ log.Debugf("%s is not assigned to the specified
CDN '%s', skipping", server.HostName, *confCdn)
+ continue
+ }
+ if *confExclude != "undef" {
+ re, err := regexp.Compile(*confExclude)
+ if err != nil {
+ log.Errorf("supplied exclusion regex
does not compile:", err)
+ os.Exit(1)
+ }
+ if re.MatchString(*server.HostName) {
+ log.Debugf("%s matches the provided
exclude regex, skipping", server.HostName)
+ continue
+ }
+ }
+ s := NewServer(*server.ID, *server.HostName,
*server.Status, -1)
+ doV4 := false //default
+ doV6 := false //default
+ defaulStatusValue := -1
+ var statusData tc.ServercheckRequestNullable
+ statusData.ID = &s.id
+ statusData.Name = confName
+ statusData.HostName = &s.name
+ statusData.Value = &defaulStatusValue
+ s.fqdn = s.name + "." + *server.DomainName
+ log.Infof("Next server=%s status=%s", s.fqdn, s.status)
+ if (s.status == "REPORTED" || s.status == "ADMIN_DOWN")
&& *confReset != true {
+ s.failcount = 0
+ s.cdn = *server.CDNName
+ s.httpPort = strconv.Itoa(*server.TCPPort)
+ s.httpsPort = strconv.Itoa(*server.HTTPSPort)
+ for _, interf := range server.Interfaces {
+ for _, addr := range interf.IPAddresses
{
+ if s.ip4 == "" &&
strings.Count(addr.Address, ":") == 0 {
+ s.ip4 =
strings.Split(addr.Address, "/")[0]
+ }
+ if s.ip6 == "" &&
strings.Count(addr.Address, ":") > 0 {
+ s.ip6 =
strings.Split(addr.Address, "/")[0]
+ }
+ }
+ }
+ log.Debugf("Ports for %s: http=%s https=%s",
s.name, http_port, https_port)
+ services, _, err :=
session.GetDeliveryServicesByServerV30WithHdr(s.id, nil)
+ if err != nil {
+ log.Errorf("Error getting delivery
services from TO:", err)
+ os.Exit(1)
+ }
+
+ dialer := &net.Dialer{
+ Timeout: connect_timeout,
+ KeepAlive: -1,
+ DualStack: false,
+ FallbackDelay: -1,
+ }
+ if s.ip4 != "" {
+ doV4 = true
+ check_ip4 = s.ip4
+ dialer_ip4 = s.ip4
+ }
+ if s.ip6 != "" {
+ doV6 = true
+ check_ip6 = s.ip6
+ dialer_ip6 = "[" + s.ip6 + "]"
+ }
+
+ // it is necessary to define custom Transports
in order to support
+ // TLS SNI in go. Otherwise, we could have just
had the http client
+ // connect to the IPv4 or IPv6 address, and set
a custom Host header
+ // to ID the test target. SNI must be done this
way, however, so in
+ // order to be consistent, just set up
Transports for all protocol
+ // combinations.
+ http4 = &http.Transport{
+ DisableKeepAlives: true,
+ TLSClientConfig:
&tls.Config{InsecureSkipVerify: true},
Review Comment:
## Disabled TLS certificate check
InsecureSkipVerify should not be used in production code.
[Show more
details](https://github.com/apache/trafficcontrol/security/code-scanning/189)
##########
traffic_ops/app/bin/checks/ToDSCPCheck.go:
##########
@@ -0,0 +1,646 @@
+package main
+
+import (
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "flag"
+ "io"
+ "io/ioutil"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/apache/trafficcontrol/lib/go-log"
+ tc "github.com/apache/trafficcontrol/lib/go-tc"
+ toclient "github.com/apache/trafficcontrol/traffic_ops/v3-client"
+ "github.com/google/gopacket"
+ "github.com/google/gopacket/layers"
+ "github.com/google/gopacket/pcap"
+)
+
+// Traffic Ops connection params
+const AllowInsecureConnections = false
+const UserAgent = "go/tc-dscp-monitor"
+const UseClientCache = false
+const TrafficOpsRequestTimeout = time.Second * time.Duration(10)
+
+var (
+ protocol int
+ sslflag bool
+ host_header string
+ confInt *string
+ http4 *http.Transport
+ http6 *http.Transport
+ https4 *http.Transport
+ https6 *http.Transport
+ httpClient4 *http.Client
+ httpClient6 *http.Client
+ httpsClient4 *http.Client
+ httpsClient6 *http.Client
+ http_port string
+ https_port string
+ eth_layer layers.Ethernet
+ ip4_layer layers.IPv4
+ ip6_layer layers.IPv6
+ tcp_layer layers.TCP
+ tls_layer layers.TLS
+ payload gopacket.Payload
+)
+
+var connect_timeout = 2000 * time.Millisecond
+var http_timeout = 1500 * time.Millisecond
+var pcap_timeout = 250 * time.Millisecond
+
+var parser *gopacket.DecodingLayerParser =
gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð_layer,
&tcp_layer, &tls_layer, &ip4_layer, &ip6_layer, &payload)
+
+type Config struct {
+ URL string `json:"to_url"`
+ User string `json:"user"`
+ Passwd string `json:"passwd"`
+}
+
+type Server struct {
+ id int
+ cdn string
+ name string
+ fqdn string
+ ip4 string
+ ip6 string
+ httpPort string
+ httpsPort string
+ failcount int
+ status string
+}
+
+func NewServer(id int, name string, status string, f int) Server {
+ server := Server{}
+ server.id = id
+ server.name = name
+ server.status = status
+ server.failcount = f
+ return server
+}
+
+func LoadConfig(file string) (Config, error) {
+ var config Config
+ configFile, err := os.Open(file)
+ defer configFile.Close()
+ if err != nil {
+ return config, err
+ }
+ jsonParser := json.NewDecoder(configFile)
+ jsonParser.Decode(&config)
+ return config, err
+}
+
+func capture(ctx context.Context, s Server, iface *string, ch_dscp chan uint8,
ch_ready chan uint8, ip string, ssl bool) {
+ var pcap_port string
+ if ssl {
+ pcap_port = s.httpsPort
+ } else {
+ pcap_port = s.httpPort
+ }
+
+ pcap_filter := "tcp and src " + ip + " and port " + pcap_port + " and
(tcp[tcpflags] & tcp-push != 0 or ip6[53] & 8 != 0)"
+ log.Debugf("capture() filter='%s'", pcap_filter)
+ if handle, err := pcap.OpenLive(*iface, 1400, false, pcap_timeout); err
!= nil {
+ log.Errorf("capture() pcap.OpenLive() error:", err)
+ } else if err := handle.SetBPFFilter(pcap_filter); err != nil {
+ log.Errorf("capture() handle.SetBPFFilter() error:", err)
+ } else if err := handle.SetDirection(pcap.DirectionIn); err != nil {
+ log.Errorf("capture() handle.SetDirection() error:", err)
+ } else {
+ defer handle.Close()
+ decodedLayers := []gopacket.LayerType{}
+ packetSource := gopacket.NewPacketSource(handle,
handle.LinkType())
+ timer := time.NewTimer(2000 * time.Millisecond)
+ ch_ready <- 1 // signal that capture is ready to proceed
+ pktCount := 0
+ for {
+ select {
+ case <-ctx.Done():
+ handle.Close() // without this, serious fh leak
+ log.Debugf("capture() context cancelled")
+ return
+ case <-timer.C:
+ log.Debugf("capture() timed out before packets
received")
+ ch_dscp <- 254
+ return
+ default:
+ pktCount++
+ packet, err := packetSource.NextPacket()
+ if err == io.EOF {
+ break
+ } else if err != nil {
+ log.Errorf("capture() Error:", err)
+ continue
+ }
+ if sslflag == true && pktCount < 6 {
+ // skip the TLS handshake packets -
they may not provide real DSCP value
+ log.Debugf("Packet #%d: %s", pktCount,
packet)
+ continue
+ }
+ log.Debugf("Packet #%d: %s", pktCount, packet)
+ err = parser.DecodeLayers(packet.Data(),
&decodedLayers)
+ if err != nil {
+ log.Warnf("%s", err)
+ }
+ for _, typ := range decodedLayers {
+ switch typ {
+ case layers.LayerTypeIPv4:
+ ch_dscp <- ip4_layer.TOS
+ return
+ case layers.LayerTypeIPv6:
+ ch_dscp <-
ip6_layer.TrafficClass
+ return
+ }
+ }
+ }
+ }
+ }
+}
+
+func protocol_picker(s Server, check_ip string, host_header string, check_path
string, v6flag bool) (cap_dscp string) {
+ if protocol == 0 || protocol == 2 {
+ // if prot is HTTP and HTTPS, just check HTTP - both is overkill
+ // do HTTP stuff
+ sslflag = false
+ }
+ if protocol == 1 || protocol == 3 {
+ // if a DS is HTTPS *only*...
+ // do HTTPS stuff
+ sslflag = true
+ }
+ log.Debugf("protocol_picker() ssl=%t", sslflag)
+ cap_dscp = request(confInt, s, host_header, check_ip, check_path,
v6flag, sslflag)
+ return
+}
+
+func request(iface *string, s Server, host_header string, ip string,
check_path string, v6 bool, ssl bool) string {
+ var cap_dscp uint8
+ var cap_dscp2 string
+ var url string
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel() // make sure all paths cancel the context to avoid
context leak
+ ch_dscp := make(chan uint8)
+ ch_ready := make(chan uint8)
+ go capture(ctx, s, iface, ch_dscp, ch_ready, ip, ssl)
+ if ssl {
+ url = "https://" + host_header + check_path
+ } else {
+ url = "http://" + host_header + check_path
+ }
+ log.Infof("request() url=%s ip=%s", url, ip)
+ req, err := http.NewRequest("GET", url, nil)
+ if err != nil {
+ log.Errorf("request() http.NewRequest() error:", err)
+ }
+ req.Close = true
+ req.Header.Add("Cache-Control", "only-if-cached")
+ req.Header.Add("User-Agent", UserAgent)
+ ready := <-ch_ready
+ if ready == 1 {
+ log.Debugf("request() received go signal from capture()")
+ }
+ if v6 && ssl == false {
+ resp, err := httpClient6.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient6.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else if v6 == false && ssl == false {
+ resp, err := httpClient4.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient4.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else if v6 && ssl {
+ resp, err := httpsClient6.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient6.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else {
+ resp, err := httpsClient4.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient4.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ }
+ cap_tos, more := <-ch_dscp
+ if more {
+ log.Debugf("request() received tos=%d", cap_tos)
+ cancel() // cancel context to prevent goroutine leak!
+ } else {
+ log.Debugf("request() received all dscp values")
+ cancel() // cancel context to prevent goroutine leak!
+ }
+ if cap_tos == 254 {
+ log.Errorf("request() no valid DSCP mark received")
+ cap_dscp2 = "-1"
+ } else {
+ cap_dscp = cap_tos >> 2
+ cap_dscp2 = strconv.Itoa(int(cap_dscp))
+ log.Debugf("request() received ipv6=%t dscp=%s", v6, cap_dscp2)
+ }
+ return cap_dscp2
+}
+
+func check_result(want string, have string) bool {
+ if want == have {
+ log.Debugf("check_result() success want=%s got=%s", want, have)
+ return true
+ } else if have == "-1" {
+ log.Debugf("check_result() undetermined (ignoring) want=%s
got=CAPTURE_TIMEOUT", want)
+ return true
+ } else {
+ log.Debugf("check_result() failure want=%s got=%s", want, have)
+ return false
+ }
+}
+
+func main() {
+ var (
+ cpath_new string
+ cap_dscp string
+ conf_dscp string
+ xmlID string
+ check_ip4 string
+ check_ip6 string
+ dialer_ip4 string
+ dialer_ip6 string
+ )
+
+ jobStart := time.Now()
+
+ // define default config file path
+ cpath, err := filepath.Abs(filepath.Dir(os.Args[0]))
+ if err != nil {
+ log.Errorf("Config error:", err)
+ os.Exit(1)
+ }
+ cpath_new = strings.Replace(cpath, "/bin/checks",
"/conf/check-config.json", 1)
+
+ // command-line flags
+ confPtr := flag.String("conf", cpath_new, "Config file path")
+ confInt = flag.String("iface", "undef", "Network interface for packet
capture")
+ confName := flag.String("name", "DSCP", "Check name to pass to TO, e.g.
'DSCP'")
+ confInclude := flag.String("host", "undef", "Specific host or regex to
include (optional)")
+ confCdn := flag.String("cdn", "all", "Check specific CDN by name")
+ confExclude := flag.String("exclude", "undef", "Hostname regex to
exclude")
+ confReset := flag.Bool("reset", false, "Reset check values in TO to
'blank' state")
+ confQuiet := flag.Bool("q", false, "Do not send updates to TO")
+ flag.Parse()
+
+ if *confInt == "undef" {
+ log.Errorf("Must specify network interface for packet capture")
+ os.Exit(1)
+ }
+ if *confName == "undef" {
+ log.Errorf("Must specify check name for update to send to TO")
+ os.Exit(1)
+ }
+
+ // load config json
+ config, err := LoadConfig(*confPtr)
+ if err != nil {
+ log.Errorf("Error loading config:", err)
+ os.Exit(1)
+ }
+
+ // connect to TO
+ session, _, err := toclient.LoginWithAgent(
+ config.URL,
+ config.User,
+ config.Passwd,
+ AllowInsecureConnections,
+ UserAgent,
+ UseClientCache,
+ TrafficOpsRequestTimeout)
+ if err != nil {
+ log.Errorf("An error occurred while logging in: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for server details
+ var servers tc.ServersV3Response
+ servers, _, err = session.GetServersWithHdr(nil, nil)
+ if err != nil {
+ log.Errorf("An error occurred while getting servers: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for delivery service details
+ var deliveryservices []tc.DeliveryServiceNullableV30
+ deliveryservices, _, err = session.GetDeliveryServicesV30WithHdr(nil,
nil)
+ if err != nil {
+ log.Errorf("An error occurred while getting delivery services:
%v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for cdn details
+ var cdns []tc.CDN
+ cdns, _, err = session.GetCDNs()
+ if err != nil {
+ log.Errorf("An error occurred while getting cdns: %v\n", err)
+ os.Exit(1)
+ }
+
+ // map cdn to domain name
+ cdn_map := make(map[string]string)
+ for _, cdn := range cdns {
+ cdn_map[cdn.Name] = cdn.DomainName
+ }
+
+ // map ds info
+ ds_matchlist := make(map[string][]tc.DeliveryServiceMatch)
+ ds_types := make(map[string]tc.DSType)
+ for _, ds := range deliveryservices {
+ ds_matchlist[*ds.XMLID] = *ds.MatchList
+ ds_types[*ds.XMLID] = *ds.Type
+ }
+
+ for _, server := range servers.Response {
+ re, err := regexp.Compile("^EDGE.*")
+ if err != nil {
+ log.Errorf("supplied exclusion regex does not
compile:", err)
+ os.Exit(1)
+ }
+ if re.Match([]byte(server.Type)) {
+ serverStart := time.Now()
+ if *confInclude != "undef" {
+ re_inc, err := regexp.Compile(*confInclude)
+ if err != nil {
+ log.Errorf("supplied exclusion regex
does not compile:", err)
+ os.Exit(1)
+ }
+ if !re_inc.MatchString(*server.HostName) {
+ log.Debugf("%s does not match the
provided include regex, skipping", server.HostName)
+ continue
+ }
+ }
+ if *confCdn != "all" && *confCdn != *server.CDNName {
+ log.Debugf("%s is not assigned to the specified
CDN '%s', skipping", server.HostName, *confCdn)
+ continue
+ }
+ if *confExclude != "undef" {
+ re, err := regexp.Compile(*confExclude)
+ if err != nil {
+ log.Errorf("supplied exclusion regex
does not compile:", err)
+ os.Exit(1)
+ }
+ if re.MatchString(*server.HostName) {
+ log.Debugf("%s matches the provided
exclude regex, skipping", server.HostName)
+ continue
+ }
+ }
+ s := NewServer(*server.ID, *server.HostName,
*server.Status, -1)
+ doV4 := false //default
+ doV6 := false //default
+ defaulStatusValue := -1
+ var statusData tc.ServercheckRequestNullable
+ statusData.ID = &s.id
+ statusData.Name = confName
+ statusData.HostName = &s.name
+ statusData.Value = &defaulStatusValue
+ s.fqdn = s.name + "." + *server.DomainName
+ log.Infof("Next server=%s status=%s", s.fqdn, s.status)
+ if (s.status == "REPORTED" || s.status == "ADMIN_DOWN")
&& *confReset != true {
+ s.failcount = 0
+ s.cdn = *server.CDNName
+ s.httpPort = strconv.Itoa(*server.TCPPort)
+ s.httpsPort = strconv.Itoa(*server.HTTPSPort)
+ for _, interf := range server.Interfaces {
+ for _, addr := range interf.IPAddresses
{
+ if s.ip4 == "" &&
strings.Count(addr.Address, ":") == 0 {
+ s.ip4 =
strings.Split(addr.Address, "/")[0]
+ }
+ if s.ip6 == "" &&
strings.Count(addr.Address, ":") > 0 {
+ s.ip6 =
strings.Split(addr.Address, "/")[0]
+ }
+ }
+ }
+ log.Debugf("Ports for %s: http=%s https=%s",
s.name, http_port, https_port)
+ services, _, err :=
session.GetDeliveryServicesByServerV30WithHdr(s.id, nil)
+ if err != nil {
+ log.Errorf("Error getting delivery
services from TO:", err)
+ os.Exit(1)
+ }
+
+ dialer := &net.Dialer{
+ Timeout: connect_timeout,
+ KeepAlive: -1,
+ DualStack: false,
+ FallbackDelay: -1,
+ }
+ if s.ip4 != "" {
+ doV4 = true
+ check_ip4 = s.ip4
+ dialer_ip4 = s.ip4
+ }
+ if s.ip6 != "" {
+ doV6 = true
+ check_ip6 = s.ip6
+ dialer_ip6 = "[" + s.ip6 + "]"
+ }
+
+ // it is necessary to define custom Transports
in order to support
+ // TLS SNI in go. Otherwise, we could have just
had the http client
+ // connect to the IPv4 or IPv6 address, and set
a custom Host header
+ // to ID the test target. SNI must be done this
way, however, so in
+ // order to be consistent, just set up
Transports for all protocol
+ // combinations.
+ http4 = &http.Transport{
+ DisableKeepAlives: true,
+ TLSClientConfig:
&tls.Config{InsecureSkipVerify: true},
+ DialContext: func(ctx context.Context,
network, addr string) (net.Conn, error) {
+ addr = dialer_ip4 + ":" +
s.httpPort
+ return dialer.DialContext(ctx,
network, addr)
+ },
+ }
+ http6 = &http.Transport{
+ DisableKeepAlives: true,
+ TLSClientConfig:
&tls.Config{InsecureSkipVerify: true},
+ DialContext: func(ctx context.Context,
network, addr string) (net.Conn, error) {
+ addr = dialer_ip6 + ":" +
s.httpPort
+ return dialer.DialContext(ctx,
network, addr)
+ },
+ }
+ https4 = &http.Transport{
+ DisableKeepAlives: true,
+ TLSClientConfig:
&tls.Config{InsecureSkipVerify: true},
+ DialContext: func(ctx context.Context,
network, addr string) (net.Conn, error) {
+ addr = dialer_ip4 + ":" +
s.httpsPort
+ return dialer.DialContext(ctx,
network, addr)
+ },
+ }
+ https6 = &http.Transport{
+ DisableKeepAlives: true,
+ TLSClientConfig:
&tls.Config{InsecureSkipVerify: true},
Review Comment:
## Disabled TLS certificate check
InsecureSkipVerify should not be used in production code.
[Show more
details](https://github.com/apache/trafficcontrol/security/code-scanning/192)
##########
traffic_ops/app/bin/checks/ToDSCPCheck.go:
##########
@@ -0,0 +1,646 @@
+package main
+
+import (
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "flag"
+ "io"
+ "io/ioutil"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/apache/trafficcontrol/lib/go-log"
+ tc "github.com/apache/trafficcontrol/lib/go-tc"
+ toclient "github.com/apache/trafficcontrol/traffic_ops/v3-client"
+ "github.com/google/gopacket"
+ "github.com/google/gopacket/layers"
+ "github.com/google/gopacket/pcap"
+)
+
+// Traffic Ops connection params
+const AllowInsecureConnections = false
+const UserAgent = "go/tc-dscp-monitor"
+const UseClientCache = false
+const TrafficOpsRequestTimeout = time.Second * time.Duration(10)
+
+var (
+ protocol int
+ sslflag bool
+ host_header string
+ confInt *string
+ http4 *http.Transport
+ http6 *http.Transport
+ https4 *http.Transport
+ https6 *http.Transport
+ httpClient4 *http.Client
+ httpClient6 *http.Client
+ httpsClient4 *http.Client
+ httpsClient6 *http.Client
+ http_port string
+ https_port string
+ eth_layer layers.Ethernet
+ ip4_layer layers.IPv4
+ ip6_layer layers.IPv6
+ tcp_layer layers.TCP
+ tls_layer layers.TLS
+ payload gopacket.Payload
+)
+
+var connect_timeout = 2000 * time.Millisecond
+var http_timeout = 1500 * time.Millisecond
+var pcap_timeout = 250 * time.Millisecond
+
+var parser *gopacket.DecodingLayerParser =
gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð_layer,
&tcp_layer, &tls_layer, &ip4_layer, &ip6_layer, &payload)
+
+type Config struct {
+ URL string `json:"to_url"`
+ User string `json:"user"`
+ Passwd string `json:"passwd"`
+}
+
+type Server struct {
+ id int
+ cdn string
+ name string
+ fqdn string
+ ip4 string
+ ip6 string
+ httpPort string
+ httpsPort string
+ failcount int
+ status string
+}
+
+func NewServer(id int, name string, status string, f int) Server {
+ server := Server{}
+ server.id = id
+ server.name = name
+ server.status = status
+ server.failcount = f
+ return server
+}
+
+func LoadConfig(file string) (Config, error) {
+ var config Config
+ configFile, err := os.Open(file)
+ defer configFile.Close()
+ if err != nil {
+ return config, err
+ }
+ jsonParser := json.NewDecoder(configFile)
+ jsonParser.Decode(&config)
+ return config, err
+}
+
+func capture(ctx context.Context, s Server, iface *string, ch_dscp chan uint8,
ch_ready chan uint8, ip string, ssl bool) {
+ var pcap_port string
+ if ssl {
+ pcap_port = s.httpsPort
+ } else {
+ pcap_port = s.httpPort
+ }
+
+ pcap_filter := "tcp and src " + ip + " and port " + pcap_port + " and
(tcp[tcpflags] & tcp-push != 0 or ip6[53] & 8 != 0)"
+ log.Debugf("capture() filter='%s'", pcap_filter)
+ if handle, err := pcap.OpenLive(*iface, 1400, false, pcap_timeout); err
!= nil {
+ log.Errorf("capture() pcap.OpenLive() error:", err)
+ } else if err := handle.SetBPFFilter(pcap_filter); err != nil {
+ log.Errorf("capture() handle.SetBPFFilter() error:", err)
+ } else if err := handle.SetDirection(pcap.DirectionIn); err != nil {
+ log.Errorf("capture() handle.SetDirection() error:", err)
+ } else {
+ defer handle.Close()
+ decodedLayers := []gopacket.LayerType{}
+ packetSource := gopacket.NewPacketSource(handle,
handle.LinkType())
+ timer := time.NewTimer(2000 * time.Millisecond)
+ ch_ready <- 1 // signal that capture is ready to proceed
+ pktCount := 0
+ for {
+ select {
+ case <-ctx.Done():
+ handle.Close() // without this, serious fh leak
+ log.Debugf("capture() context cancelled")
+ return
+ case <-timer.C:
+ log.Debugf("capture() timed out before packets
received")
+ ch_dscp <- 254
+ return
+ default:
+ pktCount++
+ packet, err := packetSource.NextPacket()
+ if err == io.EOF {
+ break
+ } else if err != nil {
+ log.Errorf("capture() Error:", err)
+ continue
+ }
+ if sslflag == true && pktCount < 6 {
+ // skip the TLS handshake packets -
they may not provide real DSCP value
+ log.Debugf("Packet #%d: %s", pktCount,
packet)
+ continue
+ }
+ log.Debugf("Packet #%d: %s", pktCount, packet)
+ err = parser.DecodeLayers(packet.Data(),
&decodedLayers)
+ if err != nil {
+ log.Warnf("%s", err)
+ }
+ for _, typ := range decodedLayers {
+ switch typ {
+ case layers.LayerTypeIPv4:
+ ch_dscp <- ip4_layer.TOS
+ return
+ case layers.LayerTypeIPv6:
+ ch_dscp <-
ip6_layer.TrafficClass
+ return
+ }
+ }
+ }
+ }
+ }
+}
+
+func protocol_picker(s Server, check_ip string, host_header string, check_path
string, v6flag bool) (cap_dscp string) {
+ if protocol == 0 || protocol == 2 {
+ // if prot is HTTP and HTTPS, just check HTTP - both is overkill
+ // do HTTP stuff
+ sslflag = false
+ }
+ if protocol == 1 || protocol == 3 {
+ // if a DS is HTTPS *only*...
+ // do HTTPS stuff
+ sslflag = true
+ }
+ log.Debugf("protocol_picker() ssl=%t", sslflag)
+ cap_dscp = request(confInt, s, host_header, check_ip, check_path,
v6flag, sslflag)
+ return
+}
+
+func request(iface *string, s Server, host_header string, ip string,
check_path string, v6 bool, ssl bool) string {
+ var cap_dscp uint8
+ var cap_dscp2 string
+ var url string
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel() // make sure all paths cancel the context to avoid
context leak
+ ch_dscp := make(chan uint8)
+ ch_ready := make(chan uint8)
+ go capture(ctx, s, iface, ch_dscp, ch_ready, ip, ssl)
+ if ssl {
+ url = "https://" + host_header + check_path
+ } else {
+ url = "http://" + host_header + check_path
+ }
+ log.Infof("request() url=%s ip=%s", url, ip)
+ req, err := http.NewRequest("GET", url, nil)
+ if err != nil {
+ log.Errorf("request() http.NewRequest() error:", err)
+ }
+ req.Close = true
+ req.Header.Add("Cache-Control", "only-if-cached")
+ req.Header.Add("User-Agent", UserAgent)
+ ready := <-ch_ready
+ if ready == 1 {
+ log.Debugf("request() received go signal from capture()")
+ }
+ if v6 && ssl == false {
+ resp, err := httpClient6.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient6.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else if v6 == false && ssl == false {
+ resp, err := httpClient4.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient4.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else if v6 && ssl {
+ resp, err := httpsClient6.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient6.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else {
+ resp, err := httpsClient4.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient4.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ }
+ cap_tos, more := <-ch_dscp
+ if more {
+ log.Debugf("request() received tos=%d", cap_tos)
+ cancel() // cancel context to prevent goroutine leak!
+ } else {
+ log.Debugf("request() received all dscp values")
+ cancel() // cancel context to prevent goroutine leak!
+ }
+ if cap_tos == 254 {
+ log.Errorf("request() no valid DSCP mark received")
+ cap_dscp2 = "-1"
+ } else {
+ cap_dscp = cap_tos >> 2
+ cap_dscp2 = strconv.Itoa(int(cap_dscp))
+ log.Debugf("request() received ipv6=%t dscp=%s", v6, cap_dscp2)
+ }
+ return cap_dscp2
+}
+
+func check_result(want string, have string) bool {
+ if want == have {
+ log.Debugf("check_result() success want=%s got=%s", want, have)
+ return true
+ } else if have == "-1" {
+ log.Debugf("check_result() undetermined (ignoring) want=%s
got=CAPTURE_TIMEOUT", want)
+ return true
+ } else {
+ log.Debugf("check_result() failure want=%s got=%s", want, have)
+ return false
+ }
+}
+
+func main() {
+ var (
+ cpath_new string
+ cap_dscp string
+ conf_dscp string
+ xmlID string
+ check_ip4 string
+ check_ip6 string
+ dialer_ip4 string
+ dialer_ip6 string
+ )
+
+ jobStart := time.Now()
+
+ // define default config file path
+ cpath, err := filepath.Abs(filepath.Dir(os.Args[0]))
+ if err != nil {
+ log.Errorf("Config error:", err)
+ os.Exit(1)
+ }
+ cpath_new = strings.Replace(cpath, "/bin/checks",
"/conf/check-config.json", 1)
+
+ // command-line flags
+ confPtr := flag.String("conf", cpath_new, "Config file path")
+ confInt = flag.String("iface", "undef", "Network interface for packet
capture")
+ confName := flag.String("name", "DSCP", "Check name to pass to TO, e.g.
'DSCP'")
+ confInclude := flag.String("host", "undef", "Specific host or regex to
include (optional)")
+ confCdn := flag.String("cdn", "all", "Check specific CDN by name")
+ confExclude := flag.String("exclude", "undef", "Hostname regex to
exclude")
+ confReset := flag.Bool("reset", false, "Reset check values in TO to
'blank' state")
+ confQuiet := flag.Bool("q", false, "Do not send updates to TO")
+ flag.Parse()
+
+ if *confInt == "undef" {
+ log.Errorf("Must specify network interface for packet capture")
+ os.Exit(1)
+ }
+ if *confName == "undef" {
+ log.Errorf("Must specify check name for update to send to TO")
+ os.Exit(1)
+ }
+
+ // load config json
+ config, err := LoadConfig(*confPtr)
+ if err != nil {
+ log.Errorf("Error loading config:", err)
+ os.Exit(1)
+ }
+
+ // connect to TO
+ session, _, err := toclient.LoginWithAgent(
+ config.URL,
+ config.User,
+ config.Passwd,
+ AllowInsecureConnections,
+ UserAgent,
+ UseClientCache,
+ TrafficOpsRequestTimeout)
+ if err != nil {
+ log.Errorf("An error occurred while logging in: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for server details
+ var servers tc.ServersV3Response
+ servers, _, err = session.GetServersWithHdr(nil, nil)
+ if err != nil {
+ log.Errorf("An error occurred while getting servers: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for delivery service details
+ var deliveryservices []tc.DeliveryServiceNullableV30
+ deliveryservices, _, err = session.GetDeliveryServicesV30WithHdr(nil,
nil)
+ if err != nil {
+ log.Errorf("An error occurred while getting delivery services:
%v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for cdn details
+ var cdns []tc.CDN
+ cdns, _, err = session.GetCDNs()
+ if err != nil {
+ log.Errorf("An error occurred while getting cdns: %v\n", err)
+ os.Exit(1)
+ }
+
+ // map cdn to domain name
+ cdn_map := make(map[string]string)
+ for _, cdn := range cdns {
+ cdn_map[cdn.Name] = cdn.DomainName
+ }
+
+ // map ds info
+ ds_matchlist := make(map[string][]tc.DeliveryServiceMatch)
+ ds_types := make(map[string]tc.DSType)
+ for _, ds := range deliveryservices {
+ ds_matchlist[*ds.XMLID] = *ds.MatchList
+ ds_types[*ds.XMLID] = *ds.Type
+ }
+
+ for _, server := range servers.Response {
+ re, err := regexp.Compile("^EDGE.*")
+ if err != nil {
+ log.Errorf("supplied exclusion regex does not
compile:", err)
+ os.Exit(1)
+ }
+ if re.Match([]byte(server.Type)) {
+ serverStart := time.Now()
+ if *confInclude != "undef" {
+ re_inc, err := regexp.Compile(*confInclude)
+ if err != nil {
+ log.Errorf("supplied exclusion regex
does not compile:", err)
+ os.Exit(1)
+ }
+ if !re_inc.MatchString(*server.HostName) {
+ log.Debugf("%s does not match the
provided include regex, skipping", server.HostName)
+ continue
+ }
+ }
+ if *confCdn != "all" && *confCdn != *server.CDNName {
+ log.Debugf("%s is not assigned to the specified
CDN '%s', skipping", server.HostName, *confCdn)
+ continue
+ }
+ if *confExclude != "undef" {
+ re, err := regexp.Compile(*confExclude)
+ if err != nil {
+ log.Errorf("supplied exclusion regex
does not compile:", err)
+ os.Exit(1)
+ }
+ if re.MatchString(*server.HostName) {
+ log.Debugf("%s matches the provided
exclude regex, skipping", server.HostName)
+ continue
+ }
+ }
+ s := NewServer(*server.ID, *server.HostName,
*server.Status, -1)
+ doV4 := false //default
+ doV6 := false //default
+ defaulStatusValue := -1
+ var statusData tc.ServercheckRequestNullable
+ statusData.ID = &s.id
+ statusData.Name = confName
+ statusData.HostName = &s.name
+ statusData.Value = &defaulStatusValue
+ s.fqdn = s.name + "." + *server.DomainName
+ log.Infof("Next server=%s status=%s", s.fqdn, s.status)
+ if (s.status == "REPORTED" || s.status == "ADMIN_DOWN")
&& *confReset != true {
+ s.failcount = 0
+ s.cdn = *server.CDNName
+ s.httpPort = strconv.Itoa(*server.TCPPort)
+ s.httpsPort = strconv.Itoa(*server.HTTPSPort)
+ for _, interf := range server.Interfaces {
+ for _, addr := range interf.IPAddresses
{
+ if s.ip4 == "" &&
strings.Count(addr.Address, ":") == 0 {
+ s.ip4 =
strings.Split(addr.Address, "/")[0]
+ }
+ if s.ip6 == "" &&
strings.Count(addr.Address, ":") > 0 {
+ s.ip6 =
strings.Split(addr.Address, "/")[0]
+ }
+ }
+ }
+ log.Debugf("Ports for %s: http=%s https=%s",
s.name, http_port, https_port)
+ services, _, err :=
session.GetDeliveryServicesByServerV30WithHdr(s.id, nil)
+ if err != nil {
+ log.Errorf("Error getting delivery
services from TO:", err)
+ os.Exit(1)
+ }
+
+ dialer := &net.Dialer{
+ Timeout: connect_timeout,
+ KeepAlive: -1,
+ DualStack: false,
+ FallbackDelay: -1,
+ }
+ if s.ip4 != "" {
+ doV4 = true
+ check_ip4 = s.ip4
+ dialer_ip4 = s.ip4
+ }
+ if s.ip6 != "" {
+ doV6 = true
+ check_ip6 = s.ip6
+ dialer_ip6 = "[" + s.ip6 + "]"
+ }
+
+ // it is necessary to define custom Transports
in order to support
+ // TLS SNI in go. Otherwise, we could have just
had the http client
+ // connect to the IPv4 or IPv6 address, and set
a custom Host header
+ // to ID the test target. SNI must be done this
way, however, so in
+ // order to be consistent, just set up
Transports for all protocol
+ // combinations.
+ http4 = &http.Transport{
+ DisableKeepAlives: true,
+ TLSClientConfig:
&tls.Config{InsecureSkipVerify: true},
+ DialContext: func(ctx context.Context,
network, addr string) (net.Conn, error) {
+ addr = dialer_ip4 + ":" +
s.httpPort
+ return dialer.DialContext(ctx,
network, addr)
+ },
+ }
+ http6 = &http.Transport{
+ DisableKeepAlives: true,
+ TLSClientConfig:
&tls.Config{InsecureSkipVerify: true},
Review Comment:
## Disabled TLS certificate check
InsecureSkipVerify should not be used in production code.
[Show more
details](https://github.com/apache/trafficcontrol/security/code-scanning/190)
##########
traffic_ops/app/bin/checks/ToDSCPCheck.go:
##########
@@ -0,0 +1,646 @@
+package main
+
+import (
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "flag"
+ "io"
+ "io/ioutil"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/apache/trafficcontrol/lib/go-log"
+ tc "github.com/apache/trafficcontrol/lib/go-tc"
+ toclient "github.com/apache/trafficcontrol/traffic_ops/v3-client"
+ "github.com/google/gopacket"
+ "github.com/google/gopacket/layers"
+ "github.com/google/gopacket/pcap"
+)
+
+// Traffic Ops connection params
+const AllowInsecureConnections = false
+const UserAgent = "go/tc-dscp-monitor"
+const UseClientCache = false
+const TrafficOpsRequestTimeout = time.Second * time.Duration(10)
+
+var (
+ protocol int
+ sslflag bool
+ host_header string
+ confInt *string
+ http4 *http.Transport
+ http6 *http.Transport
+ https4 *http.Transport
+ https6 *http.Transport
+ httpClient4 *http.Client
+ httpClient6 *http.Client
+ httpsClient4 *http.Client
+ httpsClient6 *http.Client
+ http_port string
+ https_port string
+ eth_layer layers.Ethernet
+ ip4_layer layers.IPv4
+ ip6_layer layers.IPv6
+ tcp_layer layers.TCP
+ tls_layer layers.TLS
+ payload gopacket.Payload
+)
+
+var connect_timeout = 2000 * time.Millisecond
+var http_timeout = 1500 * time.Millisecond
+var pcap_timeout = 250 * time.Millisecond
+
+var parser *gopacket.DecodingLayerParser =
gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð_layer,
&tcp_layer, &tls_layer, &ip4_layer, &ip6_layer, &payload)
+
+type Config struct {
+ URL string `json:"to_url"`
+ User string `json:"user"`
+ Passwd string `json:"passwd"`
+}
+
+type Server struct {
+ id int
+ cdn string
+ name string
+ fqdn string
+ ip4 string
+ ip6 string
+ httpPort string
+ httpsPort string
+ failcount int
+ status string
+}
+
+func NewServer(id int, name string, status string, f int) Server {
+ server := Server{}
+ server.id = id
+ server.name = name
+ server.status = status
+ server.failcount = f
+ return server
+}
+
+func LoadConfig(file string) (Config, error) {
+ var config Config
+ configFile, err := os.Open(file)
+ defer configFile.Close()
+ if err != nil {
+ return config, err
+ }
+ jsonParser := json.NewDecoder(configFile)
+ jsonParser.Decode(&config)
+ return config, err
+}
+
+func capture(ctx context.Context, s Server, iface *string, ch_dscp chan uint8,
ch_ready chan uint8, ip string, ssl bool) {
+ var pcap_port string
+ if ssl {
+ pcap_port = s.httpsPort
+ } else {
+ pcap_port = s.httpPort
+ }
+
+ pcap_filter := "tcp and src " + ip + " and port " + pcap_port + " and
(tcp[tcpflags] & tcp-push != 0 or ip6[53] & 8 != 0)"
+ log.Debugf("capture() filter='%s'", pcap_filter)
+ if handle, err := pcap.OpenLive(*iface, 1400, false, pcap_timeout); err
!= nil {
+ log.Errorf("capture() pcap.OpenLive() error:", err)
+ } else if err := handle.SetBPFFilter(pcap_filter); err != nil {
+ log.Errorf("capture() handle.SetBPFFilter() error:", err)
+ } else if err := handle.SetDirection(pcap.DirectionIn); err != nil {
+ log.Errorf("capture() handle.SetDirection() error:", err)
+ } else {
+ defer handle.Close()
+ decodedLayers := []gopacket.LayerType{}
+ packetSource := gopacket.NewPacketSource(handle,
handle.LinkType())
+ timer := time.NewTimer(2000 * time.Millisecond)
+ ch_ready <- 1 // signal that capture is ready to proceed
+ pktCount := 0
+ for {
+ select {
+ case <-ctx.Done():
+ handle.Close() // without this, serious fh leak
+ log.Debugf("capture() context cancelled")
+ return
+ case <-timer.C:
+ log.Debugf("capture() timed out before packets
received")
+ ch_dscp <- 254
+ return
+ default:
+ pktCount++
+ packet, err := packetSource.NextPacket()
+ if err == io.EOF {
+ break
+ } else if err != nil {
+ log.Errorf("capture() Error:", err)
+ continue
+ }
+ if sslflag == true && pktCount < 6 {
+ // skip the TLS handshake packets -
they may not provide real DSCP value
+ log.Debugf("Packet #%d: %s", pktCount,
packet)
+ continue
+ }
+ log.Debugf("Packet #%d: %s", pktCount, packet)
+ err = parser.DecodeLayers(packet.Data(),
&decodedLayers)
+ if err != nil {
+ log.Warnf("%s", err)
+ }
+ for _, typ := range decodedLayers {
+ switch typ {
+ case layers.LayerTypeIPv4:
+ ch_dscp <- ip4_layer.TOS
+ return
+ case layers.LayerTypeIPv6:
+ ch_dscp <-
ip6_layer.TrafficClass
+ return
+ }
+ }
+ }
+ }
+ }
+}
+
+func protocol_picker(s Server, check_ip string, host_header string, check_path
string, v6flag bool) (cap_dscp string) {
+ if protocol == 0 || protocol == 2 {
+ // if prot is HTTP and HTTPS, just check HTTP - both is overkill
+ // do HTTP stuff
+ sslflag = false
+ }
+ if protocol == 1 || protocol == 3 {
+ // if a DS is HTTPS *only*...
+ // do HTTPS stuff
+ sslflag = true
+ }
+ log.Debugf("protocol_picker() ssl=%t", sslflag)
+ cap_dscp = request(confInt, s, host_header, check_ip, check_path,
v6flag, sslflag)
+ return
+}
+
+func request(iface *string, s Server, host_header string, ip string,
check_path string, v6 bool, ssl bool) string {
+ var cap_dscp uint8
+ var cap_dscp2 string
+ var url string
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel() // make sure all paths cancel the context to avoid
context leak
+ ch_dscp := make(chan uint8)
+ ch_ready := make(chan uint8)
+ go capture(ctx, s, iface, ch_dscp, ch_ready, ip, ssl)
+ if ssl {
+ url = "https://" + host_header + check_path
+ } else {
+ url = "http://" + host_header + check_path
+ }
+ log.Infof("request() url=%s ip=%s", url, ip)
+ req, err := http.NewRequest("GET", url, nil)
+ if err != nil {
+ log.Errorf("request() http.NewRequest() error:", err)
+ }
+ req.Close = true
+ req.Header.Add("Cache-Control", "only-if-cached")
+ req.Header.Add("User-Agent", UserAgent)
+ ready := <-ch_ready
+ if ready == 1 {
+ log.Debugf("request() received go signal from capture()")
+ }
+ if v6 && ssl == false {
+ resp, err := httpClient6.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient6.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else if v6 == false && ssl == false {
+ resp, err := httpClient4.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient4.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else if v6 && ssl {
+ resp, err := httpsClient6.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient6.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ } else {
+ resp, err := httpsClient4.Do(req)
+ if err != nil {
+ log.Errorf("request() httpClient4.Do() error:", err)
+ } else {
+ defer resp.Body.Close()
+ io.Copy(ioutil.Discard, resp.Body)
+ }
+ }
+ cap_tos, more := <-ch_dscp
+ if more {
+ log.Debugf("request() received tos=%d", cap_tos)
+ cancel() // cancel context to prevent goroutine leak!
+ } else {
+ log.Debugf("request() received all dscp values")
+ cancel() // cancel context to prevent goroutine leak!
+ }
+ if cap_tos == 254 {
+ log.Errorf("request() no valid DSCP mark received")
+ cap_dscp2 = "-1"
+ } else {
+ cap_dscp = cap_tos >> 2
+ cap_dscp2 = strconv.Itoa(int(cap_dscp))
+ log.Debugf("request() received ipv6=%t dscp=%s", v6, cap_dscp2)
+ }
+ return cap_dscp2
+}
+
+func check_result(want string, have string) bool {
+ if want == have {
+ log.Debugf("check_result() success want=%s got=%s", want, have)
+ return true
+ } else if have == "-1" {
+ log.Debugf("check_result() undetermined (ignoring) want=%s
got=CAPTURE_TIMEOUT", want)
+ return true
+ } else {
+ log.Debugf("check_result() failure want=%s got=%s", want, have)
+ return false
+ }
+}
+
+func main() {
+ var (
+ cpath_new string
+ cap_dscp string
+ conf_dscp string
+ xmlID string
+ check_ip4 string
+ check_ip6 string
+ dialer_ip4 string
+ dialer_ip6 string
+ )
+
+ jobStart := time.Now()
+
+ // define default config file path
+ cpath, err := filepath.Abs(filepath.Dir(os.Args[0]))
+ if err != nil {
+ log.Errorf("Config error:", err)
+ os.Exit(1)
+ }
+ cpath_new = strings.Replace(cpath, "/bin/checks",
"/conf/check-config.json", 1)
+
+ // command-line flags
+ confPtr := flag.String("conf", cpath_new, "Config file path")
+ confInt = flag.String("iface", "undef", "Network interface for packet
capture")
+ confName := flag.String("name", "DSCP", "Check name to pass to TO, e.g.
'DSCP'")
+ confInclude := flag.String("host", "undef", "Specific host or regex to
include (optional)")
+ confCdn := flag.String("cdn", "all", "Check specific CDN by name")
+ confExclude := flag.String("exclude", "undef", "Hostname regex to
exclude")
+ confReset := flag.Bool("reset", false, "Reset check values in TO to
'blank' state")
+ confQuiet := flag.Bool("q", false, "Do not send updates to TO")
+ flag.Parse()
+
+ if *confInt == "undef" {
+ log.Errorf("Must specify network interface for packet capture")
+ os.Exit(1)
+ }
+ if *confName == "undef" {
+ log.Errorf("Must specify check name for update to send to TO")
+ os.Exit(1)
+ }
+
+ // load config json
+ config, err := LoadConfig(*confPtr)
+ if err != nil {
+ log.Errorf("Error loading config:", err)
+ os.Exit(1)
+ }
+
+ // connect to TO
+ session, _, err := toclient.LoginWithAgent(
+ config.URL,
+ config.User,
+ config.Passwd,
+ AllowInsecureConnections,
+ UserAgent,
+ UseClientCache,
+ TrafficOpsRequestTimeout)
+ if err != nil {
+ log.Errorf("An error occurred while logging in: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for server details
+ var servers tc.ServersV3Response
+ servers, _, err = session.GetServersWithHdr(nil, nil)
+ if err != nil {
+ log.Errorf("An error occurred while getting servers: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for delivery service details
+ var deliveryservices []tc.DeliveryServiceNullableV30
+ deliveryservices, _, err = session.GetDeliveryServicesV30WithHdr(nil,
nil)
+ if err != nil {
+ log.Errorf("An error occurred while getting delivery services:
%v\n", err)
+ os.Exit(1)
+ }
+
+ // Make TO API call for cdn details
+ var cdns []tc.CDN
+ cdns, _, err = session.GetCDNs()
+ if err != nil {
+ log.Errorf("An error occurred while getting cdns: %v\n", err)
+ os.Exit(1)
+ }
+
+ // map cdn to domain name
+ cdn_map := make(map[string]string)
+ for _, cdn := range cdns {
+ cdn_map[cdn.Name] = cdn.DomainName
+ }
+
+ // map ds info
+ ds_matchlist := make(map[string][]tc.DeliveryServiceMatch)
+ ds_types := make(map[string]tc.DSType)
+ for _, ds := range deliveryservices {
+ ds_matchlist[*ds.XMLID] = *ds.MatchList
+ ds_types[*ds.XMLID] = *ds.Type
+ }
+
+ for _, server := range servers.Response {
+ re, err := regexp.Compile("^EDGE.*")
+ if err != nil {
+ log.Errorf("supplied exclusion regex does not
compile:", err)
+ os.Exit(1)
+ }
+ if re.Match([]byte(server.Type)) {
+ serverStart := time.Now()
+ if *confInclude != "undef" {
+ re_inc, err := regexp.Compile(*confInclude)
+ if err != nil {
+ log.Errorf("supplied exclusion regex
does not compile:", err)
+ os.Exit(1)
+ }
+ if !re_inc.MatchString(*server.HostName) {
+ log.Debugf("%s does not match the
provided include regex, skipping", server.HostName)
+ continue
+ }
+ }
+ if *confCdn != "all" && *confCdn != *server.CDNName {
+ log.Debugf("%s is not assigned to the specified
CDN '%s', skipping", server.HostName, *confCdn)
+ continue
+ }
+ if *confExclude != "undef" {
+ re, err := regexp.Compile(*confExclude)
+ if err != nil {
+ log.Errorf("supplied exclusion regex
does not compile:", err)
+ os.Exit(1)
+ }
+ if re.MatchString(*server.HostName) {
+ log.Debugf("%s matches the provided
exclude regex, skipping", server.HostName)
+ continue
+ }
+ }
+ s := NewServer(*server.ID, *server.HostName,
*server.Status, -1)
+ doV4 := false //default
+ doV6 := false //default
+ defaulStatusValue := -1
+ var statusData tc.ServercheckRequestNullable
+ statusData.ID = &s.id
+ statusData.Name = confName
+ statusData.HostName = &s.name
+ statusData.Value = &defaulStatusValue
+ s.fqdn = s.name + "." + *server.DomainName
+ log.Infof("Next server=%s status=%s", s.fqdn, s.status)
+ if (s.status == "REPORTED" || s.status == "ADMIN_DOWN")
&& *confReset != true {
+ s.failcount = 0
+ s.cdn = *server.CDNName
+ s.httpPort = strconv.Itoa(*server.TCPPort)
+ s.httpsPort = strconv.Itoa(*server.HTTPSPort)
+ for _, interf := range server.Interfaces {
+ for _, addr := range interf.IPAddresses
{
+ if s.ip4 == "" &&
strings.Count(addr.Address, ":") == 0 {
+ s.ip4 =
strings.Split(addr.Address, "/")[0]
+ }
+ if s.ip6 == "" &&
strings.Count(addr.Address, ":") > 0 {
+ s.ip6 =
strings.Split(addr.Address, "/")[0]
+ }
+ }
+ }
+ log.Debugf("Ports for %s: http=%s https=%s",
s.name, http_port, https_port)
+ services, _, err :=
session.GetDeliveryServicesByServerV30WithHdr(s.id, nil)
+ if err != nil {
+ log.Errorf("Error getting delivery
services from TO:", err)
+ os.Exit(1)
+ }
+
+ dialer := &net.Dialer{
+ Timeout: connect_timeout,
+ KeepAlive: -1,
+ DualStack: false,
+ FallbackDelay: -1,
+ }
+ if s.ip4 != "" {
+ doV4 = true
+ check_ip4 = s.ip4
+ dialer_ip4 = s.ip4
+ }
+ if s.ip6 != "" {
+ doV6 = true
+ check_ip6 = s.ip6
+ dialer_ip6 = "[" + s.ip6 + "]"
+ }
+
+ // it is necessary to define custom Transports
in order to support
+ // TLS SNI in go. Otherwise, we could have just
had the http client
+ // connect to the IPv4 or IPv6 address, and set
a custom Host header
+ // to ID the test target. SNI must be done this
way, however, so in
+ // order to be consistent, just set up
Transports for all protocol
+ // combinations.
+ http4 = &http.Transport{
+ DisableKeepAlives: true,
+ TLSClientConfig:
&tls.Config{InsecureSkipVerify: true},
+ DialContext: func(ctx context.Context,
network, addr string) (net.Conn, error) {
+ addr = dialer_ip4 + ":" +
s.httpPort
+ return dialer.DialContext(ctx,
network, addr)
+ },
+ }
+ http6 = &http.Transport{
+ DisableKeepAlives: true,
+ TLSClientConfig:
&tls.Config{InsecureSkipVerify: true},
+ DialContext: func(ctx context.Context,
network, addr string) (net.Conn, error) {
+ addr = dialer_ip6 + ":" +
s.httpPort
+ return dialer.DialContext(ctx,
network, addr)
+ },
+ }
+ https4 = &http.Transport{
+ DisableKeepAlives: true,
+ TLSClientConfig:
&tls.Config{InsecureSkipVerify: true},
Review Comment:
## Disabled TLS certificate check
InsecureSkipVerify should not be used in production code.
[Show more
details](https://github.com/apache/trafficcontrol/security/code-scanning/191)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]