Showing posts with label securitydefects. Show all posts
Showing posts with label securitydefects. Show all posts

Friday, March 17, 2017

Weaknesses detected by PVS-Studio this week: episode N2

We decided to search and fix potential vulnerabilities in various projects. You can call this as you wish - some kind of help to open source projects; a method of promotion or testing of the analyzer. Another way to see it as a way to attract attention to the reliability and quality of the code. In fact, the way to name these posts does not really matter - we just like doing it. This is our little hobby. So, let us have a look at our findings in the code of various projects this week - we had some time to make fixes and suggest looking at them.
Picture 2

For those who are not familiar with PVS-Studio tool

PVS-Studio is a tool that detects a large number of types of vulnerabilities and errors in the code. It performs static analysis and points to code fragments that are likely to contain errors. The best effect is achieved when the static analysis is performed regularly. Ideologically, the analyzer warnings are similar to the compiler warnings. However, unlike compilers, PVS-Studio can perform deeper and more versatile code analysis. This enables it to detect errors, even in compilers: GCC; LLVM 1, 2, 3; Roslyn.


The tool supports the analysis of C, C++ and C#; works under Windows and Linux. The analyzer can be integrated as a Visual Studio plug-in.
We suggest the following materials for further investigation of the tool:

Vulnerabilities

In this section we show those defects that fall under the CWE classification and are potential vulnerabilities in their core. Of course, not all weaknesses are really threatening for a project, but we wanted to show that our tool is able to detect them.
1. Clang. CWE-571 (Expression is Always True)
V768 The enumeration constant 'S_MOVRELS_B64' is used as a variable of a Boolean-type. gcnhazardrecognizer.cpp 75
namespace AMDGPU {
  enum {
    ....
    S_MOVRELS_B64 = 4043,
    ....
  };
}

