The following issues were found

collectors/python.d.plugin/go_expvar/go_expvar.chart.py
17 issues
Unable to import 'bases.FrameworkServices.UrlService'
Error

Line: 11 Column: 1

              import json
from collections import namedtuple

from bases.FrameworkServices.UrlService import UrlService

MEMSTATS_ORDER = [
    'memstats_heap',
    'memstats_stack',
    'memstats_mspan',

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # -*- coding: utf-8 -*-
# Description: go_expvar netdata python.d module
# Author: Jan Kral (kralewitz)
# SPDX-License-Identifier: GPL-3.0-or-later

from __future__ import division

import json
from collections import namedtuple

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 86 Column: 1

              )


def flatten(d, top='', sep='.'):
    items = []
    for key, val in d.items():
        nkey = top + sep + key if top else key
        if isinstance(val, dict):
            items.extend(flatten(val, nkey, sep=sep).items())

            

Reported by Pylint.

Argument name "d" doesn't conform to snake_case naming style
Error

Line: 86 Column: 1

              )


def flatten(d, top='', sep='.'):
    items = []
    for key, val in d.items():
        nkey = top + sep + key if top else key
        if isinstance(val, dict):
            items.extend(flatten(val, nkey, sep=sep).items())

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 97 Column: 1

                  return dict(items)


class Service(UrlService):
    def __init__(self, configuration=None, name=None):
        UrlService.__init__(self, configuration=configuration, name=name)
        # if memstats collection is enabled, add the charts and their order
        if self.configuration.get('collect_memstats'):
            self.definitions = dict(MEMSTATS_CHARTS)

            

Reported by Pylint.

Missing class docstring
Error

Line: 97 Column: 1

                  return dict(items)


class Service(UrlService):
    def __init__(self, configuration=None, name=None):
        UrlService.__init__(self, configuration=configuration, name=name)
        # if memstats collection is enabled, add the charts and their order
        if self.configuration.get('collect_memstats'):
            self.definitions = dict(MEMSTATS_CHARTS)

            

Reported by Pylint.

Line too long (116/100)
Error

Line: 117 Column: 1

                      """
        Check if the module can collect data:
        1) At least one JOB configuration has to be specified
        2) The JOB configuration needs to define the URL and either collect_memstats must be enabled or at least one
           extra_chart must be defined.

        The configuration and URL check is provided by the UrlService class.
        """


            

Reported by Pylint.

Line too long (102/100)
Error

Line: 123 Column: 1

                      The configuration and URL check is provided by the UrlService class.
        """

        if not (self.configuration.get('extra_charts') or self.configuration.get('collect_memstats')):
            self.error('Memstats collection is disabled and no extra_charts are defined, disabling module.')
            return False

        return UrlService.check(self)


            

Reported by Pylint.

Line too long (108/100)
Error

Line: 124 Column: 1

                      """

        if not (self.configuration.get('extra_charts') or self.configuration.get('collect_memstats')):
            self.error('Memstats collection is disabled and no extra_charts are defined, disabling module.')
            return False

        return UrlService.check(self)

    def _parse_extra_charts_config(self, extra_charts_config):

            

Reported by Pylint.

Line too long (109/100)
Error

Line: 163 Column: 1

                              line_id = line.get('id')

                if not all([ev_key, ev_type, line_id]):
                    self.info('Line missing expvar_key, expvar_type, or line_id, skipping: {0}'.format(line))
                    continue

                if ev_type not in ['int', 'float']:
                    self.info('Unsupported expvar_type "{0}". Must be "int" or "float"'.format(ev_type))
                    continue

            

Reported by Pylint.

aclk/aclk_tx_msgs.c
17 issues
snprintf - If format strings can be influenced by an attacker, they can be exploited, and note that sprintf variations do not always \0-terminate
Security

Line: 34 Column: 5 CWE codes: 134
Suggestion: Use a constant for the format specification

              #ifdef ACLK_LOG_CONVERSATION_DIR
#define FN_MAX_LEN 1024
    char filename[FN_MAX_LEN];
    snprintf(filename, FN_MAX_LEN, ACLK_LOG_CONVERSATION_DIR "/%010d-tx.json", ACLK_GET_CONV_LOG_NEXT());
    json_object_to_file_ext(filename, msg, JSON_C_TO_STRING_PRETTY);
#endif
}

uint16_t aclk_send_bin_message_subtopic_pid(mqtt_wss_client client, char *msg, size_t msg_len, enum aclk_topics subtopic, const char *msgname)

            

Reported by FlawFinder.

snprintf - If format strings can be influenced by an attacker, they can be exploited, and note that sprintf variations do not always \0-terminate
Security

Line: 59 Column: 5 CWE codes: 134
Suggestion: Use a constant for the format specification

              #ifdef ACLK_LOG_CONVERSATION_DIR
#define FN_MAX_LEN 1024
    char filename[FN_MAX_LEN];
    snprintf(filename, FN_MAX_LEN, ACLK_LOG_CONVERSATION_DIR "/%010d-tx-%s.bin", ACLK_GET_CONV_LOG_NEXT(), msgname);
    FILE *fptr;
    if (fptr = fopen(filename,"w")) {
        fwrite(msg, msg_len, 1, fptr);
        fclose(fptr);
    }

            

Reported by FlawFinder.

snprintf - If format strings can be influenced by an attacker, they can be exploited, and note that sprintf variations do not always \0-terminate
Security

Line: 88 Column: 5 CWE codes: 134
Suggestion: Use a constant for the format specification

              #ifdef ACLK_LOG_CONVERSATION_DIR
#define FN_MAX_LEN 1024
    char filename[FN_MAX_LEN];
    snprintf(filename, FN_MAX_LEN, ACLK_LOG_CONVERSATION_DIR "/%010d-tx.json", ACLK_GET_CONV_LOG_NEXT());
    json_object_to_file_ext(filename, msg, JSON_C_TO_STRING_PRETTY);
