Security hardening: fix 19 of 22 vulnerabilities found in audit

Critical:
- Trunk HMAC-SHA1 auth: MsgTrunkHello now carries nonce+digest,
  peer disconnected on secret mismatch (was loaded but never verified)

High:
- Pre-hello guard: reject all trunk messages before handshake completes
- CSPRNG for password generator: random.choice -> secrets.choice

Medium:
- Path traversal protection on callsign-based file operations
- Replace assert() on network-derived UDP data with error handling
- HTTP server connection throttling (matching main TCP server)
- try/catch on regex compilation in callsignOk()/emailOk()
- Per-link trunk talker tracking (clearAllTrunkTalkers scoped to peer)
- Regenerate priority nonce on each new trunk connection
- Cap active TGs and trunk talkers at 10000 each
- Don't reset heartbeat for unauthenticated client app messages
- Fix RENEW_AFTER integer division (2/3 -> 2.0/3.0)

Low:
- JSON-escape HTTP method in error response
- snprintf for pidfile error message
- MsgAuthResponse::digest() null check on empty vector
- Check unpack() return values in AsyncMsg.h vector/map/string
- Replace stack VLA with std::string; reserve+push_back vs resize
- Require TalkerStart before accepting trunk audio
This commit is contained in:
Audric committed 2026-03-20 11:54:18 +01:00
commit fca7c33794
276 files changed
+73533

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
/makefile.root
/Makefile
+17
View File
@@ -0,0 +1,17 @@
set(LIBNAME svxmisc)
set(EXPINC common.h CppStdCompat.h LogWriter.h)
set(LIBSRC common.cpp LogWriter.cpp)
# Copy exported include files to the global include directory
foreach(incfile ${EXPINC})
expinc(${incfile})
endforeach(incfile)
# Build a static library
add_library(${LIBNAME} STATIC ${LIBSRC})
set_target_properties(${LIBNAME} PROPERTIES OUTPUT_NAME ${LIBNAME})
target_link_libraries(${LIBNAME} ${LIBS})
# Install targets
install(TARGETS ${LIBNAME} DESTINATION ${LIB_INSTALL_DIR})
install(FILES ${EXPINC} DESTINATION ${SVX_INCLUDE_INSTALL_DIR})
+10
View File
@@ -0,0 +1,10 @@
#ifndef CPP_STD_COMPAT_INCLUDED
#define CPP_STD_COMPAT_INCLUDED
#if __cplusplus >= 201102L
#define CONSTEXPR constexpr
#else
#define CONSTEXPR const
#endif
#endif /* CPP_STD_COMPAT_INCLUDED */
+504
View File
@@ -0,0 +1,504 @@
/**
@file LogWriter.cpp
@brief A class for writing stdout and stderr to a logfile
@author Tobias Blomberg / SM0SVX
@date 2025-06-11
\verbatim
SvxLink - A Multi Purpose Voice Services System for Ham Radio Use
Copyright (C) 2003-2025 Tobias Blomberg / SM0SVX
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
*/
/****************************************************************************
*
* System Includes
*
****************************************************************************/
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <syslog.h>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <sstream>
/****************************************************************************
*
* Project Includes
*
****************************************************************************/
/****************************************************************************
*
* Local Includes
*
****************************************************************************/
#include "LogWriter.h"
/****************************************************************************
*
* Namespaces to use
*
****************************************************************************/
/****************************************************************************
*
* Defines & typedefs
*
****************************************************************************/
/****************************************************************************
*
* Static class variables
*
****************************************************************************/
/****************************************************************************
*
* Local class definitions
*
****************************************************************************/
class LogWriter::LogWriterWorker
{
public:
virtual ~LogWriterWorker(void) {}
virtual void setTimestampFormat(const std::string& fmt) {}
virtual bool logOpen(void) { return true; }
virtual void logClose(void) {}
virtual void logReopen(std::string reason) {}
virtual bool logWriteTimestamp(void) { return true; }
virtual void logWrite(const char *buf) = 0;
};
class LogWriter::LogWriterWorkerFile : public LogWriter::LogWriterWorker
{
public:
LogWriterWorkerFile(const std::string& filename);
virtual ~LogWriterWorkerFile(void) {}
virtual void setTimestampFormat(const std::string& fmt) override;
virtual bool logOpen(void) override;
virtual void logClose(void) override;
virtual void logReopen(std::string reason) override;
virtual bool logWriteTimestamp(void) override;
virtual void logWrite(const char *buf) override;
private:
std::string m_logfile_name;
int m_logfd {-1};
std::string m_tstamp_format {"%c"};
};
class LogWriter::LogWriterWorkerSyslog : public LogWriter::LogWriterWorker
{
public:
virtual ~LogWriterWorkerSyslog(void) {}
virtual void logWrite(const char *buf) override;
private:
std::string m_buf;
};
namespace {
/****************************************************************************
*
* Local functions
*
****************************************************************************/
}; /* End of anonymous namespace */
/****************************************************************************
*
* Public member functions
*
****************************************************************************/
LogWriter::LogWriter(void)
{
// Create a pipe to route stdout and stderr through
if (pipe(m_pipefd) == -1)
{
perror("pipe");
exit(1);
}
} /* LogWriter::LogWriter */
LogWriter::~LogWriter(void)
{
stop();
} /* LogWriter::~LogWriter */
void LogWriter::setTimestampFormat(const std::string& fmt)
{
const std::lock_guard<std::mutex> lock(m_mutex);
m_tstamp_format = fmt;
if (m_worker != nullptr)
{
m_worker->setTimestampFormat(fmt);
}
} /* LogWriter::setTimestampFormat */
void LogWriter::setDestinationName(const std::string& name)
{
m_dest_name = name;
} /* LogWriter::setDestinationName */
void LogWriter::start(void)
{
m_logthread = std::thread(&LogWriter::writerThread, this);
} /* LogWriter::start */
void LogWriter::stop(void)
{
logFlush();
if (m_pipefd[1] != -1)
{
write(m_pipefd[1], "\0", 1);
close(m_pipefd[1]);
m_pipefd[1] = -1;
}
if (m_logthread.joinable())
{
m_logthread.join();
}
if (m_pipefd[0] != -1)
{
close(m_pipefd[0]);
m_pipefd[0] = -1;
}
//m_worker->logClose();
} /* LogWriter::stop */
void LogWriter::reopenLogfile(void)
{
m_reopen_log = true;
} /* LogWriter::reopenLogfile */
void LogWriter::redirectStdout(void)
{
// Redirect stdout to the logpipe
if (dup2(m_pipefd[1], STDOUT_FILENO) == -1)
{
perror("dup2(stdout)");
exit(1);
}
// Force stdout to line buffered mode
if (setvbuf(stdout, NULL, _IOLBF, 0) != 0)
{
perror("setvbuf(stdout, NULL, _IOLBF, 0)");
exit(1);
}
} /* LogWriter::redirectStdout */
void LogWriter::redirectStderr(void)
{
// Redirect stderr to the logpipe
if (dup2(m_pipefd[1], STDERR_FILENO) == -1)
{
perror("dup2(stderr)");
exit(1);
}
} /* LogWriter::redirectStderr */
/****************************************************************************
*
* Protected member functions
*
****************************************************************************/
/****************************************************************************
*
* Private member functions
*
****************************************************************************/
void LogWriter::writerThread(void)
{
{
const std::lock_guard<std::mutex> lock(m_mutex);
if (m_dest_name == "syslog:")
{
m_worker = new LogWriterWorkerSyslog;
}
else
{
m_worker = new LogWriterWorkerFile(m_dest_name);
}
m_worker->setTimestampFormat(m_tstamp_format);
if (!m_worker->logOpen())
{
abort();
}
}
for (;;)
{
char buf[256];
auto len = read(m_pipefd[0], buf, sizeof(buf)-1);
if ((len <= 0) || (buf[len-1] == '\0'))
{
break;
}
buf[len] = 0;
const std::lock_guard<std::mutex> lock(m_mutex);
m_worker->logWrite(buf);
if (m_reopen_log)
{
m_worker->logReopen("Reopen requested");
m_reopen_log = false;
}
}
const std::lock_guard<std::mutex> lock(m_mutex);
//m_worker->logWrite("### logwriter exited\n");
delete m_worker;
m_worker = nullptr;
} /* LogWriter::writerThread */
void LogWriter::logFlush(void)
{
std::cout.flush();
std::cerr.flush();
} /* LogWriter::logFlush */
LogWriter::LogWriterWorkerFile::LogWriterWorkerFile(const std::string& filename)
: m_logfile_name(filename)
{
} /* LogWriter::LogWriterWorkerFile::LogWriterWorkerFile */
void LogWriter::LogWriterWorkerFile::setTimestampFormat(const std::string& fmt)
{
m_tstamp_format = fmt;
} /* LogWriter::LogWriterWorkerFile::setTimestampFormat */
bool LogWriter::LogWriterWorkerFile::logOpen(void)
{
logClose();
m_logfd = open(m_logfile_name.c_str(), O_WRONLY | O_APPEND | O_CREAT, 00644);
if (m_logfd == -1)
{
//std::cerr << "open(\"" << m_logfile_name << "\"): " << strerror(errno)
// << std::endl;
return false;
}
return true;
} /* LogWriter::LogWriterWorkerFile::logOpen */
void LogWriter::LogWriterWorkerFile::logClose(void)
{
if (m_logfd != -1)
{
close(m_logfd);
m_logfd = -1;
}
} /* LogWriter::LogWriterWorkerFile::logClose */
void LogWriter::LogWriterWorkerFile::logReopen(std::string reason)
{
if (!reason.empty())
{
reason += ". ";
}
logWriteTimestamp();
std::string msg(reason);
msg += "Reopening logfile...\n";
if (write(m_logfd, msg.c_str(), msg.size()) == -1)
{
abort();
}
if (!logOpen())
{
abort();
}
logWriteTimestamp();
msg = reason;
msg += "Logfile reopened.\n";
if (write(m_logfd, msg.c_str(), msg.size()) == -1)
{
abort();
}
} /* LogWriter::LogWriterWorkerFile::logReopen */
bool LogWriter::LogWriterWorkerFile::logWriteTimestamp(void)
{
if (!m_tstamp_format.empty())
{
struct timeval tv;
gettimeofday(&tv, NULL);
std::string fmt(m_tstamp_format);
const std::string frac_code("%f");
size_t pos = fmt.find(frac_code);
if (pos != std::string::npos)
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(3) << (tv.tv_usec / 1000);
fmt.replace(pos, frac_code.length(), ss.str());
}
struct tm tm;
char tstr[256];
size_t tlen = strftime(tstr, sizeof(tstr), fmt.c_str(),
localtime_r(&tv.tv_sec, &tm));
ssize_t ret = write(m_logfd, tstr, tlen);
if (ret != static_cast<ssize_t>(tlen))
{
return false;
}
ret = write(m_logfd, ": ", 2);
if (ret != 2)
{
return false;
}
}
return true;
} /* LogWriter::LogWriterWorkerFile::logWriteTimestamp */
void LogWriter::LogWriterWorkerFile::logWrite(const char *buf)
{
if (m_logfd == -1)
{
return;
}
const char *ptr = buf;
while (*ptr != 0)
{
static bool print_timestamp = true;
ssize_t ret;
if (print_timestamp)
{
if (!logWriteTimestamp())
{
logReopen("Write error");
return;
}
print_timestamp = false;
}
size_t write_len = 0;
const char *nl = strchr(ptr, '\n');
if (nl != 0)
{
write_len = nl-ptr+1;
print_timestamp = true;
}
else
{
write_len = strlen(ptr);
}
ret = write(m_logfd, ptr, write_len);
if (ret != static_cast<ssize_t>(write_len))
{
logReopen("Write error");
return;
}
ptr += write_len;
}
} /* LogWriter::LogWriterWorkerFile::logWrite */
void LogWriter::LogWriterWorkerSyslog::logWrite(const char* buf)
{
m_buf.append(buf);
std::string::size_type pos;
while ((pos = m_buf.find ('\n')) != std::string::npos)
{
std::string line(m_buf, 0, pos);
m_buf.erase(0, pos + 1);
int loglevel = LOG_INFO;
if (line.rfind("*** ERROR", 0) == 0)
{
loglevel = LOG_ERR;
}
else if (line.rfind("*** WARNING", 0) == 0)
{
loglevel = LOG_WARNING;
}
else if (line.rfind("NOTICE", 0) == 0)
{
loglevel = LOG_NOTICE;
}
else if (line.rfind("### ", 0) == 0)
{
loglevel = LOG_DEBUG;
}
syslog(LOG_DAEMON | loglevel, "%s", line.c_str());
}
} /* LogWriter::LogWriterWorkerSyslog::logWrite */
/*
* This file has not been truncated
*/
+200
View File
@@ -0,0 +1,200 @@
/**
@file LogWriter.h
@brief A class for writing stdout and stderr to a logfile or syslog
@author Tobias Blomberg / SM0SVX
@date 2025-06-11
\verbatim
SvxLink - A Multi Purpose Voice Services System for Ham Radio Use
Copyright (C) 2003-2025 Tobias Blomberg / SM0SVX
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
*/
#ifndef LOG_WRITER_INCLUDED
#define LOG_WRITER_INCLUDED
/****************************************************************************
*
* System Includes
*
****************************************************************************/
#include <string>
#include <thread>
#include <atomic>
#include <mutex>
/****************************************************************************
*
* Project Includes
*
****************************************************************************/
/****************************************************************************
*
* Local Includes
*
****************************************************************************/
/****************************************************************************
*
* Forward declarations
*
****************************************************************************/
/****************************************************************************
*
* Namespace
*
****************************************************************************/
/****************************************************************************
*
* Forward declarations of classes inside of the declared namespace
*
****************************************************************************/
/****************************************************************************
*
* Defines & typedefs
*
****************************************************************************/
/****************************************************************************
*
* Exported Global Variables
*
****************************************************************************/
/****************************************************************************
*
* Class definitions
*
****************************************************************************/
/**
@brief A class for writing stdout and stderr to a logfile or syslog
@author Tobias Blomberg / SM0SVX
@date 2025-06-11
This is a threaded logging class for routing stdout and stderr to a logfile or
to syslog.
When writing to a file, each row will be prefixed with a timestamp.
When writing to syslog, the timestamp format in SvxLink is ignored.
*/
class LogWriter
{
public:
/**
* @brief Default constructor
*/
LogWriter(void);
/**
* @brief Disallow copy construction
*/
LogWriter(const LogWriter&) = delete;
/**
* @brief Disallow copy assignment
*/
LogWriter& operator=(const LogWriter&) = delete;
/**
* @brief Destructor
*/
~LogWriter(void);
/**
* @brief Set the format used for writing timestamps to file
* @param format A strftime format string
*/
void setTimestampFormat(const std::string& fmt);
/**
* @brief Set the name of the logging destination
* @param name Either a path to a logfile or the literal "syslog:"
*/
void setDestinationName(const std::string& name);
/**
* @brief Start the logger thread
*/
void start(void);
/**
* @brief Stop the logger thread
*/
void stop(void);
/**
* @brief Reopen the logfile before writing the next log row
*/
void reopenLogfile(void);
/**
* @brief Call this function to redirect stdout to the logger
*/
void redirectStdout(void);
/**
* @brief Call this function to redirect stderr to the logger
*/
void redirectStderr(void);
private:
class LogWriterWorker;
class LogWriterWorkerFile;
class LogWriterWorkerSyslog;
std::string m_dest_name;
std::string m_tstamp_format {"%c"};
std::atomic_bool m_reopen_log;
int m_pipefd[2] {-1, -1};
std::thread m_logthread;
std::mutex m_mutex;
LogWriterWorker* m_worker {nullptr};
void writerThread(void);
void logFlush(void);
}; /* class LogWriter */
#endif /* LOG_WRITER_INCLUDED */
/*
* This file has not been truncated
*/
+14
View File
@@ -0,0 +1,14 @@
#include <string>
#include "common.h"
namespace SvxLink
{
bool setValueFromString(std::string &val, const std::string &str)
{
val = str;
return true;
} /* setValueFromString */
}; /* namespace SvxLink */
+287
View File
@@ -0,0 +1,287 @@
/**
@file common.h
@brief Contains some commonly used global functions
@author Tobias Blomberg / SM0SVX
@date 2010-04-05
\verbatim
SvxLink - A Multi Purpose Voice Services System for Ham Radio Use
Copyright (C) 2003-2025 Tobias Blomberg / SM0SVX
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
*/
#ifndef COMMON_INCLUDED
#define COMMON_INCLUDED
/****************************************************************************
*
* System Includes
*
****************************************************************************/
#include <utility>
#include <sstream>
#include <istream>
#include <ostream>
#include <cstring>
#include <cassert>
/****************************************************************************
*
* Project Includes
*
****************************************************************************/
/****************************************************************************
*
* Local Includes
*
****************************************************************************/
/****************************************************************************
*
* Forward declarations
*
****************************************************************************/
/****************************************************************************
*
* Namespace
*
****************************************************************************/
namespace SvxLink
{
/****************************************************************************
*
* Forward declarations of classes inside of the declared namespace
*
****************************************************************************/
/****************************************************************************
*
* Defines & typedefs
*
****************************************************************************/
/****************************************************************************
*
* Exported Global Variables
*
****************************************************************************/
/****************************************************************************
*
* Global functions
*
****************************************************************************/
/**
* @brief Set a value of any type supporting streaming from a string
* @param val Reference to the value to set
* @param str The sting to set the value from
* @returns Returns \em true if the operation succeeded or \em false if not
*
* This function use the streaming operator to set the outgoing value from the
* incoming string so any type that support the streaming operator will work.
* All characters in the string must be consumed for the parser to indicate
* success.
*/
template <typename ValueType>
bool setValueFromString(ValueType &val, const std::string &str)
{
std::istringstream ss(str);
ss >> std::noskipws >> val;
if(!ss.eof())
{
ss >> std::ws;
}
return !ss.fail() && ss.eof();
} /* setValueFromString */
/**
* @brief Set a value of any type supporting streaming from a string
* @param val Reference to the value to set
* @param str The sting to set the value from
* @returns Returns \em true if the operation succeeded or \em false if not
*
* This function overload the more general template function when the value
* to be set is an std::string. It just copies the incoming string to the
* outgoing value. If streaming were to be used for strings, white space
* would be unconditionally ignored.
*/
bool setValueFromString(std::string &val, const std::string &str);
/**
* @brief Split a string using a set of delimiters and put the tokens in a
* container
* @param L The container to put the tokens into. Any container that
* supports the clear, size and push_back methods can be used.
* @param seq The string to split
* @param delims The set of delimiters used to split the string. Be sure to
* include any white space characters that you want to ignore.
* @returns Returns the number of tokens stored in the container
*
* This is a template function that is used to split strings into tokens,
* storing the tokens into a container. The container can be of any type that
* supports the clear, size and insert methods (e.g. vector, list, deque,
* set etc). Insertions will be done at the end of the container.
*
* The container value type may be any that supports setting a value by
* streaming to it (e.g. std::string, int, float, char etc).
*
* If a parsed value is malformed, in a way so that it cannot be parsed into
* the given container value type, it will be ignored.
*
* Empty values will not be stored.
*/
template <class Container>
static typename Container::size_type splitStr(Container &L,
const std::string &seq,
const std::string &delims)
{
L.clear();
std::string::size_type pos = 0;
std::string::size_type len = seq.size();
while (pos < len)
{
// remove any delimiters including optional (white)spaces
while ((delims.find(seq[pos]) != std::string::npos) && (pos < len))
{
pos++;
}
// Save token data
std::string str;
while ((delims.find(seq[pos]) == std::string::npos) && (pos < len))
{
str += seq[pos++];
}
// Put valid str buffer into the supplied list. If the specified string
// does not match the value type, it is skipped.
if (!str.empty())
{
typename Container::value_type val;
if (setValueFromString(val, str))
{
L.insert(L.end(), val);
}
}
}
return L.size();
} /* splitStr */
/**
* @brief A pair type with separator which can be streamed
* @param a The first type in the pair
* @param b The second type in the pair
* @param sep The character used to separate the two values (default colon)
*
* This class was created to make it easy to stream a pair type in or out.
* For example, if we read the string "100.5:1000" from an input stream and
* we declare the variable "SepPair<float, unsigned> my_pair", we can write
* "is >> my_pair". Then we have my_pair.first == 100.5 and
* my_pair.second == 1000.
*/
template <typename a, typename b, char sep=':'>
class SepPair : public std::pair<a, b>
{
public:
friend std::istream &operator>>(std::istream &is, SepPair &cp)
{
std::string value;
is >> value;
std::string::size_type seppos = value.find(sep);
if (seppos == std::string::npos)
{
is.setstate(std::ios_base::failbit);
return is;
}
std::string first(value.substr(0, seppos));
std::string second(value.substr(seppos+1));
if (!setValueFromString(cp.first, first) ||
!setValueFromString(cp.second, second))
{
is.setstate(std::ios_base::failbit);
}
return is;
}
friend std::ostream &operator<<(std::ostream &output, SepPair &cp)
{
output << cp.first << sep << cp.second;
return output;
}
};
static inline const char* strError(int errnum)
{
static thread_local struct
{
char errstr[256];
// XSI version of strerror_r
const char* operator()(int ret)
{
assert(ret == 0);
return errstr;
}
// GNU version of strerror_r
const char* operator()(char* ret)
{
return ret;
}
} wrap;
return wrap(strerror_r(errno, wrap.errstr, sizeof(wrap.errstr)));
} /* strError */
} /* namespace */
#endif /* COMMON_INCLUDED */
/*
* This file has not been truncated
*/