static bool isSMovRel(unsigned Opcode) {
  return
    Opcode == AMDGPU::S_MOVRELS_B32 || AMDGPU::S_MOVRELS_B64 ||
    Opcode == AMDGPU::S_MOVRELD_B32 || AMDGPU::S_MOVRELD_B64;
}
2. Clang. CWE-457 (Use of Uninitialized Variable)
V573 Uninitialized variable 'BytesToDrop' was used. The variable was used to initialize itself. typerecordmapping.cpp 73
static Error mapNameAndUniqueName(....) {
  ....
  size_t BytesLeft = IO.maxFieldLength();
  if (HasUniqueName) {
    .....
    if (BytesNeeded > BytesLeft) {
      size_t BytesToDrop = (BytesNeeded - BytesLeft);
      size_t DropN = std::min(N.size(), BytesToDrop / 2);
      size_t DropU = std::min(U.size(), BytesToDrop - DropN);
      ....
    }
  } else {
    size_t BytesNeeded = Name.size() + 1;
    StringRef N = Name;
    if (BytesNeeded > BytesLeft) {
      size_t BytesToDrop = std::min(N.size(), BytesToDrop); // <=
      N = N.drop_back(BytesToDrop);
    }
    error(IO.mapStringZ(N));
  }
  ....
}
3. Clang. CWE-570 Expression is Always False
V517 The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical error presence. Check lines: 416, 418. iteratorpastendchecker.cpp 416
bool IteratorPastEndChecker::evalCall(const CallExpr *CE,
                                      CheckerContext &C) const {
  ....
  if (FD->getIdentifier() == II_find) {
    return evalFind(C, CE);
  } else if (FD->getIdentifier() == II_find_end) {
    return evalFindEnd(C, CE);
  } else if (FD->getIdentifier() == II_find_first_of) {
    return evalFindFirstOf(C, CE);
  } else if (FD->getIdentifier() == II_find_if) {         // <=
    return evalFindIf(C, CE);
  } else if (FD->getIdentifier() == II_find_if) {         // <=
    return evalFindIf(C, CE);
  } else if (FD->getIdentifier() == II_find_if_not) {
    return evalFindIfNot(C, CE);
  } else if (FD->getIdentifier() == II_upper_bound) {
    return evalUpperBound(C, CE);
  } else if (FD->getIdentifier() == II_lower_bound) {
    return evalLowerBound(C, CE);
  } else if (FD->getIdentifier() == II_search) {
    return evalSearch(C, CE);
  } else if (FD->getIdentifier() == II_search_n) {
    return evalSearchN(C, CE);
  }
  ....
}
4. GCC. CWE-476 (NULL Pointer Dereference)
V595 The 'm->component' pointer was utilized before it was verified against nullptr. Check lines: 399, 407. genmodes.c 399
static void complete_mode (struct mode_data *m)
{
  ....
  if (   m->cl == MODE_COMPLEX_INT 
      || m->cl == MODE_COMPLEX_FLOAT)
    alignment = m->component->bytesize;        // <=
  else
    alignment = m->bytesize;

  m->alignment = alignment & (~alignment + 1);

  if (m->component)                            // <=
  {
    m->next_cont = m->component->contained;
    m->component->contained = m;
  }
}
5. GCC. CWE-570 (Expression is Always False)
V625 Consider inspecting the 'for' operator. Initial and final values of the iterator are the same. sese.c 201
void free_sese_info (sese_info_p region)
{
  region->params.release ();
  region->loop_nest.release ();

  for (rename_map_t::iterator it = region->rename_map->begin();
       it != region->rename_map->begin (); ++it) // <=
    (*it).second.release();
  ....
}
6. GCC. CWE-571 (Expression is Always True)
V501 There are identical sub-expressions '!strcmp(a->v.val_vms_delta.lbl1, b->v.val_vms_delta.lbl1)' to the left and to the right of the '&&' operator. dwarf2out.c 1434
static bool dw_val_equal_p (dw_val_node *a, dw_val_node *b)
{
  ....
  switch (a->val_class)
  {
    ....
  case dw_val_class_vms_delta:
    return (   !strcmp (a->v.val_vms_delta.lbl1,
                        b->v.val_vms_delta.lbl1)
            && !strcmp (a->v.val_vms_delta.lbl1, 
                        b->v.val_vms_delta.lbl1));
    ....
  }
  ....
}
7. GCC. CWE-483 (Incorrect Block Delimitation)
V640 The code's operational logic does not correspond with its formatting. The second statement will always be executed. It is possible that curly brackets are missing. asan.c 2582
void initialize_sanitizer_builtins (void)
{
  ....
  #define DEF_SANITIZER_BUILTIN(ENUM, NAME, TYPE, ATTRS) \
  decl = add_builtin_function ("__builtin_" NAME, TYPE, ENUM, \
             BUILT_IN_NORMAL, NAME, NULL_TREE);  \
  set_call_expr_flags (decl, ATTRS);          \
  set_builtin_decl (ENUM, decl, true);

  #include "sanitizer.def"

  if ((flag_sanitize & SANITIZE_OBJECT_SIZE)
      && !builtin_decl_implicit_p (BUILT_IN_OBJECT_SIZE))
    DEF_SANITIZER_BUILTIN (BUILT_IN_OBJECT_SIZE, "object_size",
         BT_FN_SIZE_CONST_PTR_INT,
         ATTR_PURE_NOTHROW_LEAF_LIST)
  ....
}
8. FreeBSD. CWE-467: (Use of sizeof() on a Pointer Type)
V512 A call of the 'memset' function will lead to underflow of the buffer 'plog'. nat64lsn.c 218
struct pfloghdr {
  u_int8_t  length;
  sa_family_t  af;
  u_int8_t  action;
  u_int8_t  reason;
  char    ifname[IFNAMSIZ];
  char    ruleset[PFLOG_RULESET_NAME_SIZE];
  u_int32_t  rulenr;
  u_int32_t  subrulenr;
  uid_t    uid;
  pid_t    pid;
  uid_t    rule_uid;
  pid_t    rule_pid;
  u_int8_t  dir;
  u_int8_t  pad[3];
};