#endif
    return packet_id;
}


            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 33 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              #endif
#ifdef ACLK_LOG_CONVERSATION_DIR
#define FN_MAX_LEN 1024
    char filename[FN_MAX_LEN];
    snprintf(filename, FN_MAX_LEN, ACLK_LOG_CONVERSATION_DIR "/%010d-tx.json", ACLK_GET_CONV_LOG_NEXT());
    json_object_to_file_ext(filename, msg, JSON_C_TO_STRING_PRETTY);
#endif
}


            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 58 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              #endif
#ifdef ACLK_LOG_CONVERSATION_DIR
#define FN_MAX_LEN 1024
    char filename[FN_MAX_LEN];
    snprintf(filename, FN_MAX_LEN, ACLK_LOG_CONVERSATION_DIR "/%010d-tx-%s.bin", ACLK_GET_CONV_LOG_NEXT(), msgname);
    FILE *fptr;
    if (fptr = fopen(filename,"w")) {
        fwrite(msg, msg_len, 1, fptr);
        fclose(fptr);

            

Reported by FlawFinder.

fopen - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 61 Column: 16 CWE codes: 362

                  char filename[FN_MAX_LEN];
    snprintf(filename, FN_MAX_LEN, ACLK_LOG_CONVERSATION_DIR "/%010d-tx-%s.bin", ACLK_GET_CONV_LOG_NEXT(), msgname);
    FILE *fptr;
    if (fptr = fopen(filename,"w")) {
        fwrite(msg, msg_len, 1, fptr);
        fclose(fptr);
    }
#endif


            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 87 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              #endif
#ifdef ACLK_LOG_CONVERSATION_DIR
#define FN_MAX_LEN 1024
    char filename[FN_MAX_LEN];
    snprintf(filename, FN_MAX_LEN, ACLK_LOG_CONVERSATION_DIR "/%010d-tx.json", ACLK_GET_CONV_LOG_NEXT());
    json_object_to_file_ext(filename, msg, JSON_C_TO_STRING_PRETTY);
#endif
    return packet_id;
}

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 136 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

              
    full_msg = mallocz(len + strlen(V2_BIN_PAYLOAD_SEPARATOR) + payload_len);

    memcpy(full_msg, str, len);
    memcpy(&full_msg[len], V2_BIN_PAYLOAD_SEPARATOR, strlen(V2_BIN_PAYLOAD_SEPARATOR));
    len += strlen(V2_BIN_PAYLOAD_SEPARATOR);
    memcpy(&full_msg[len], payload, payload_len);
    len += payload_len;


            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 137 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  full_msg = mallocz(len + strlen(V2_BIN_PAYLOAD_SEPARATOR) + payload_len);

    memcpy(full_msg, str, len);
    memcpy(&full_msg[len], V2_BIN_PAYLOAD_SEPARATOR, strlen(V2_BIN_PAYLOAD_SEPARATOR));
    len += strlen(V2_BIN_PAYLOAD_SEPARATOR);
    memcpy(&full_msg[len], payload, payload_len);
    len += payload_len;

