Initialization with Hard-Coded Network Resource Configuration Data

Description

Initialization with Hard-Coded Network Resource Configuration Data occurs when software initializes data using hard-coded values that act as network resource identifiers. This includes embedding IP addresses, hostnames, port numbers, URLs, API endpoints, or other network configuration directly in source code rather than using external configuration files, environment variables, or dynamic discovery mechanisms. Such hard-coding makes the software inflexible and can cause failures when deployed in different network environments.

Risk

While primarily a reliability and maintainability concern, hard-coded network configuration has security implications. Hard-coded credentials or endpoints may be extracted from compiled code. Changing compromised endpoints requires code changes and redeployment rather than configuration updates. Internal network addresses exposed in code can reveal infrastructure details to attackers. Applications may fail to switch to backup or failover systems. Security patches for endpoint changes become slower to deploy. In some cases, hard-coded values may point to test or development environments that lack production security controls.

Solution

Externalize network configuration using: (1) Configuration files (with proper access controls), (2) Environment variables, (3) Service discovery mechanisms, (4) Container orchestration configuration (Kubernetes ConfigMaps, etc.), (5) Centralized configuration services (Consul, etcd, Spring Cloud Config). Provide sensible defaults while allowing override. Validate configuration at startup. Use DNS names instead of IP addresses where possible. Implement configuration refresh mechanisms for runtime updates. Encrypt sensitive network configuration like API keys or authentication endpoints.

Common Consequences

ImpactDetails
OtherScope: Other

Reduce Reliability - Application may fail in environments that don't match the hard-coded network identifiers.
OtherScope: Other

Reduce Maintainability - Changing network configuration requires code changes, slowing security response.
ConfidentialityScope: Confidentiality

Information Exposure - Hard-coded internal addresses in code may reveal infrastructure details.

Example Code

Vulnerable Code

// Vulnerable: Hard-coded network configuration
public class VulnerableApiClient {

    // Vulnerable: Hard-coded URL
    private static final String API_URL = "https://api.production.example.com:8443";

    // Vulnerable: Hard-coded IP address
    private static final String DATABASE_HOST = "192.168.1.100";
    private static final int DATABASE_PORT = 5432;

    // Vulnerable: Hard-coded backup server
    private static final String BACKUP_SERVER = "10.0.0.50";

    public void connect() {
        // These values cannot be changed without recompiling
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(API_URL + "/health"))
            .build();

        // If API_URL becomes compromised or changes, code must be modified
    }

    public Connection getDbConnection() {
        String url = "jdbc:postgresql://" + DATABASE_HOST + ":" + DATABASE_PORT + "/mydb";
        return DriverManager.getConnection(url, "user", "pass");
    }
}
# Vulnerable: Hard-coded endpoints in Python
class VulnerableService:

    # Vulnerable: Hard-coded configuration
    API_ENDPOINT = "https://internal-api.company.local:8080"
    REDIS_HOST = "172.16.0.10"
    REDIS_PORT = 6379
    MESSAGE_QUEUE = "amqp://10.0.1.50:5672"

    def __init__(self):
        # All connections use hard-coded values
        self.redis = redis.Redis(host=self.REDIS_HOST, port=self.REDIS_PORT)
        self.mq = pika.BlockingConnection(
            pika.URLParameters(self.MESSAGE_QUEUE)
        )

    def call_api(self, endpoint):
        # Cannot change API server without code modification
        return requests.get(f"{self.API_ENDPOINT}/{endpoint}")
// Vulnerable: Hard-coded configuration in C#
public class VulnerableEmailService
{
    // Vulnerable: Hard-coded SMTP configuration
    private const string SmtpHost = "smtp.internal.company.com";
    private const int SmtpPort = 587;
    private const string SmtpUser = "[email protected]";

    // Vulnerable: Hard-coded API gateway
    private const string AuthServiceUrl = "https://auth.company.com:443/api/v1";

    public void SendEmail(string to, string subject, string body)
    {
        using var client = new SmtpClient(SmtpHost, SmtpPort);
        // Configuration locked to specific server
        client.Send(SmtpUser, to, subject, body);
    }