static void
nat64lsn_log(struct pfloghdr *plog, ....)
{
  memset(plog, 0, sizeof(plog));        // <=
  plog->length = PFLOG_REAL_HDRLEN;
  plog->af = family;
  plog->action = PF_NAT;
  plog->dir = PF_IN;
  plog->rulenr = htonl(n);
  plog->subrulenr = htonl(sn);
  plog->ruleset[0] = '\0';
  strlcpy(plog->ifname, "NAT64LSN", sizeof(plog->ifname));
  ipfw_bpf_mtap2(plog, PFLOG_HDRLEN, m);
}
9. FreeBSD. CWE-570 (Expression is Always False)
V517 The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical error presence. Check lines: 102, 109. dtrace_debug.c 102
static void
dtrace_debug_output(void)
{
  ....
  if (d->first < d->next) {
    char *p1 = dtrace_debug_bufr;
    count = (uintptr_t) d->next - (uintptr_t) d->first;
    for (p = d->first; p < d->next; p++)
      *p1++ = *p;
  } else if (d->next > d->first) {
    char *p1 = dtrace_debug_bufr;
    count = (uintptr_t) d->last - (uintptr_t) d->first;
    for (p = d->first; p < d->last; p++)
      *p1++ = *p;
    count += (uintptr_t) d->next - (uintptr_t) d->bufr;
    for (p = d->bufr; p < d->next; p++)
      *p1++ = *p;
  }
  ....
}
10. FreeBSD. CWE-571 (Expression is Always True)
V547 Expression 'cfgflags >= 0 || cfgflags <= 3' is always true. hwpmc_piv.c 812
V547 Expression 'cfgflags >= 0 || cfgflags <= 3' is always true. hwpmc_piv.c 838
static int
p4_config_pmc(int cpu, int ri, struct pmc *pm)
{
  ....
  int cfgflags, cpuflag;
  ....
  KASSERT(cfgflags >= 0 || cfgflags <= 3,
      ("[p4,%d] illegal cfgflags cfg=%d on cpu=%d ri=%d",
    __LINE__, cfgflags, cpu, ri));
  ....
  KASSERT(cfgflags >= 0 || cfgflags <= 3,
      ("[p4,%d] illegal runcount cfg=%d on cpu=%d ri=%d",
    __LINE__, cfgflags, cpu, ri));
  ....
}
11. FreeBSD. CWE-570 (Expression is Always False)
V547 Expression is always false. scif_sas_controller.c 531
....
U16  max_ncq_depth;
....
SCI_STATUS scif_user_parameters_set(
   SCI_CONTROLLER_HANDLE_T   controller,
   SCIF_USER_PARAMETERS_T  * scif_parms
)
{
  ....
   if (scif_parms->sas.max_ncq_depth < 1 &&
       scif_parms->sas.max_ncq_depth > 32)
     return SCI_FAILURE_INVALID_PARAMETER_VALUE;
  ....
}
12. FreeBSD. CWE-571: (Expression is Always True)
V547 Expression 'cdb[0] != 0x28 || cdb[0] != 0x2A' is always true. Probably the '&&' operator should be used here. mfi_tbolt.c 1110
int
mfi_tbolt_send_frame(struct mfi_softc *sc, struct mfi_command *cm)
{
  ....
  uint8_t *cdb;
  ....
  /* check for inquiry commands coming from CLI */
  if (cdb[0] != 0x28 || cdb[0] != 0x2A) {
    if ((req_desc = mfi_tbolt_build_mpt_cmd(sc, cm)) == NULL) {
      device_printf(sc->mfi_dev, "Mapping from MFI "
                                 "to MPT Failed \n");
      return 1;
    }
  }
  ....
}
13. FreeBSD. CWE-571 (Expression is Always True)
V560 A part of conditional expression is always true: 0x2002. sampirsp.c 7224
#define OSSA_MPI_ENC_ERR_ILLEGAL_DEK_PARAM            0x2001
#define OSSA_MPI_ERR_DEK_MANAGEMENT_DEK_UNWRAP_FAIL   0x2002