/* TODO

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 139 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  memcpy(full_msg, str, len);
    memcpy(&full_msg[len], V2_BIN_PAYLOAD_SEPARATOR, strlen(V2_BIN_PAYLOAD_SEPARATOR));
    len += strlen(V2_BIN_PAYLOAD_SEPARATOR);
    memcpy(&full_msg[len], payload, payload_len);
    len += payload_len;

/* TODO
#ifdef ACLK_LOG_CONVERSATION_DIR
#define FN_MAX_LEN 1024

            

Reported by FlawFinder.

collectors/cgroups.plugin/cgroup-network.c
16 issues
chroot - chroot can be very helpful, but is hard to use correctly
Security

Line: 273 Column: 12 CWE codes: 250 22
Suggestion: Make sure the program immediately chdir("/"), closes file descriptors, and drops root privileges, and that all necessary files (and no more!) are in the new root

                      if(fchdir(root_fd) < 0)
            error("Cannot fchdir() to pid %d root directory", (int)pid);

        if(chroot(".") < 0)
            error("Cannot chroot() to pid %d root directory", (int)pid);

        close(root_fd);
    }


            

Reported by FlawFinder.

getenv - Environment variables are untrustable input if they can be set by an attacker. They can have any content and length, and the same variable can be set more than once
Security

Line: 657 Column: 38 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

                  // ------------------------------------------------------------------------
    // make sure NETDATA_HOST_PREFIX is safe

    netdata_configured_host_prefix = getenv("NETDATA_HOST_PREFIX");
    if(verify_netdata_host_prefix() == -1) exit(1);

    if(netdata_configured_host_prefix[0] != '\0' && verify_path(netdata_configured_host_prefix) == -1)
        fatal("invalid NETDATA_HOST_PREFIX '%s'", netdata_configured_host_prefix);


            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 12 Column: 1 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              #include <sched.h>
#endif

char environment_variable2[FILENAME_MAX + 50] = "";
char *environment[] = {
        "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin",
        environment_variable2,
        NULL
};

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 66 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              unsigned int read_iface_iflink(const char *prefix, const char *iface) {
    if(!prefix) prefix = "";

    char filename[FILENAME_MAX + 1];
    snprintfz(filename, FILENAME_MAX, "%s/sys/class/net/%s/iflink", prefix, iface);

    unsigned long long iflink = 0;
    int ret = read_single_number_file(filename, &iflink);
    if(ret) error("Cannot read '%s'.", filename);

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 79 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              unsigned int read_iface_ifindex(const char *prefix, const char *iface) {
    if(!prefix) prefix = "";

    char filename[FILENAME_MAX + 1];
    snprintfz(filename, FILENAME_MAX, "%s/sys/class/net/%s/ifindex", prefix, iface);

    unsigned long long ifindex = 0;
    int ret = read_single_number_file(filename, &ifindex);
    if(ret) error("Cannot read '%s'.", filename);

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 93 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                  if(!prefix) prefix = "";

    procfile *ff = NULL;
    char filename[FILENAME_MAX + 1];

    snprintfz(filename, FILENAME_MAX, "%s%s", prefix, (*prefix)?"/proc/1/net/dev":"/proc/net/dev");

#ifdef NETDATA_INTERNAL_CHECKS
    info("parsing '%s'", filename);

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 203 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              int proc_pid_fd(const char *prefix, const char *ns, pid_t pid) {
    if(!prefix) prefix = "";

    char filename[FILENAME_MAX + 1];
    snprintfz(filename, FILENAME_MAX, "%s/proc/%d/%s", prefix, (int)pid, ns);
    int fd = open(filename, O_RDONLY);

    if(fd == -1)
        error("Cannot open proc_pid_fd() file '%s'", filename);

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 205 Column: 14 CWE codes: 362

              
    char filename[FILENAME_MAX + 1];
    snprintfz(filename, FILENAME_MAX, "%s/proc/%d/%s", prefix, (int)pid, ns);
    int fd = open(filename, O_RDONLY);

    if(fd == -1)
        error("Cannot open proc_pid_fd() file '%s'", filename);

    return fd;

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 312 Column: 14 CWE codes: 362

              }

pid_t read_pid_from_cgroup_file(const char *filename) {
    int fd = open(filename, procfile_open_flags);
    if(fd == -1) {
        error("Cannot open pid_from_cgroup() file '%s'.", filename);
        return 0;
    }


            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 324 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                      return 0;
    }

    char buffer[100 + 1];
    pid_t pid = 0;
    char *s;
    while((s = fgets(buffer, 100, fp))) {
        buffer[100] = '\0';
        pid = atoi(s);

            

Reported by FlawFinder.

collectors/python.d.plugin/tomcat/tomcat.chart.py
16 issues
Unable to import 'bases.FrameworkServices.UrlService'
Error

Line: 10 Column: 1

              import re
import xml.etree.ElementTree as ET

from bases.FrameworkServices.UrlService import UrlService

MiB = 1 << 20

# Regex fix for Tomcat single quote XML attributes
# affecting Tomcat < 8.5.24 & 9.0.2 running with Java > 9

            

Reported by Pylint.

Using xml.etree.ElementTree.fromstring to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree.fromstring with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called
Security blacklist

Line: 108
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b313-b320-xml-bad-elementtree

              
    def xml_parse(self, data):
        try:
            return ET.fromstring(data)
        except ET.ParseError:
            self.debug('%s is not a valid XML page. Please add "?XML=true" to tomcat status page.' % self.url)
            return None

    def xml_single_quote_fix_parse(self, data):

            

Reported by Bandit.

Attribute '_manager' defined outside __init__
Error

Line: 118 Column: 9

                      return self.xml_parse(data)

    def check(self):
        self._manager = self._build_manager()

        raw_data = self._get_raw_data()
        if not raw_data:
            return False


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # -*- coding: utf-8 -*-
# Description: tomcat netdata python.d module
# Author: Pawel Krupa (paulfantom)
# Author: Wei He (Wing924)
# SPDX-License-Identifier: GPL-3.0-or-later

import re
import xml.etree.ElementTree as ET


            

Reported by Pylint.

Using xml.etree.ElementTree to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.
Security blacklist

Line: 8
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b405-import-xml-etree

              # SPDX-License-Identifier: GPL-3.0-or-later

import re
import xml.etree.ElementTree as ET

from bases.FrameworkServices.UrlService import UrlService

MiB = 1 << 20


            

Reported by Bandit.

Constant name "MiB" doesn't conform to UPPER_CASE naming style
Error

Line: 12 Column: 1

              
from bases.FrameworkServices.UrlService import UrlService

MiB = 1 << 20

# Regex fix for Tomcat single quote XML attributes
# affecting Tomcat < 8.5.24 & 9.0.2 running with Java > 9
# cf. https://bz.apache.org/bugzilla/show_bug.cgi?id=61603
single_quote_regex = re.compile(r"='([^']+)'([^']+)''")

            

Reported by Pylint.

Line too long (104/100)
Error

Line: 46 Column: 1

                      ]
    },
    'processing_time': {
        'options': [None, 'processing time', 'seconds', 'statistics', 'tomcat.processing_time', 'area'],
        'lines': [
            ['processingTime', 'processing time', 'incremental', 1, 1000]
        ]
    },
    'threads': {

            

Reported by Pylint.

Missing class docstring
Error

Line: 97 Column: 1

              }


class Service(UrlService):
    def __init__(self, configuration=None, name=None):
        UrlService.__init__(self, configuration=configuration, name=name)
        self.order = ORDER
        self.definitions = CHARTS
        self.url = self.configuration.get('url', 'http://127.0.0.1:8080/manager/status?XML=true')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 106 Column: 5

                      self.connector_name = self.configuration.get('connector_name', None)
        self.parse = self.xml_parse

    def xml_parse(self, data):
        try:
            return ET.fromstring(data)
        except ET.ParseError:
            self.debug('%s is not a valid XML page. Please add "?XML=true" to tomcat status page.' % self.url)
            return None

            

Reported by Pylint.

Line too long (110/100)
Error

Line: 110 Column: 1

                      try:
            return ET.fromstring(data)
        except ET.ParseError:
            self.debug('%s is not a valid XML page. Please add "?XML=true" to tomcat status page.' % self.url)
            return None

    def xml_single_quote_fix_parse(self, data):
        data = single_quote_regex.sub(r"='\g<1>\g<2>'", data)
        return self.xml_parse(data)

            

Reported by Pylint.

streaming/receiver.c
16 issues
sprintf - Does not check for buffer overflows
Security

Line: 392 Column: 9 CWE codes: 120
Suggestion: Use sprintf_s, snprintf, or vsnprintf

                  char initial_response[HTTP_HEADER_SIZE];
    if (rpt->stream_version > 1) {
        info("STREAM %s [receive from [%s]:%s]: Netdata is using the stream version %u.", rpt->host->hostname, rpt->client_ip, rpt->client_port, rpt->stream_version);
        sprintf(initial_response, "%s%u", START_STREAMING_PROMPT_VN, rpt->stream_version);
    } else if (rpt->stream_version == 1) {
        info("STREAM %s [receive from [%s]:%s]: Netdata is using the stream version %u.", rpt->host->hostname, rpt->client_ip, rpt->client_port, rpt->stream_version);
        sprintf(initial_response, "%s", START_STREAMING_PROMPT_V2);
    } else {
        info("STREAM %s [receive from [%s]:%s]: Netdata is using first stream protocol.", rpt->host->hostname, rpt->client_ip, rpt->client_port);

            

Reported by FlawFinder.

sprintf - Does not check for buffer overflows
Security

Line: 395 Column: 9 CWE codes: 120
Suggestion: Use sprintf_s, snprintf, or vsnprintf

                      sprintf(initial_response, "%s%u", START_STREAMING_PROMPT_VN, rpt->stream_version);
    } else if (rpt->stream_version == 1) {
        info("STREAM %s [receive from [%s]:%s]: Netdata is using the stream version %u.", rpt->host->hostname, rpt->client_ip, rpt->client_port, rpt->stream_version);
        sprintf(initial_response, "%s", START_STREAMING_PROMPT_V2);
    } else {
        info("STREAM %s [receive from [%s]:%s]: Netdata is using first stream protocol.", rpt->host->hostname, rpt->client_ip, rpt->client_port);
        sprintf(initial_response, "%s", START_STREAMING_PROMPT);
    }
    debug(D_STREAM, "Initial response to %s: %s", rpt->client_ip, initial_response);

            

Reported by FlawFinder.

sprintf - Does not check for buffer overflows
Security

Line: 398 Column: 9 CWE codes: 120
Suggestion: Use sprintf_s, snprintf, or vsnprintf

                      sprintf(initial_response, "%s", START_STREAMING_PROMPT_V2);
    } else {
        info("STREAM %s [receive from [%s]:%s]: Netdata is using first stream protocol.", rpt->host->hostname, rpt->client_ip, rpt->client_port);
        sprintf(initial_response, "%s", START_STREAMING_PROMPT);
    }
    debug(D_STREAM, "Initial response to %s: %s", rpt->client_ip, initial_response);
    #ifdef ENABLE_HTTPS
    rpt->host->stream_ssl.conn = rpt->ssl.conn;
    rpt->host->stream_ssl.flags = rpt->ssl.flags;

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 79 Column: 9 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                          info("STREAM %s from %s: Checking for gaps... remote=%ld local=%ld..%ld slew=%ld  %ld-sec gap",
                 host->hostname, cd->cmd, remote_time, prev, now, remote_time - now, gap);
        }
        char message[128];
        sprintf(message,"REPLICATE %ld %ld\n", remote_time - gap, remote_time);
        int ret;
#ifdef ENABLE_HTTPS
        SSL *conn = host->stream_ssl.conn ;
        if(conn && !host->stream_ssl.flags) {

            

Reported by FlawFinder.

sprintf - Does not check for buffer overflows
Security

Line: 80 Column: 9 CWE codes: 120
Suggestion: Use sprintf_s, snprintf, or vsnprintf

                               host->hostname, cd->cmd, remote_time, prev, now, remote_time - now, gap);
        }
        char message[128];
        sprintf(message,"REPLICATE %ld %ld\n", remote_time - gap, remote_time);
        int ret;
#ifdef ENABLE_HTTPS
        SSL *conn = host->stream_ssl.conn ;
        if(conn && !host->stream_ssl.flags) {
            ret = SSL_write(conn, message, strlen(message));

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 158 Column: 9 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                      }
        // Don't treat SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE differently on blocking socket
        u_long err;
        char buf[256];
        while ((err = ERR_get_error()) != 0) {
            ERR_error_string_n(err, buf, sizeof(buf));
            error("STREAM %s [receive from %s] ssl error: %s", r->hostname, r->client_ip, buf);
        }
        return 1;

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 389 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                  snprintfz(cd.cmd,          PLUGINSD_CMD_MAX, "%s:%s", rpt->client_ip, rpt->client_port);

    info("STREAM %s [receive from [%s]:%s]: initializing communication...", rpt->host->hostname, rpt->client_ip, rpt->client_port);
    char initial_response[HTTP_HEADER_SIZE];
    if (rpt->stream_version > 1) {
        info("STREAM %s [receive from [%s]:%s]: Netdata is using the stream version %u.", rpt->host->hostname, rpt->client_ip, rpt->client_port, rpt->stream_version);
        sprintf(initial_response, "%s%u", START_STREAMING_PROMPT_VN, rpt->stream_version);
    } else if (rpt->stream_version == 1) {
        info("STREAM %s [receive from [%s]:%s]: Netdata is using the stream version %u.", rpt->host->hostname, rpt->client_ip, rpt->client_port, rpt->stream_version);

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 85 Column: 44 CWE codes: 126

              #ifdef ENABLE_HTTPS
        SSL *conn = host->stream_ssl.conn ;
        if(conn && !host->stream_ssl.flags) {
            ret = SSL_write(conn, message, strlen(message));
        } else {
            ret = send(host->receiver->fd, message, strlen(message), MSG_DONTWAIT);
        }
#else
        ret = send(host->receiver->fd, message, strlen(message), MSG_DONTWAIT);

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 87 Column: 53 CWE codes: 126

                      if(conn && !host->stream_ssl.flags) {
            ret = SSL_write(conn, message, strlen(message));
        } else {
            ret = send(host->receiver->fd, message, strlen(message), MSG_DONTWAIT);
        }
#else
        ret = send(host->receiver->fd, message, strlen(message), MSG_DONTWAIT);
#endif
        if (ret != (int)strlen(message))

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 90 Column: 49 CWE codes: 126

                          ret = send(host->receiver->fd, message, strlen(message), MSG_DONTWAIT);
        }
#else
        ret = send(host->receiver->fd, message, strlen(message), MSG_DONTWAIT);
#endif
        if (ret != (int)strlen(message))
            error("Failed to send initial timestamp - gaps may appear in charts");
        return PARSER_RC_OK;
    }

            

Reported by FlawFinder.

aclk/aclk_util.c
16 issues
strcpy - Does not check for buffer overflows when copying to destination [MS-banned]
Security

Line: 198 Column: 5 CWE codes: 120
Suggestion: Consider using snprintf, strcpy_s, or strlcpy (warning: strncpy easily misused)

                  dest += strlen(localhost->aclk_state.claimed_id);
    rrdhost_aclk_state_unlock(localhost);
    replace_tag += strlen(CLAIM_ID_REPLACE_TAG);
    strcpy(dest, replace_tag);
    dest += strlen(replace_tag);
    *dest = 0;
}

static int topic_cache_add_topic(struct json_object *json, struct aclk_topic *topic)

            

Reported by FlawFinder.

srandom - This function is not sufficiently random for security-related functions such as key and nonce creation
Security

Line: 330 Column: 9 CWE codes: 327
Suggestion: Use a more secure technique for acquiring random values

                  attempt++;

    if (attempt == 0) {
        srandom(time(NULL));
        return 0;
    }

    unsigned long int delay = pow(base, attempt - 1);
    delay *= MSEC_PER_SEC;

            

Reported by FlawFinder.

random - This function is not sufficiently random for security-related functions such as key and nonce creation
Security

Line: 337 Column: 15 CWE codes: 327
Suggestion: Use a more secure technique for acquiring random values

                  unsigned long int delay = pow(base, attempt - 1);
    delay *= MSEC_PER_SEC;

    delay += (random() % (MAX(1000, delay/2)));

    if (delay <= min * MSEC_PER_SEC)
        return min;

    if (delay >= max * MSEC_PER_SEC)

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 191 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  }

    t->topic = mallocz(strlen(t->topic_recvd) + 1 - strlen(CLAIM_ID_REPLACE_TAG) + strlen(localhost->aclk_state.claimed_id));
    memcpy(t->topic, t->topic_recvd, replace_tag - t->topic_recvd);
    dest = t->topic + (replace_tag - t->topic_recvd);

    memcpy(dest, localhost->aclk_state.claimed_id, strlen(localhost->aclk_state.claimed_id));
    dest += strlen(localhost->aclk_state.claimed_id);
    rrdhost_aclk_state_unlock(localhost);

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 194 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  memcpy(t->topic, t->topic_recvd, replace_tag - t->topic_recvd);
    dest = t->topic + (replace_tag - t->topic_recvd);

    memcpy(dest, localhost->aclk_state.claimed_id, strlen(localhost->aclk_state.claimed_id));
    dest += strlen(localhost->aclk_state.claimed_id);
    rrdhost_aclk_state_unlock(localhost);
    replace_tag += strlen(CLAIM_ID_REPLACE_TAG);
    strcpy(dest, replace_tag);
    dest += strlen(replace_tag);

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 369 Column: 9 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

              
    if ((tmp = strchr(ptr, '/'))) {
        host = mallocz((tmp - ptr) + 1);
        memcpy(host, ptr, (tmp - ptr));
        host[tmp - ptr] = 0;
    } else
        host = strdupz(ptr);

    if ((tmp = strchr(host, ':'))) {

            

Reported by FlawFinder.

atoi - Unless checked, the resulting number can exceed the expected range
Security

Line: 377 Column: 17 CWE codes: 190
Suggestion: If source untrusted, check both minimum and maximum, even if the input had no minus sign (large numbers can roll over into negative number; consider saving to an unsigned value if that is intended)

                  if ((tmp = strchr(host, ':'))) {
        *tmp = 0;
        tmp++;
        *port = atoi(tmp);
    }

    if (*port <= 0 || *port > 65535)
        *port = 8080;


            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 190 Column: 53 CWE codes: 126

                      return;
    }

    t->topic = mallocz(strlen(t->topic_recvd) + 1 - strlen(CLAIM_ID_REPLACE_TAG) + strlen(localhost->aclk_state.claimed_id));
    memcpy(t->topic, t->topic_recvd, replace_tag - t->topic_recvd);
    dest = t->topic + (replace_tag - t->topic_recvd);

    memcpy(dest, localhost->aclk_state.claimed_id, strlen(localhost->aclk_state.claimed_id));
    dest += strlen(localhost->aclk_state.claimed_id);

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 190 Column: 84 CWE codes: 126

                      return;
    }

    t->topic = mallocz(strlen(t->topic_recvd) + 1 - strlen(CLAIM_ID_REPLACE_TAG) + strlen(localhost->aclk_state.claimed_id));
    memcpy(t->topic, t->topic_recvd, replace_tag - t->topic_recvd);
    dest = t->topic + (replace_tag - t->topic_recvd);

    memcpy(dest, localhost->aclk_state.claimed_id, strlen(localhost->aclk_state.claimed_id));
    dest += strlen(localhost->aclk_state.claimed_id);

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 190 Column: 24 CWE codes: 126

                      return;
    }

    t->topic = mallocz(strlen(t->topic_recvd) + 1 - strlen(CLAIM_ID_REPLACE_TAG) + strlen(localhost->aclk_state.claimed_id));
    memcpy(t->topic, t->topic_recvd, replace_tag - t->topic_recvd);
    dest = t->topic + (replace_tag - t->topic_recvd);

    memcpy(dest, localhost->aclk_state.claimed_id, strlen(localhost->aclk_state.claimed_id));
    dest += strlen(localhost->aclk_state.claimed_id);

            

Reported by FlawFinder.

collectors/python.d.plugin/python_modules/bases/FrameworkServices/MySQLService.py
16 issues
Unable to import 'bases.FrameworkServices.SimpleService'
Error

Line: 20 Column: 1

                  except ImportError:
        PY_MYSQL = False

from bases.FrameworkServices.SimpleService import SimpleService


class MySQLService(SimpleService):
    def __init__(self, configuration=None, name=None):
        SimpleService.__init__(self, configuration=configuration, name=name)

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 113 Column: 16

              
        try:
            data = self._get_data()
        except Exception as error:
            self.error('_get_data() failed. Error: {error}'.format(error=error))
            return False

        if isinstance(data, dict) and data:
            return True

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 143 Column: 25

                              except (MySQLdb.ProgrammingError, MySQLdb.OperationalError) as error:
                    if self.__is_error_critical(err_class=exc_info()[0], err_text=str(error)):
                        cursor.close()
                        raise RuntimeError
                    self.error('Removed query: {name}[{query}]. Error: error'.format(name=name,
                                                                                     query=query,
                                                                                     error=error))
                    self.queries.pop(name)
                    continue

            

Reported by Pylint.

Unused format argument 'error'
Error

Line: 144 Column: 32

                                  if self.__is_error_critical(err_class=exc_info()[0], err_text=str(error)):
                        cursor.close()
                        raise RuntimeError
                    self.error('Removed query: {name}[{query}]. Error: error'.format(name=name,
                                                                                     query=query,
                                                                                     error=error))
                    self.queries.pop(name)
                    continue
                else:

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # -*- coding: utf-8 -*-
# Description:
# Author: Ilya Mashchenko (ilyam8)
# SPDX-License-Identifier: GPL-3.0-or-later

from sys import exc_info

try:
    import MySQLdb

            

Reported by Pylint.

Module name "MySQLService" doesn't conform to snake_case naming style
Error

Line: 1 Column: 1

              # -*- coding: utf-8 -*-
# Description:
# Author: Ilya Mashchenko (ilyam8)
# SPDX-License-Identifier: GPL-3.0-or-later

from sys import exc_info

try:
    import MySQLdb

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 23 Column: 1

              from bases.FrameworkServices.SimpleService import SimpleService


class MySQLService(SimpleService):
    def __init__(self, configuration=None, name=None):
        SimpleService.__init__(self, configuration=configuration, name=name)
        self.__connection = None
        self.__conn_properties = dict()
        self.extra_conn_properties = dict()

            

Reported by Pylint.

Missing class docstring
Error

Line: 23 Column: 1

              from bases.FrameworkServices.SimpleService import SimpleService


class MySQLService(SimpleService):
    def __init__(self, configuration=None, name=None):
        SimpleService.__init__(self, configuration=configuration, name=name)
        self.__connection = None
        self.__conn_properties = dict()
        self.extra_conn_properties = dict()

            

Reported by Pylint.

Line too long (101/100)
Error

Line: 34 Column: 1

              
    def __connect(self):
        try:
            connection = MySQLdb.connect(connect_timeout=self.update_every, **self.__conn_properties)
        except (MySQLdb.MySQLError, TypeError, AttributeError) as error:
            return None, str(error)
        else:
            return connection, None


            

Reported by Pylint.

Too many return statements (7/6)
Error

Line: 40 Column: 5

                      else:
            return connection, None

    def check(self):
        def get_connection_properties(conf, extra_conf):
            properties = dict()
            if conf.get('user'):
                properties['user'] = conf['user']
            if conf.get('pass'):

            

Reported by Pylint.

collectors/python.d.plugin/redis/redis.chart.py
15 issues
Unable to import 'bases.FrameworkServices.SocketService'
Error

Line: 10 Column: 1

              import re
from copy import deepcopy

from bases.FrameworkServices.SocketService import SocketService

REDIS_ORDER = [
    'operations',
    'hit_rate',
    'memory',

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # -*- coding: utf-8 -*-
# Description: redis netdata python.d module
# Author: Pawel Krupa (paulfantom)
# Author: Ilya Mashchenko (ilyam8)
# SPDX-License-Identifier: GPL-3.0-or-later

import re
from copy import deepcopy


            

Reported by Pylint.

Line too long (102/100)
Error

Line: 89 Column: 1

                      ]
    },
    'connections': {
        'options': [None, 'Connections', 'connections/s', 'connections', 'redis.connections', 'line'],
        'lines': [
            ['total_connections_received', 'received', 'incremental', 1],
            ['rejected_connections', 'rejected', 'incremental', -1]
        ]
    },

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 138 Column: 1

              }


def copy_chart(name):
    return {name: deepcopy(CHARTS[name])}


RE = re.compile(r'\n([a-z_0-9 ]+):(?:keys=)?([^,\r]+)')


            

Reported by Pylint.

Too many instance attributes (10/7)
Error

Line: 145 Column: 1

              RE = re.compile(r'\n([a-z_0-9 ]+):(?:keys=)?([^,\r]+)')


class Service(SocketService):
    def __init__(self, configuration=None, name=None):
        SocketService.__init__(self, configuration=configuration, name=name)
        self.order = list()
        self.definitions = dict()
        self._keep_alive = True

            

Reported by Pylint.

Missing class docstring
Error

Line: 145 Column: 1

              RE = re.compile(r'\n([a-z_0-9 ]+):(?:keys=)?([^,\r]+)')


class Service(SocketService):
    def __init__(self, configuration=None, name=None):
        SocketService.__init__(self, configuration=configuration, name=name)
        self.order = list()
        self.definitions = dict()
        self._keep_alive = True

            

Reported by Pylint.

Variable name "p" doesn't conform to snake_case naming style
Error

Line: 154 Column: 9

                      self.host = self.configuration.get('host', 'localhost')
        self.port = self.configuration.get('port', 6379)
        self.unix_socket = self.configuration.get('socket')
        p = self.configuration.get('pass')
        self.auth_request = 'AUTH {0} \r\n'.format(p).encode() if p else None
        self.request = 'INFO\r\n'.encode()
        self.bgsave_time = 0
        self.keyspace_dbs = set()


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 160 Column: 5

                      self.bgsave_time = 0
        self.keyspace_dbs = set()

    def do_auth(self):
        resp = self._get_raw_data(request=self.auth_request)
        if not resp:
            return False
        if resp.strip() != '+OK':
            self.error('invalid password')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 169 Column: 5

                          return False
        return True

    def get_raw_and_parse(self):
        if self.auth_request and not self.do_auth():
            return None

        resp = self._get_raw_data()


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 201 Column: 5

                      return data

    @staticmethod
    def calc_hit_rate(data):
        try:
            hits = int(data['keyspace_hits'])
            misses = int(data['keyspace_misses'])
            data['hit_rate'] = hits * 100 / (hits + misses)
        except (KeyError, ZeroDivisionError):

            

Reported by Pylint.

collectors/python.d.plugin/alarms/alarms.chart.py
15 issues
Unable to import 'bases.FrameworkServices.UrlService'
Error

Line: 8 Column: 1

              
from json import loads

from bases.FrameworkServices.UrlService import UrlService

update_every = 10
disabled_by_default = True



            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # -*- coding: utf-8 -*-
# Description: alarms netdata python.d module
# Author: andrewm4894
# SPDX-License-Identifier: GPL-3.0-or-later

from json import loads

from bases.FrameworkServices.UrlService import UrlService


            

Reported by Pylint.

Constant name "update_every" doesn't conform to UPPER_CASE naming style
Error

Line: 10 Column: 1

              
from bases.FrameworkServices.UrlService import UrlService

update_every = 10
disabled_by_default = True


def charts_template(sm, alarm_status_chart_type='line'):
    order = [

            

Reported by Pylint.

Constant name "disabled_by_default" doesn't conform to UPPER_CASE naming style
Error

Line: 11 Column: 1

              from bases.FrameworkServices.UrlService import UrlService

update_every = 10
disabled_by_default = True


def charts_template(sm, alarm_status_chart_type='line'):
    order = [
        'alarms',

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 14 Column: 1

              disabled_by_default = True


def charts_template(sm, alarm_status_chart_type='line'):
    order = [
        'alarms',
        'values'
    ]


            

Reported by Pylint.

Argument name "sm" doesn't conform to snake_case naming style
Error

Line: 14 Column: 1

              disabled_by_default = True


def charts_template(sm, alarm_status_chart_type='line'):
    order = [
        'alarms',
        'values'
    ]


            

Reported by Pylint.

Line too long (125/100)
Error

Line: 23 Column: 1

                  mappings = ', '.join(['{0}={1}'.format(k, v) for k, v in sm.items()])
    charts = {
        'alarms': {
            'options': [None, 'Alarms ({0})'.format(mappings), 'status', 'status', 'alarms.status', alarm_status_chart_type],
            'lines': [],
            'variables': [
                ['alarms_num'],
            ]
        },

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 43 Column: 1

              DEFAULT_ALARM_STATUS_CHART_TYPE = 'line'


class Service(UrlService):
    def __init__(self, configuration=None, name=None):
        UrlService.__init__(self, configuration=configuration, name=name)
        self.sm = self.configuration.get('status_map', DEFAULT_STATUS_MAP)
        self.alarm_status_chart_type = self.configuration.get('alarm_status_chart_type', DEFAULT_ALARM_STATUS_CHART_TYPE)
        self.order, self.definitions = charts_template(self.sm, self.alarm_status_chart_type)

            

Reported by Pylint.

Missing class docstring
Error

Line: 43 Column: 1

              DEFAULT_ALARM_STATUS_CHART_TYPE = 'line'


class Service(UrlService):
    def __init__(self, configuration=None, name=None):
        UrlService.__init__(self, configuration=configuration, name=name)
        self.sm = self.configuration.get('status_map', DEFAULT_STATUS_MAP)
        self.alarm_status_chart_type = self.configuration.get('alarm_status_chart_type', DEFAULT_ALARM_STATUS_CHART_TYPE)
        self.order, self.definitions = charts_template(self.sm, self.alarm_status_chart_type)

            

Reported by Pylint.

Attribute name "sm" doesn't conform to snake_case naming style
Error

Line: 46 Column: 9

              class Service(UrlService):
    def __init__(self, configuration=None, name=None):
        UrlService.__init__(self, configuration=configuration, name=name)
        self.sm = self.configuration.get('status_map', DEFAULT_STATUS_MAP)
        self.alarm_status_chart_type = self.configuration.get('alarm_status_chart_type', DEFAULT_ALARM_STATUS_CHART_TYPE)
        self.order, self.definitions = charts_template(self.sm, self.alarm_status_chart_type)
        self.url = self.configuration.get('url', DEFAULT_URL)
        self.collect_alarm_values = bool(self.configuration.get('collect_alarm_values', DEFAULT_COLLECT_ALARM_VALUES))
        self.collected_dims = {'alarms': set(), 'values': set()}

            

Reported by Pylint.

collectors/proc.plugin/sys_class_infiniband.c
15 issues
strcat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 410 Column: 5 CWE codes: 120
Suggestion: Consider using strcat_s, strncat, strlcat, or snprintf (warning: strncat is easily misused)

              // Gen filename allocation and concatenation
#define GEN_DO_COUNTER_NAME(NAME, GRP, DESC, DIR, PORT, ...)                                                           \
    PORT->file_##NAME = callocz(1, strlen(PORT->counters_path) + sizeof(#NAME) + 3);                                   \
    strcat(PORT->file_##NAME, PORT->counters_path);                                                                    \
    strcat(PORT->file_##NAME, "/" #NAME);
                    FOREACH_COUNTER(GEN_DO_COUNTER_NAME, p)

                    // Check HW Counters vendor dependent
                    DIR *hwcounters_dir = opendir(hwcounters_dirname);

            

Reported by FlawFinder.

strcat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 411 Column: 5 CWE codes: 120
Suggestion: Consider using strcat_s, strncat, strlcat, or snprintf (warning: strncat is easily misused)

              #define GEN_DO_COUNTER_NAME(NAME, GRP, DESC, DIR, PORT, ...)                                                           \
    PORT->file_##NAME = callocz(1, strlen(PORT->counters_path) + sizeof(#NAME) + 3);                                   \
    strcat(PORT->file_##NAME, PORT->counters_path);                                                                    \
    strcat(PORT->file_##NAME, "/" #NAME);
                    FOREACH_COUNTER(GEN_DO_COUNTER_NAME, p)

                    // Check HW Counters vendor dependent
                    DIR *hwcounters_dir = opendir(hwcounters_dirname);
                    if (hwcounters_dir) {

            

Reported by FlawFinder.

strcat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 426 Column: 5 CWE codes: 120
Suggestion: Consider using strcat_s, strncat, strlcat, or snprintf (warning: strncat is easily misused)

              // Allocate the chars to the filenames
#define GEN_DO_HWCOUNTER_NAME(NAME, GRP, DESC, DIR, PORT, HW, ...)                                                     \
    HW->file_##NAME = callocz(1, strlen(PORT->hwcounters_path) + sizeof(#NAME) + 3);                                   \
    strcat(HW->file_##NAME, PORT->hwcounters_path);                                                                    \
    strcat(HW->file_##NAME, "/" #NAME);

                        // VENDOR-MLX: Mellanox
                        if (strncmp(dev_dent->d_name, "mlx", 3) == 0) {
                            // Allocate the vendor specific struct

            

Reported by FlawFinder.

strcat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 427 Column: 5 CWE codes: 120
Suggestion: Consider using strcat_s, strncat, strlcat, or snprintf (warning: strncat is easily misused)

              #define GEN_DO_HWCOUNTER_NAME(NAME, GRP, DESC, DIR, PORT, HW, ...)                                                     \
    HW->file_##NAME = callocz(1, strlen(PORT->hwcounters_path) + sizeof(#NAME) + 3);                                   \
    strcat(HW->file_##NAME, PORT->hwcounters_path);                                                                    \
    strcat(HW->file_##NAME, "/" #NAME);

                        // VENDOR-MLX: Mellanox
                        if (strncmp(dev_dent->d_name, "mlx", 3) == 0) {
                            // Allocate the vendor specific struct
                            p->hwcounters_mlx = callocz(1, sizeof(struct ibporthw_mlx));

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 237 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              {
    struct ibport *p;

    char name[IBNAME_MAX + 1];
    snprintfz(name, IBNAME_MAX, "%s-%s", dev, port);

    // search it, resuming from the last position in sequence
    for (p = ibport_last_used; p; p = p->next) {
        if (unlikely(!strcmp(name, p->name))) {

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 267 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                  p->chart_type_hwpackets = strdupz("infiniband_hwc_packets");
    p->chart_type_hwerrors  = strdupz("infiniband_hwc_errors");

    char buffer[RRD_ID_LENGTH_MAX + 1];
    snprintfz(buffer, RRD_ID_LENGTH_MAX, "ib_cntbytes_%s",     p->name);
    p->chart_id_bytes = strdupz(buffer);

    snprintfz(buffer, RRD_ID_LENGTH_MAX, "ib_cntpackets_%s",   p->name);
    p->chart_id_packets = strdupz(buffer);

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 310 Column: 9 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                  static long long int dt_to_refresh_ports = 0, last_refresh_ports_usec = 0;

    if (unlikely(enable_new_ports == -1)) {
        char dirname[FILENAME_MAX + 1];

        snprintfz(dirname, FILENAME_MAX, "%s%s", netdata_configured_host_prefix, "/sys/class/infiniband");
        sys_class_infiniband_dirname =
            config_get(CONFIG_SECTION_PLUGIN_SYS_CLASS_INFINIBAND, "dirname to monitor", dirname);


            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 355 Column: 13 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                              continue;

            // /sys/class/infiniband/<dev>/ports
            char ports_dirname[FILENAME_MAX + 1];
            snprintfz(ports_dirname, FILENAME_MAX, "%s/%s/%s", sys_class_infiniband_dirname, dev_dent->d_name, "ports");

            DIR *ports_dir = opendir(ports_dirname);
            if (unlikely(!ports_dir))
                continue;

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 368 Column: 17 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                              if (!strcmp(port_dent->d_name, "..") || !strcmp(port_dent->d_name, "."))
                    continue;

                char buffer[FILENAME_MAX + 1];

                // Check if counters are available (mandatory)
                // /sys/class/infiniband/<device>/ports/<port>/counters
                char counters_dirname[FILENAME_MAX + 1];
                snprintfz(counters_dirname, FILENAME_MAX, "%s/%s/%s", ports_dirname, port_dent->d_name, "counters");

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 372 Column: 17 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              
                // Check if counters are available (mandatory)
                // /sys/class/infiniband/<device>/ports/<port>/counters
                char counters_dirname[FILENAME_MAX + 1];
                snprintfz(counters_dirname, FILENAME_MAX, "%s/%s/%s", ports_dirname, port_dent->d_name, "counters");
                DIR *counters_dir = opendir(counters_dirname);
                // Standard counters are mandatory
                if (!counters_dir)
                    continue;

            

Reported by FlawFinder.