    public bool ValidateToken(string token)
    {
        // Hard-coded auth service - cannot switch to backup
        var response = httpClient.GetAsync($"{AuthServiceUrl}/validate?token={token}");
        return response.Result.IsSuccessStatusCode;
    }
}
// Vulnerable: Hard-coded network config in Go
package main

const (
    // Vulnerable: Hard-coded addresses
    DatabaseURL   = "postgres://user:[email protected]:5432/production"
    CacheServer   = "memcache.internal:11211"
    MetricsServer = "http://10.0.0.100:9090/metrics"
    LogServer     = "logs.company.local:514"
)

func connectToServices() {
    // All connections use compile-time constants
    db, _ := sql.Open("postgres", DatabaseURL)
    cache := memcache.New(CacheServer)
    // Cannot change without recompiling
}

Fixed Code

// Fixed: Externalized network configuration
public class FixedApiClient {

    private final String apiUrl;
    private final String databaseHost;
    private final int databasePort;

    // Fixed: Configuration injected via constructor
    public FixedApiClient(NetworkConfig config) {
        this.apiUrl = config.getApiUrl();
        this.databaseHost = config.getDatabaseHost();
        this.databasePort = config.getDatabasePort();
    }

    // Alternative: Load from configuration file
    public static FixedApiClient fromConfig() {
        Properties props = loadProperties("network.properties");
        return new FixedApiClient(
            new NetworkConfig(
                props.getProperty("api.url"),
                props.getProperty("database.host"),
                Integer.parseInt(props.getProperty("database.port"))
            )
        );
    }

    // Alternative: Load from environment variables
    public static FixedApiClient fromEnvironment() {
        return new FixedApiClient(
            new NetworkConfig(
                System.getenv("API_URL"),
                System.getenv("DB_HOST"),
                Integer.parseInt(System.getenv("DB_PORT"))
            )
        );
    }
}

// Configuration class with validation
public class NetworkConfig {
    private final String apiUrl;
    private final String databaseHost;
    private final int databasePort;

    public NetworkConfig(String apiUrl, String databaseHost, int databasePort) {
        // Validate configuration
        Objects.requireNonNull(apiUrl, "API URL is required");
        Objects.requireNonNull(databaseHost, "Database host is required");
        if (databasePort < 1 || databasePort > 65535) {
            throw new IllegalArgumentException("Invalid port number");
        }

        this.apiUrl = apiUrl;
        this.databaseHost = databaseHost;
        this.databasePort = databasePort;
    }

    // Getters...
}
# Fixed: Configuration-based network settings
import os
from dataclasses import dataclass
from typing import Optional
import yaml

@dataclass
class NetworkConfig:
    api_endpoint: str
    redis_host: str
    redis_port: int
    message_queue: str

    @classmethod
    def from_environment(cls) -> 'NetworkConfig':
        """Load configuration from environment variables"""
        return cls(
            api_endpoint=os.environ['API_ENDPOINT'],
            redis_host=os.environ.get('REDIS_HOST', 'localhost'),
            redis_port=int(os.environ.get('REDIS_PORT', '6379')),
            message_queue=os.environ['MESSAGE_QUEUE_URL']
        )

    @classmethod
    def from_file(cls, path: str) -> 'NetworkConfig':
        """Load configuration from YAML file"""
        with open(path) as f:
            config = yaml.safe_load(f)

        return cls(
            api_endpoint=config['api']['endpoint'],
            redis_host=config['redis']['host'],
            redis_port=config['redis']['port'],
            message_queue=config['messaging']['url']
        )

    def validate(self):
        """Validate configuration values"""
        if not self.api_endpoint.startswith('https://'):
            raise ValueError("API endpoint must use HTTPS")
        if not 1 <= self.redis_port <= 65535:
            raise ValueError("Invalid Redis port")


class FixedService:
    def __init__(self, config: NetworkConfig):
        config.validate()
        self.config = config
        self.redis = redis.Redis(
            host=config.redis_host,
            port=config.redis_port
        )
        self.mq = pika.BlockingConnection(
            pika.URLParameters(config.message_queue)
        )

    def call_api(self, endpoint):
        return requests.get(f"{self.config.api_endpoint}/{endpoint}")