GLOBAL bit32 mpiDekManagementRsp(
  agsaRoot_t               *agRoot,
  agsaDekManagementRsp_t   *pIomb
  )
{
  ....
  if (status == OSSA_MPI_ENC_ERR_ILLEGAL_DEK_PARAM ||
      OSSA_MPI_ERR_DEK_MANAGEMENT_DEK_UNWRAP_FAIL)
  {
    agEvent.eq = errorQualifier;
  }
  ....
}
14. FreeBSD. CWE-571 (Expression is Always True)
V560 A part of conditional expression is always true: 0x7dac. t4_main.c 8001
#define A_TP_KEEP_INTVL 0x7dac

static int
sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
{
  struct adapter *sc = arg1;
  int reg = arg2;
  u_int tre;
  u_long tp_tick_us, v;
  u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;

  MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
      reg == A_TP_PERS_MIN || reg == A_TP_PERS_MAX ||
      reg == A_TP_KEEP_IDLE || A_TP_KEEP_INTVL ||
      reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
  ....
}
15. FreeBSD. CWE-476 (NULL Pointer Dereference)
V595 The 'mc' pointer was utilized before it was verified against nullptr. Check lines: 2954, 2955. mly.c 2954
static int
mly_user_command(struct mly_softc *sc, struct mly_user_command *uc)
{
  struct mly_command  *mc;
  ....
  if (mc->mc_data != NULL)           // <=
    free(mc->mc_data, M_DEVBUF);     // <=
  if (mc != NULL) {                  // <=
    MLY_LOCK(sc);
    mly_release_command(mc);
    MLY_UNLOCK(sc);
  }
  return(error);
}
16. FreeBSD. CWE-563 (Assignment to Variable without Use ('Unused Variable'))
V519 The 'vf->flags' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 5992, 5994. if_ix.c 5994
static int
ixgbe_add_vf(device_t dev, u16 vfnum, const nvlist_t *config)
{
  ....
  if (nvlist_exists_binary(config, "mac-addr")) {
    mac = nvlist_get_binary(config, "mac-addr", NULL);
    bcopy(mac, vf->ether_addr, ETHER_ADDR_LEN);
    if (nvlist_get_bool(config, "allow-set-mac"))
      vf->flags |= IXGBE_VF_CAP_MAC;
  } else
    /*
     * If the administrator has not specified a MAC address then
     * we must allow the VF to choose one.
     */
    vf->flags |= IXGBE_VF_CAP_MAC;

  vf->flags = IXGBE_VF_ACTIVE;
  ....
}
17. FreeBSD. CWE-563 (Assignment to Variable without Use ('Unused Variable'))
V519 The 'pmuctrl' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 2025, 2026. bhnd_pmu_subr.c 2026
static void
bhnd_pmu1_pllinit0(struct bhnd_pmu_softc *sc, uint32_t xtal)
{
  uint32_t pmuctrl;
  ....
  /* Write XtalFreq. Set the divisor also. */
  pmuctrl = BHND_PMU_READ_4(sc, BHND_PMU_CTRL);
  pmuctrl = ~(BHND_PMU_CTRL_ILP_DIV_MASK |
              BHND_PMU_CTRL_XTALFREQ_MASK);
  pmuctrl |= BHND_PMU_SET_BITS(((xt->fref + 127) / 128) - 1,
             BHND_PMU_CTRL_ILP_DIV);
  pmuctrl |= BHND_PMU_SET_BITS(xt->xf, BHND_PMU_CTRL_XTALFREQ);
  ....
}
18. FreeBSD. CWE-561 (Dead Code)
V779 Unreachable code detected. It is possible that an error is present. if_wi_pci.c 258
static int
wi_pci_resume(device_t dev)
{
  struct wi_softc  *sc = device_get_softc(dev);
  struct ieee80211com *ic = &sc->sc_ic;

  WI_LOCK(sc);
  if (sc->wi_bus_type != WI_BUS_PCI_NATIVE) {
    return (0);                                 // <=
    WI_UNLOCK(sc);                              // <=
  }
  if (ic->ic_nrunning > 0)
    wi_init(sc);
  WI_UNLOCK(sc);
  return (0);
}
19. FreeBSD. CWE-561 (Dead Code)
V779 Unreachable code detected. It is possible that an error is present. mpr.c 1329
void panic(const char *a) __dead2;

static int
mpr_alloc_requests(struct mpr_softc *sc)
{
  ....
  else {
    panic("failed to allocate command %d\n", i);
    sc->num_reqs = i;
    break;
  }
  ....
}

Miscellaneous errors

1. GCC
V590 Consider inspecting this expression. The expression is excessive or contains a misprint. genmatch.c 3829
const cpp_token * parser::next ()
{
  const cpp_token *token;
  do
  {
    token = cpp_get_token (r);
  }
  while (   token->type == CPP_PADDING
         && token->type != CPP_EOF);    // <=
  return token;
}
2. Clang
V501 There are identical sub-expressions 'RA.getSubReg() != 0' to the left and to the right of the '||' operator. hexagonearlyifconv.cpp 485
unsigned HexagonEarlyIfConversion::computePhiCost(....) const {
  ....
  const MachineOperand &RA = MI.getOperand(1);
  const MachineOperand &RB = MI.getOperand(3);
  assert(RA.isReg() && RB.isReg());
  // Must have a MUX if the phi uses a subregister.
  if (RA.getSubReg() != 0 || RA.getSubReg() != 0) {
    Cost++;
    continue;
  }
  ....
}

Conclusion

We suggest downloading PVS-Studio analyzer and trying to check your project:
To remove the restrictions of a demo version, you can contact us and we will provide a temporary license key for you.

For a quick introduction to the analyzer, you can use the tools, tracking the runs of the compiler and collect all the necessary information for the analysis. See the description of the utilities CLMonitoring and pvs-studio-analyzer. If you are working with a classic type of project in Visual Studio, everything is much simpler: you should just choose in PVS-Studio menu a command "Check Solution".

Thursday, March 16, 2017

PVS-Studio: searching software weaknesses

PVS-Studio has always been able to detect a large number of various security defects (potential vulnerabilities) in the program code. However, historically, we positioned PVS-Studio as a tool to search for errors. We see a trend in the software development to look for vulnerabilities in the code, although it is just the same. It seems to us that it is high time to do the rebranding of our static analyzer PVS-Studio. We will start with Common Weakness Enumeration (CWE). This article provides a table that shows matches of PVS-Studio diagnostic warnings of with the classifier. The table will be gradually updated and changed, but we can already use the table to write articles about security defects detected in projects. We suppose it would attract more attention of the software security specialists.
Picture 2

Common Weakness Enumeration (CWE)

Let us make the terms clear first. To do this, I will quote a fragment of the FAQ from cwe.mitre.org.


A1. What is CWE? What is a "software weakness"?
Targeted at both the development community and the community of security practitioners, Common Weakness Enumeration (CWE) is a formal list or dictionary of common software weaknesses that can occur in software's architecture, design, code or implementation that can lead to exploitable security vulnerabilities. CWE was created to serve as a common language for describing software security weaknesses; serve as a standard measuring stick for software security tools targeting these weaknesses; and to provide a common baseline standard for weakness identification, mitigation, and prevention efforts.
Software weaknesses are flaws, faults, bugs, vulnerabilities, and other errors in software implementation, code, design, or architecture that if left unaddressed could result in systems and networks being vulnerable to attack. Example software weaknesses include: buffer overflows, format strings, etc.; structure and validity problems; common special element manipulations; channel and path errors; handler errors; user interface errors; pathname traversal and equivalence errors; authentication errors; resource management errors; insufficient verification of data; code evaluation and injection; and randomness and predictability.
A2. What is the difference between a software vulnerability and software weakness?
Software weaknesses are errors that can lead to software vulnerabilities. A software vulnerability, such as those enumerated on the Common Vulnerabilities and Exposures (CVE) List, is a mistake in software that can be directly used by a hacker to gain access to a system or network.