# Usage
config = NetworkConfig.from_environment()
# or
config = NetworkConfig.from_file('/etc/myapp/network.yaml')
service = FixedService(config)
// Fixed: Configuration-driven network settings in C#
public class NetworkSettings
{
    public string SmtpHost { get; set; }
    public int SmtpPort { get; set; }
    public string SmtpUser { get; set; }
    public string AuthServiceUrl { get; set; }
}

public class FixedEmailService
{
    private readonly NetworkSettings _settings;
    private readonly HttpClient _httpClient;

    // Fixed: Configuration injected
    public FixedEmailService(IOptions<NetworkSettings> settings, HttpClient httpClient)
    {
        _settings = settings.Value;
        _httpClient = httpClient;
        ValidateSettings();
    }

    private void ValidateSettings()
    {
        if (string.IsNullOrEmpty(_settings.SmtpHost))
            throw new ConfigurationException("SMTP host is required");
        if (_settings.SmtpPort < 1 || _settings.SmtpPort > 65535)
            throw new ConfigurationException("Invalid SMTP port");
    }

    public void SendEmail(string to, string subject, string body)
    {
        using var client = new SmtpClient(_settings.SmtpHost, _settings.SmtpPort);
        client.Send(_settings.SmtpUser, to, subject, body);
    }

    public async Task<bool> ValidateToken(string token)
    {
        var response = await _httpClient.GetAsync(
            $"{_settings.AuthServiceUrl}/validate?token={token}");
        return response.IsSuccessStatusCode;
    }
}

// appsettings.json
/*
{
    "NetworkSettings": {
        "SmtpHost": "smtp.company.com",
        "SmtpPort": 587,
        "SmtpUser": "[email protected]",
        "AuthServiceUrl": "https://auth.company.com/api/v1"
    }
}
*/

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<NetworkSettings>(Configuration.GetSection("NetworkSettings"));
    services.AddHttpClient<FixedEmailService>();
}
// Fixed: Configuration-based network settings in Go
package main

import (
    "encoding/json"
    "os"
)

type NetworkConfig struct {
    DatabaseURL   string `json:"database_url" env:"DATABASE_URL"`
    CacheServer   string `json:"cache_server" env:"CACHE_SERVER"`
    MetricsServer string `json:"metrics_server" env:"METRICS_SERVER"`
    LogServer     string `json:"log_server" env:"LOG_SERVER"`
}

func LoadConfig() (*NetworkConfig, error) {
    config := &NetworkConfig{}

    // Try environment variables first (for containers/12-factor apps)
    config.DatabaseURL = os.Getenv("DATABASE_URL")
    config.CacheServer = os.Getenv("CACHE_SERVER")
    config.MetricsServer = os.Getenv("METRICS_SERVER")
    config.LogServer = os.Getenv("LOG_SERVER")

    // Fall back to config file
    if config.DatabaseURL == "" {
        file, err := os.Open("/etc/myapp/config.json")
        if err != nil {
            return nil, err
        }
        defer file.Close()

        if err := json.NewDecoder(file).Decode(config); err != nil {
            return nil, err
        }
    }

    if err := config.Validate(); err != nil {
        return nil, err
    }

    return config, nil
}

func (c *NetworkConfig) Validate() error {
    if c.DatabaseURL == "" {
        return fmt.Errorf("database URL is required")
    }
    // Additional validation...
    return nil
}

func connectToServices(config *NetworkConfig) {
    db, _ := sql.Open("postgres", config.DatabaseURL)
    cache := memcache.New(config.CacheServer)
    // Configuration can be changed without recompiling
}

CVE Examples

This CWE is marked as PROHIBITED for direct CVE mapping as it represents a quality/reliability concern rather than a direct security vulnerability.


  • CWE-1419: Incorrect Initialization of Resource (parent)
  • CWE-452: Initialization and Cleanup Errors (category member)
  • CWE-547: Use of Hard-coded, Security-relevant Constants (related)

References

  1. MITRE Corporation. "CWE-1051: Initialization with Hard-Coded Network Resource Configuration Data." https://cwe.mitre.org/data/definitions/1051.html
  2. The Twelve-Factor App. "Configuration."
  3. OWASP. "Configuration and Deployment Management Testing."