Correspondence between warnings of PVS-Studio and CWE

We want people to start seeing PVS-Studio not as just a tool to search for bugs, but as a tool that helps to eliminate vulnerabilities in the code. Of course, not every security defect listed in CWE is a vulnerability. It depends on a lot of factors if a certain flaw can be used to attack a program. That is why further on, we will write that PVS-Studio detects not just vulnerabilities, but potential vulnerabilities - it would be more correct.
So, here is the first variant of the correspondence table. As I have already said, the table will get updated in the future, but this variant already gives an overall impression of the analyzer abiliities.
CWEPVS-StudioCWE Description
CWE-14V597Compiler Removal of Code to Clear Buffers
CWE-121V755Stack-based Buffer Overflow
CWE-122V755Heap-based Buffer Overflow
CWE-123V575Write-what-where Condition
CWE-129V557, V781, V3106Improper Validation of Array Index
CWE-131V514, V531, V568, V620, V627, V635, V641, V651, V687, V706, V727Incorrect Calculation of Buffer Size
CWE-134V576, V618, V3025Use of Externally-Controlled Format String
CWE-135V518, V635Incorrect Calculation of Multi-Byte String Length
CWE-188V557, V3106Reliance on Data/Memory Layout
CWE-195V569Signed to Unsigned Conversion Error
CWE-197V642Numeric Truncation Error
CWE-36V631, V3039Absolute Path Traversal
CWE-369V609, V3064Divide By Zero
CWE-401V701, V773Improper Release of Memory Before Removing Last Reference ('Memory Leak')
CWE-404V611, V773Improper Resource Shutdown or Release
CWE-415V586Double Free
CWE-416V774Use after free
CWE-457V573, V614, V670, V3070, V3128Use of Uninitialized Variable
CWE-462V766, V3058Duplicate Key in Associative List (Alist)
CWE-467V511, V512, V568Use of sizeof() on a Pointer Type
CWE-468V613, V620, V643Incorrect Pointer Scaling
CWE-476V522, V595, V664, V757, V769, V3019, V3042, V3080, V3095, V3105, V3125NULL Pointer Dereference
CWE-478V577, V719, V622, V3002Missing Default Case in Switch Statement
CWE-481V559, V3055Assigning instead of comparing
CWE-482V607Comparing instead of Assigning
CWE-483V640, V3043Incorrect Block Delimitation
CWE-561V551, V695, V734, V776, V779, V3021Dead Code
CWE-562V558Return of Stack Variable Address
CWE-563V519, V603, V751, V763, V3061, V3065, V3077, V3117Assignment to Variable without Use ('Unused Variable')
CWE-570V501, V547, V560, V654, V3022, V3063Expression is Always False
CWE-571V501, V547, V560, V617, V654, V694, V3022, V3063Expression is Always True
CWE-587V566Assignment of a Fixed Address to a Pointer
CWE-588V641Attempt to Access Child of a Non-structure Pointer
CWE-674V3110Uncontrolled Recursion
CWE-690V522, V3080Unchecked Return Value to NULL Pointer Dereference
CWE-762V611Mismatched Memory Management Routines
CWE-805V512, V594, V3106Buffer Access with Incorrect Length Value
CWE-806V512Buffer Access Using Size of Source Buffer
CWE-843V641Access of Resource Using Incompatible Type ('Type Confusion')
Table N1. The first draft of the correspondence between CWE and PVS-Studio diagnostics.
Now we can write in our articles devoted to the project checks about the potential vulnerabilities as well. As this trend is becoming more common among the analyzers, we will also touch upon this topic in our articles.

Demonstration

Let us see how this table can be used in the articles. We will analyze a project and have a look at the diagnostic warnings from the point of view of the weaknesses.
Of course, not every project is worth examining in terms of vulnerabilities. So let us consider such a serious project like Apache HTTP Server.
As we check it, we see bugs crawling everywhere across the code. But wait! These are not just bugs, but security weaknesses. It sounds more serious, when we speak about safety issues, rather than about banal typos and errors.
I should say right away, that this time we are not going to analyze the whole project, because we have a task of showing how the table can be used in practice. Here are only three warnings.
Example N1.
#define myConnConfig(c) \
(SSLConnRec *)ap_get_module_config(c->conn_config, &ssl_module)

....

int ssl_callback_alpn_select(SSL *ssl,
  const unsigned char **out, unsigned char *outlen,
  const unsigned char *in, unsigned int inlen,
  void *arg)
{
  conn_rec *c = (conn_rec*)SSL_get_app_data(ssl);
  SSLConnRec *sslconn = myConnConfig(c);
  apr_array_header_t *client_protos;
  const char *proposed;
  size_t len;
  int i;

  /* If the connection object is not available,
   * then there's nothing for us to do. */
  if (c == NULL) {
    return SSL_TLSEXT_ERR_OK;
  }
  ....
}
PVS-Studio analyzer issues a warning: V595 The 'c' pointer was utilized before it was verified against nullptr. Check lines: 2340, 2348. ssl_engine_kernel.c 2340
In terms of security defects this is: CWE-476 (NULL Pointer Dereference)
The main point of this error. Let us point out two most important lines of code:
SSLConnRec *sslconn = myConnConfig(c);
if (c == NULL) {
The check (c == NULL) shows that the pointer can be NULL. However, it is already dereferenced inside the myConnConfig macro:
#define myConnConfig(c) \
(SSLConnRec *)ap_get_module_config(c->conn_config, &ssl_module)
Thus, this code is no way protected against the null pointer dereference.
Example N2.
int get_password(struct passwd_ctx *ctx)
{
  char buf[MAX_STRING_LEN + 1];
  ....
  memset(buf, '\0', sizeof(buf));
  return 0;
err_too_long:
  ....
}
PVS-Studio analyzer issues a warning: V597 The compiler could delete the 'memset' function call, which is used to flush 'buf' buffer. The memset_s() function should be used to erase the private data. passwd_common.c 165
In terms of security defects this is: CWE-14 (Compiler Removal of Code to Clear Buffers)
The main point of this error. When compiling the code in optimized mode, the compiler will remove the call of the memset function, because from the compiler's point of view, this call is redundant. After the buffer that was created on the stack is filled with zeroes, it is not used in any way. This means that filling the buffer with zeros is a waste of time and the call of the memset function should be removed. Thus, private data will not be overwritten and will stay in the memory.
I want to note that this is not some abstract theoretically possible behavior of a compiler. Compilers really do so to speed up our programs. Details:
Example N3
static int is_quoted_pair(const char *s)
{
    int res = -1;
    int c;

    if (((s + 1) != NULL) && (*s == '\\')) {
        c = (int) *(s + 1);
        if (apr_isascii(c)) {
          res = 1;
        }
    }
    return (res);
}
PVS-Studio analyzer issues a warning: V694 The condition ((s + 1) != ((void *) 0)) is only false if there is pointer overflow which is undefined behaviour anyway. mod_mime.c 531
In terms of security defects this is: CWE-571 (Expression is Always True)
The main point of this error: the condition ((s + 1) != NULL) is always true. It may be false only in case of the pointer overflow. It causes undefined behavior, so there is no sense in speaking about this case. We may consider that the condition is always true; the analyzer warned us about it.
We are not authors of the code, so we do not know for sure, how it should be written, but most likely, in this way:
if ((*(s + 1) != '\0') && (*s == '\\')) {

Conclusion

Hooray, PVS-Studio analyzer can be used to detect potential vulnerabilities in the code!
For those who are willing to investigate the analyzer abilities, we suggest trying a demo version on the project. Product page: PVS-Studio.

In case you have any technical questions or questions concerning the licensing of the product, we ask to write to us at support [@] viva64.com or use the feedback form.