Skip to content

Instantly share code, notes, and snippets.

@anubhavg-icpl
Created September 21, 2024 19:10
Show Gist options
  • Save anubhavg-icpl/29c69ba5b4c10041ed906d2f32857e59 to your computer and use it in GitHub Desktop.
Save anubhavg-icpl/29c69ba5b4c10041ed906d2f32857e59 to your computer and use it in GitHub Desktop.

CoreDNS: A Comprehensive Overview

Table of Contents

  1. Introduction
  2. Installation
  3. Configuration
  4. Plugins
  5. Server Blocks
  6. Common Setups
  7. Writing Plugins
  8. Best Practices

Introduction

CoreDNS is a flexible, extensible DNS server written in Go. Unlike traditional DNS servers, CoreDNS relies heavily on plugins to provide functionality. This modular approach allows for great customization and extensibility.

Key features of CoreDNS:

  • Written in Go
  • Plugin-based architecture
  • Supports various protocols: DNS, DNS over TLS (DoT), DNS over HTTPS (DoH), and DNS over gRPC
  • Highly configurable

Installation

There are several ways to install CoreDNS:

  1. Pre-compiled binaries: Available for various operating systems and architectures.
  2. Docker: Images are available on the public Docker hub.
  3. From source: Requires a working Go setup and uses Go modules for dependency management.

To test a basic CoreDNS installation:

$ ./coredns -dns.port=1053
$ dig @localhost -p 1053 a whoami.example.org

Configuration

CoreDNS uses a file called Corefile for configuration. The Corefile consists of one or more Server Blocks, each containing plugin configurations.

Environment Variables

CoreDNS supports environment variable substitution in its configuration using the syntax {$ENV_VAR} or {%ENV_VAR%}.

Importing Other Files

The import plugin allows including other configuration files or snippets.

Reusable Snippets

Snippets are defined using parentheses and can be imported into other parts of the configuration:

(snip) {
    prometheus
    log
    errors
}

. {
    whoami
    import snip
}

Plugins

Plugins are the core of CoreDNS functionality. They can:

  • Process queries
  • Forward queries
  • Modify responses
  • Implement non-DNS functionality (e.g., metrics, health checks)

The order of plugins in the Corefile does not determine execution order. The execution order is defined in plugin.cfg.

Example plugin configuration:

. {
    chaos CoreDNS-001 [email protected]
}

Server Blocks

Server Blocks define the zones a server is responsible for and the port it listens on. The basic syntax is:

zone:port {
    plugin1
    plugin2
}

Multiple zones can be specified in a single Server Block.

Common Setups

Authoritative Serving from Files

Use the file plugin to serve zone data from a file:

example.org {
    file db.example.org
    log
}

Forwarding

Forward queries to other DNS servers:

. {
    forward . 8.8.8.8 9.9.9.9
    log
}

Recursive Resolver

Use the unbound plugin (requires recompilation) for recursive resolution:

. {
    unbound
    cache
    log
}

Writing Plugins

To write a custom plugin:

  1. Create a setup.go file for Corefile parsing
  2. Implement the plugin logic in a separate file (e.g., example.go)
  3. Write tests
  4. Create a README.md documenting the plugin
  5. Include a LICENSE file

Plugins should implement the plugin.Handler interface, which includes the ServeDNS method.

Best Practices

  1. Use example.org or example.net in examples and tests
  2. Implement fallthrough functionality when appropriate
  3. Follow the style guide for documentation
  4. Include metrics and readiness reporting
  5. Use proper logging practices

Remember to check the CoreDNS website and GitHub repository for the most up-to-date information and best practices.

@mranv
Copy link

mranv commented Sep 21, 2024

CoreDNS: Essential Code Examples

Table of Contents

  1. Basic Configuration
  2. Plugin Examples
  3. Advanced Setups
  4. Custom Plugin Development

Basic Configuration

Minimal Corefile

. {
    whoami
    log
}

This configuration will respond to all queries with the client's IP address and log each query.

Serving a Zone File

example.org {
    file db.example.org
    log
}

Corresponding db.example.org file:

$ORIGIN example.org.
@	3600 IN	SOA sns.dns.icann.org. noc.dns.icann.org. (
				2017042745 ; serial
				7200       ; refresh (2 hours)
				3600       ; retry (1 hour)
				1209600    ; expire (2 weeks)
				3600       ; minimum (1 hour)
				)

	3600 IN NS a.iana-servers.net.
	3600 IN NS b.iana-servers.net.

www     IN A     127.0.0.1
        IN AAAA  ::1

Plugin Examples

Forwarding

Forward all queries to Google Public DNS and Quad9:

. {
    forward . 8.8.8.8 9.9.9.9
    log
}

Caching

Enable caching for all queries:

. {
    cache 3600
    forward . 8.8.8.8 9.9.9.9
    log
}

Multiple Zones

Handle multiple zones with different configurations:

example.com {
    file db.example.com
    log
}

example.org {
    forward . 192.168.1.10
    log
}

. {
    forward . 8.8.8.8
    log
}

Advanced Setups

DNS over TLS (DoT)

.:853 {
    tls cert.pem key.pem
    whoami
    log
}

Kubernetes Service Discovery

.:53 {
    errors
    log
    health
    kubernetes cluster.local in-addr.arpa ip6.arpa {
        pods insecure
        upstream
        fallthrough in-addr.arpa ip6.arpa
    }
    prometheus :9153
    forward . /etc/resolv.conf
    cache 30
    loop
    reload
    loadbalance
}

Reusable Snippets

(common) {
    errors
    log
    prometheus
    cache 300
}

example.com {
    file db.example.com
    import common
}

example.org {
    forward . 8.8.8.8
    import common
}

Custom Plugin Development

Basic Plugin Structure

package example

import (
    "github.com/coredns/coredns/plugin"
    "github.com/coredns/coredns/request"
    "github.com/miekg/dns"
    "golang.org/x/net/context"
)

type Example struct {
    Next plugin.Handler
}

func (e Example) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
    state := request.Request{W: w, Req: r}
    qname := state.Name()

    // Plugin logic here
    a := new(dns.Msg)
    a.SetReply(r)
    a.Authoritative = true

    rr := new(dns.A)
    rr.Hdr = dns.RR_Header{Name: qname, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 3600}
    rr.A = net.ParseIP("192.0.2.1")
    a.Answer = []dns.RR{rr}

    w.WriteMsg(a)
    return dns.RcodeSuccess, nil
}

func (e Example) Name() string { return "example" }

var _ plugin.Handler = Example{}

Plugin Setup Function

func setup(c *caddy.Controller) error {
    c.Next() // Ignore "example" token
    if c.NextArg() {
        return plugin.Error("example", c.ArgErr())
    }

    dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
        return Example{Next: next}
    })

    return nil
}

These code examples demonstrate various aspects of CoreDNS configuration and plugin development. They cover basic setups, advanced configurations, and custom plugin creation, providing a solid foundation for working with CoreDNS.

@mranv
Copy link

mranv commented Sep 21, 2024

Secure Service Mesh Setup Guide with CoreDNS and OpenXPKI/EJBCA

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Set Up Cilium on Linux VMs
  4. Install and Configure CoreDNS
  5. Set Up Certificate Authority (OpenXPKI or EJBCA)
  6. Configure Services for mTLS
  7. Integrate Cilium with Certificate-based Authentication
  8. Test and Validate the Setup

1. Introduction

This guide will walk you through setting up a secure service mesh using Cilium, CoreDNS, and either OpenXPKI or EJBCA for certificate management. This setup will provide service discovery, mutual TLS (mTLS) authentication, and network policy enforcement without the need for Kubernetes.

2. Prerequisites

  • Multiple Linux VMs (preferably Ubuntu 20.04 or later)
  • Root access to all VMs
  • Basic understanding of networking, DNS, and PKI concepts

3. Set Up Cilium on Linux VMs

  1. Install Cilium on each VM:

    curl -L --remote-name-all https://github.com/cilium/cilium-cli/releases/latest/download/cilium-linux-amd64.tar.gz
    sudo tar xzvfC cilium-linux-amd64.tar.gz /usr/local/bin
    rm cilium-linux-amd64.tar.gz
  2. Configure Cilium in standalone mode:

    Create a file /etc/cilium/cilium.yaml with the following content:

    devices:
    - eth0
    tunnel: vxlan
    ipam:
      type: cluster-pool
      pool:
        cidr: 10.0.0.0/16
  3. Start Cilium:

    sudo cilium-agent --config /etc/cilium/cilium.yaml

4. Install and Configure CoreDNS

  1. Install CoreDNS:

    wget https://github.com/coredns/coredns/releases/download/v1.8.6/coredns_1.8.6_linux_amd64.tgz
    tar xzf coredns_1.8.6_linux_amd64.tgz
    sudo mv coredns /usr/local/bin/
  2. Create a CoreDNS configuration file /etc/coredns/Corefile:

    .:53 {
        etcd {
            path /coredns
            endpoint http://localhost:2379
        }
        forward . 8.8.8.8
        log
        errors
    }
    
    internal.cluster.local:53 {
        etcd {
            path /coredns
            endpoint http://localhost:2379
        }
        auto
        log
        errors
    }
    
  3. Install and configure etcd:

    sudo apt-get update
    sudo apt-get install -y etcd
  4. Start CoreDNS:

    sudo coredns -conf /etc/coredns/Corefile
  5. Update /etc/resolv.conf on all VMs to use CoreDNS:

    nameserver <CoreDNS_VM_IP>
    search internal.cluster.local
    

5. Set Up Certificate Authority (OpenXPKI or EJBCA)

Choose either OpenXPKI or EJBCA as your Certificate Authority:

Option A: OpenXPKI

  1. Install OpenXPKI:

    sudo apt-get update
    sudo apt-get install -y openxpki
  2. Configure OpenXPKI (basic setup):

    sudo openxpkiadm init
    sudo openxpkiadm certificate import --file /etc/ssl/certs/ca-certificates.crt
  3. Create a Root CA and Issuing CA:

    sudo openxpkiadm ca import --file root-ca.pem --realm ca-one
    sudo openxpkiadm ca import --file issuing-ca.pem --realm ca-one --issuer root-ca

Option B: EJBCA

  1. Install EJBCA:

    wget https://sourceforge.net/projects/ejbca/files/ejbca6/ejbca_6_15_2_6/ejbca-ce-6.15.2.6.zip
    unzip ejbca-ce-6.15.2.6.zip
    cd ejbca-ce-6.15.2.6
    ant deploy
  2. Configure EJBCA (basic setup):

    sudo /opt/ejbca/bin/ejbca.sh ca init --caname "MyRootCA" --dn "CN=My Root CA,O=My Organization,C=US"
    sudo /opt/ejbca/bin/ejbca.sh ca init --caname "MyIssuingCA" --dn "CN=My Issuing CA,O=My Organization,C=US"

6. Configure Services for mTLS

For each service:

  1. Generate a certificate signing request (CSR):

    openssl req -new -newkey rsa:2048 -nodes -keyout service.key -out service.csr
  2. Submit the CSR to your CA (OpenXPKI or EJBCA) and obtain a signed certificate.

  3. Configure your service to use the certificate and private key for mTLS.

7. Integrate Cilium with Certificate-based Authentication

  1. Create a Cilium network policy that uses certificate information:

    apiVersion: "cilium.io/v2"
    kind: CiliumNetworkPolicy
    metadata:
      name: "allow-service1-to-service2"
    spec:
      endpointSelector:
        matchLabels:
          app: service2
      ingress:
      - fromEndpoints:
        - matchLabels:
            app: service1
      - toPorts:
        - ports:
          - port: "8080"
            protocol: TCP
        rules:
          http:
          - method: "GET"
            path: "/api/v1/"
  2. Apply the policy:

    cilium policy import allow-service1-to-service2.yaml

8. Test and Validate the Setup

  1. Verify DNS resolution:

    dig service1.internal.cluster.local
  2. Test mTLS communication between services:

    curl --cert service1.crt --key service1.key https://service2.internal.cluster.local:8080/api/v1/
  3. Verify Cilium network policies:

    cilium policy get

This guide provides a comprehensive approach to setting up a secure service mesh using CoreDNS and either OpenXPKI or EJBCA for certificate management. It covers service discovery, mutual TLS authentication, and network policy enforcement without the need for Kubernetes.

Remember to adapt the configurations and commands to your specific environment and requirements. Always follow best practices for security and keep your systems updated.

@mranv
Copy link

mranv commented Sep 21, 2024

Secure Service Mesh Setup Guide for 3 Linux VMs

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Server VM Setup
  4. Client VMs Setup
  5. Configure mTLS between VMs
  6. Test and Validate the Setup

1. Introduction

This guide will walk you through setting up a secure service mesh using Cilium, CoreDNS, and OpenXPKI on three Linux VMs: one server VM and two client VMs. This setup will provide service discovery, mutual TLS (mTLS) authentication, and network policy enforcement.

2. Prerequisites

  • 3 Linux VMs (1 server, 2 clients) - Ubuntu 20.04 or later recommended
  • Root access to all VMs
  • Basic understanding of networking, DNS, and PKI concepts

3. Server VM Setup

3.1 Install and Configure Cilium

  1. Install Cilium:

    curl -L --remote-name-all https://github.com/cilium/cilium-cli/releases/latest/download/cilium-linux-amd64.tar.gz
    sudo tar xzvfC cilium-linux-amd64.tar.gz /usr/local/bin
    rm cilium-linux-amd64.tar.gz
  2. Configure Cilium:

    Create /etc/cilium/cilium.yaml:

    devices:
    - eth0
    tunnel: vxlan
    ipam:
      type: cluster-pool
      pool:
        cidr: 10.0.0.0/16
  3. Start Cilium:

    sudo cilium-agent --config /etc/cilium/cilium.yaml

3.2 Install and Configure CoreDNS

  1. Install CoreDNS:

    wget https://github.com/coredns/coredns/releases/download/v1.8.6/coredns_1.8.6_linux_amd64.tgz
    tar xzf coredns_1.8.6_linux_amd64.tgz
    sudo mv coredns /usr/local/bin/
  2. Create /etc/coredns/Corefile:

    .:53 {
        hosts {
            10.0.0.1 server.internal.cluster.local
            10.0.0.2 client1.internal.cluster.local
            10.0.0.3 client2.internal.cluster.local
            fallthrough
        }
        forward . 8.8.8.8
        log
        errors
    }
    
    internal.cluster.local:53 {
        hosts {
            10.0.0.1 server.internal.cluster.local
            10.0.0.2 client1.internal.cluster.local
            10.0.0.3 client2.internal.cluster.local
        }
        log
        errors
    }
    
  3. Start CoreDNS:

    sudo coredns -conf /etc/coredns/Corefile

3.3 Install and Configure OpenXPKI

  1. Install OpenXPKI:

    sudo apt-get update
    sudo apt-get install -y openxpki
  2. Configure OpenXPKI:

    sudo openxpkiadm init
    sudo openxpkiadm certificate import --file /etc/ssl/certs/ca-certificates.crt
  3. Create a Root CA and Issuing CA:

    sudo openxpkiadm ca import --file root-ca.pem --realm ca-one
    sudo openxpkiadm ca import --file issuing-ca.pem --realm ca-one --issuer root-ca

4. Client VMs Setup

Perform these steps on both client VMs:

4.1 Install and Configure Cilium

Follow steps 3.1.1 to 3.1.3 from the Server VM Setup.

4.2 Configure DNS

Update /etc/resolv.conf:

nameserver 10.0.0.1  # IP of the server VM
search internal.cluster.local

5. Configure mTLS between VMs

Perform these steps on all VMs:

  1. Generate a certificate signing request (CSR):

    openssl req -new -newkey rsa:2048 -nodes -keyout vm.key -out vm.csr -subj "/CN=$(hostname).internal.cluster.local"
  2. On the server VM, sign the CSR using OpenXPKI:

    sudo openxpkiadm certificate issue --csr vm.csr --out vm.crt
  3. Distribute the signed certificates to each VM.

  4. Configure services to use the certificates for mTLS.

6. Test and Validate the Setup

  1. Verify DNS resolution on client VMs:

    dig server.internal.cluster.local
  2. Test mTLS communication between VMs:

    curl --cert vm.crt --key vm.key https://server.internal.cluster.local:8443
  3. Verify Cilium network connectivity:

    sudo cilium connectivity test

This guide provides a comprehensive approach to setting up a secure service mesh using three Linux VMs. It covers service discovery with CoreDNS, mutual TLS authentication with OpenXPKI, and network policy enforcement with Cilium.

Remember to adapt the configurations and commands to your specific environment and requirements. Always follow best practices for security and keep your systems updated.

@mranv
Copy link

mranv commented Sep 21, 2024

CoreDNS Setup with Custom CA and SSL

Table of Contents

  1. Introduction
  2. Prerequisites
  3. System Architecture
  4. Step 1: Set Up the Root CA
  5. Step 2: Set Up the Intermediate CA
  6. Step 3: Install and Configure CoreDNS
  7. Step 4: Generate SSL Certificate for hostname.local
  8. Step 5: Configure Client VMs
  9. Step 6: Configure SELinux (if applicable)
  10. Troubleshooting
  11. Advanced Usage

Introduction

This guide will walk you through setting up CoreDNS with a custom Certificate Authority (CA) and SSL certificates for secure local connections. The setup mimics commercial CA operations, providing valid SSL certificates for your local network.

Prerequisites

  • 1 Debian VM for CoreDNS server and CA
  • 2 Client VMs (any Linux distribution)
  • Root or sudo access on all VMs
  • Basic understanding of DNS, SSL, and networking concepts

System Architecture

  • CoreDNS Server: Acts as DNS server and Certificate Authority
  • Client VMs: Use CoreDNS for local resolution and trust the custom CA

Step 1: Set Up the Root CA

  1. Create the root CA directory:

    mkdir -p /root/ca/{root-ca,intermediate-ca,certs,crl,newcerts,private}
    cd /root/ca
    chmod 700 private
    touch index.txt
    echo 1000 > serial
    
  2. Create the root CA configuration file:

    nano /root/ca/root-ca.cnf
    

    Add the following content:

    [ ca ]
    default_ca = CA_default
    
    [ CA_default ]
    dir               = /root/ca
    certs             = $dir/certs
    crl_dir           = $dir/crl
    new_certs_dir     = $dir/newcerts
    database          = $dir/index.txt
    serial            = $dir/serial
    RANDFILE          = $dir/private/.rand
    
    private_key       = $dir/private/ca.key.pem
    certificate       = $dir/certs/ca.cert.pem
    
    crlnumber         = $dir/crlnumber
    crl               = $dir/crl/ca.crl.pem
    crl_extensions    = crl_ext
    default_crl_days  = 30
    
    default_md        = sha256
    name_opt          = ca_default
    cert_opt          = ca_default
    default_days      = 3650
    preserve          = no
    policy            = policy_strict
    
    [ policy_strict ]
    countryName             = match
    stateOrProvinceName     = match
    organizationName        = match
    organizationalUnitName  = optional
    commonName              = supplied
    emailAddress            = optional
    
    [ req ]
    default_bits        = 4096
    distinguished_name  = req_distinguished_name
    string_mask         = utf8only
    default_md          = sha256
    x509_extensions     = v3_ca
    
    [ req_distinguished_name ]
    countryName                     = Country Name (2 letter code)
    stateOrProvinceName             = State or Province Name
    localityName                    = Locality Name
    0.organizationName              = Organization Name
    organizationalUnitName          = Organizational Unit Name
    commonName                      = Common Name
    emailAddress                    = Email Address
    
    [ v3_ca ]
    subjectKeyIdentifier = hash
    authorityKeyIdentifier = keyid:always,issuer
    basicConstraints = critical, CA:true
    keyUsage = critical, digitalSignature, cRLSign, keyCertSign
    
    [ v3_intermediate_ca ]
    subjectKeyIdentifier = hash
    authorityKeyIdentifier = keyid:always,issuer
    basicConstraints = critical, CA:true, pathlen:0
    keyUsage = critical, digitalSignature, cRLSign, keyCertSign
    
  3. Generate the root CA key:

    openssl genrsa -aes256 -out /root/ca/private/ca.key.pem 4096
    chmod 400 /root/ca/private/ca.key.pem
    
  4. Generate the root CA certificate:

    openssl req -config /root/ca/root-ca.cnf -key /root/ca/private/ca.key.pem -new -x509 -days 7300 -sha256 -extensions v3_ca -out /root/ca/certs/ca.cert.pem
    
  5. Verify the root CA certificate:

    openssl x509 -noout -text -in /root/ca/certs/ca.cert.pem
    

Step 2: Set Up the Intermediate CA

  1. Create the intermediate CA directory:

    mkdir -p /root/ca/intermediate-ca/{certs,crl,newcerts,private,csr}
    cd /root/ca/intermediate-ca
    chmod 700 private
    touch index.txt
    echo 1000 > serial
    echo 1000 > /root/ca/intermediate-ca/crlnumber
    
  2. Create the intermediate CA configuration file:

    nano /root/ca/intermediate-ca.cnf
    

    Add content similar to the root CA configuration, adjusting paths and CA settings as needed.

  3. Generate the intermediate CA key:

    openssl genrsa -aes256 -out /root/ca/intermediate-ca/private/intermediate.key.pem 4096
    chmod 400 /root/ca/intermediate-ca/private/intermediate.key.pem
    
  4. Generate the intermediate CA CSR:

    openssl req -config /root/ca/intermediate-ca.cnf -new -sha256 -key /root/ca/intermediate-ca/private/intermediate.key.pem -out /root/ca/intermediate-ca/csr/intermediate.csr.pem
    
  5. Sign the intermediate CA certificate with the root CA:

    openssl ca -config /root/ca/root-ca.cnf -extensions v3_intermediate_ca -days 3650 -notext -md sha256 -in /root/ca/intermediate-ca/csr/intermediate.csr.pem -out /root/ca/intermediate-ca/certs/intermediate.cert.pem
    
  6. Verify the intermediate CA certificate:

    openssl x509 -noout -text -in /root/ca/intermediate-ca/certs/intermediate.cert.pem
    openssl verify -CAfile /root/ca/certs/ca.cert.pem /root/ca/intermediate-ca/certs/intermediate.cert.pem
    

Step 3: Install and Configure CoreDNS

  1. Download and install CoreDNS:

    wget https://github.com/coredns/coredns/releases/download/v1.10.1/coredns_1.10.1_linux_amd64.tgz
    tar xzf coredns_1.10.1_linux_amd64.tgz
    sudo mv coredns /usr/local/bin/
    
  2. Create CoreDNS configuration:

    sudo mkdir /etc/coredns
    sudo nano /etc/coredns/Corefile
    

    Add the following content:

    .:53 {
        hosts {
            192.168.1.10 server.local
            192.168.1.20 client1.local
            192.168.1.30 client2.local
            fallthrough
        }
        forward . 1.1.1.1
        log
        errors
    }
    
  3. Create a systemd service for CoreDNS:

    sudo nano /etc/systemd/system/coredns.service
    

    Add the following content:

    [Unit]
    Description=CoreDNS DNS server
    After=network.target
    
    [Service]
    ExecStart=/usr/local/bin/coredns -conf /etc/coredns/Corefile
    Restart=on-failure
    
    [Install]
    WantedBy=multi-user.target
    
  4. Start and enable CoreDNS:

    sudo systemctl daemon-reload
    sudo systemctl start coredns
    sudo systemctl enable coredns
    

Step 4: Generate SSL Certificate for hostname.local

  1. Create a certificate signing request (CSR) for hostname.local:

    openssl req -new -key /path/to/hostname.local.key -out /root/ca/intermediate-ca/csr/hostname.local.csr
    
  2. Sign the certificate with the intermediate CA:

    openssl ca -config /root/ca/intermediate-ca.cnf -extensions server_cert -days 365 -notext -md sha256 -in /root/ca/intermediate-ca/csr/hostname.local.csr -out /root/ca/intermediate-ca/certs/hostname.local.cert.pem
    
  3. Verify the certificate:

    openssl x509 -noout -text -in /root/ca/intermediate-ca/certs/hostname.local.cert.pem
    openssl verify -CAfile /root/ca/certs/ca.cert.pem -untrusted /root/ca/intermediate-ca/certs/intermediate.cert.pem /root/ca/intermediate-ca/certs/hostname.local.cert.pem
    

Step 5: Configure Client VMs

  1. Copy the root CA certificate to client VMs:

    scp /root/ca/certs/ca.cert.pem user@client-vm:/tmp/
    
  2. On each client VM, install the root CA certificate:

    sudo cp /tmp/ca.cert.pem /usr/local/share/ca-certificates/custom-root-ca.crt
    sudo update-ca-certificates
    
  3. Configure DNS on client VMs:

    sudo nano /etc/resolv.conf
    

    Add:

    nameserver 192.168.1.10  # CoreDNS server IP
    

Step 6: Configure SELinux (if applicable)

If you're using SELinux, follow these steps:

  1. Generate a custom SELinux policy for CoreDNS:

    sudo ausearch -c 'coredns' --raw | audit2allow -M my-coredns
    
  2. Apply the custom policy:

    sudo semodule -i my-coredns.pp
    
  3. Set correct file contexts:

    sudo semanage fcontext -a -t bin_t "/usr/local/bin/coredns"
    sudo restorecon -v /usr/local/bin/coredns
    sudo semanage fcontext -a -t etc_t "/etc/coredns(/.*)?"
    sudo restorecon -R -v /etc/coredns
    

Troubleshooting

  • Check CoreDNS logs: sudo journalctl -u coredns
  • Verify DNS resolution: dig @192.168.1.10 hostname.local
  • Test SSL: openssl s_client -connect hostname.local:443 -CAfile /path/to/ca.cert.pem

Advanced Usage

  • Add more local domain entries to CoreDNS configuration
  • Implement DNSSEC
  • Set up DNS-over-TLS or DNS-over-HTTPS

This README provides a comprehensive guide to setting up CoreDNS with a custom CA and SSL certificates, mimicking commercial CA operations for your local network.

@mranv
Copy link

mranv commented Sep 21, 2024

CoreDNS and OpenXPKI Setup Guide

Table of Contents

  1. Introduction
  2. Prerequisites
  3. System Architecture
  4. Step 1: Install OpenXPKI
  5. Step 2: Configure OpenXPKI
  6. Step 3: Set Up Root CA and Issuing CA
  7. Step 4: Install and Configure CoreDNS
  8. Step 5: Generate SSL Certificate for hostname.local
  9. Step 6: Configure Client VMs
  10. Step 7: Configure SELinux (if applicable)
  11. Troubleshooting
  12. Advanced Usage

Introduction

This guide will walk you through setting up CoreDNS with OpenXPKI for certificate management, providing a robust local DNS infrastructure with valid SSL certificates.

Prerequisites

  • 1 Debian VM for CoreDNS server and OpenXPKI
  • 2 Client VMs (any Linux distribution)
  • Root or sudo access on all VMs
  • Basic understanding of DNS, SSL, and networking concepts

System Architecture

  • Server VM: Hosts CoreDNS and OpenXPKI
  • Client VMs: Use CoreDNS for local resolution and trust the OpenXPKI CA

Step 1: Install OpenXPKI

  1. Update your system and install dependencies:

    sudo apt update
    sudo apt upgrade -y
    sudo apt install -y libopenca-perl libopenxpki-perl openxpki-i18n
  2. Install OpenXPKI:

    sudo apt install -y openxpki

Step 2: Configure OpenXPKI

  1. Initialize the OpenXPKI configuration:

    sudo openxpkiadm init
  2. Create a new realm (replace "Local-CA" with your desired realm name):

    sudo openxpkiadm realm create --realm Local-CA
  3. Edit the OpenXPKI configuration file:

    sudo nano /etc/openxpki/config.d/realm/Local-CA/system/crypto.yaml

    Adjust the key sizes and algorithms as needed:

    type: OpenXPKI::Crypto::Backend::OpenSSL
    
    key:
        default:
            algorithm: rsa
            key_length: 4096
            enc_alg: aes256
    
    hash: sha256
  4. Configure the certificate profiles in /etc/openxpki/config.d/realm/Local-CA/profile/:
    Create or edit files for your certificate profiles (e.g., I18N_OPENXPKI_PROFILE_TLS_SERVER.yaml for server certificates).

Step 3: Set Up Root CA and Issuing CA

  1. Generate the Root CA:

    sudo openxpkiadm certificate init --realm Local-CA --token root
  2. Generate the Issuing CA:

    sudo openxpkiadm certificate init --realm Local-CA --token ca-signer
  3. Start the OpenXPKI service:

    sudo systemctl start openxpki.service
    sudo systemctl enable openxpki.service

Step 4: Install and Configure CoreDNS

  1. Download and install CoreDNS:

    wget https://github.com/coredns/coredns/releases/download/v1.10.1/coredns_1.10.1_linux_amd64.tgz
    tar xzf coredns_1.10.1_linux_amd64.tgz
    sudo mv coredns /usr/local/bin/
  2. Create CoreDNS configuration:

    sudo mkdir /etc/coredns
    sudo nano /etc/coredns/Corefile

    Add the following content:

    .:53 {
        hosts {
            192.168.1.10 server.local
            192.168.1.20 client1.local
            192.168.1.30 client2.local
            fallthrough
        }
        forward . 1.1.1.1
        log
        errors
    }
    
  3. Create a systemd service for CoreDNS:

    sudo nano /etc/systemd/system/coredns.service

    Add the following content:

    [Unit]
    Description=CoreDNS DNS server
    After=network.target
    
    [Service]
    ExecStart=/usr/local/bin/coredns -conf /etc/coredns/Corefile
    Restart=on-failure
    
    [Install]
    WantedBy=multi-user.target
  4. Start and enable CoreDNS:

    sudo systemctl daemon-reload
    sudo systemctl start coredns
    sudo systemctl enable coredns

Step 5: Generate SSL Certificate for hostname.local

  1. Create a certificate signing request (CSR) for hostname.local:

    openssl req -new -newkey rsa:2048 -nodes -keyout hostname.local.key -out hostname.local.csr
  2. Submit the CSR to OpenXPKI:

    openxpki-cli request create --subject "CN=hostname.local" --format pkcs10 --csr hostname.local.csr
  3. Approve and issue the certificate:

    openxpki-cli workflow start --workflow certificate_signing_request_v2 --param cert_profile=tls-server --param cert_subject_style=00_basic_style

    Follow the prompts to approve and issue the certificate.

  4. Retrieve the issued certificate:

    openxpki-cli certificate get --format PEM > hostname.local.crt

Step 6: Configure Client VMs

  1. Export the Root CA certificate:

    openxpki-cli certificate get --format PEM --realm Local-CA --issuer root > root-ca.crt
  2. Copy the Root CA certificate to client VMs:

    scp root-ca.crt user@client-vm:/tmp/
  3. On each client VM, install the Root CA certificate:

    sudo cp /tmp/root-ca.crt /usr/local/share/ca-certificates/openxpki-root-ca.crt
    sudo update-ca-certificates
  4. Configure DNS on client VMs:

    sudo nano /etc/resolv.conf

    Add:

    nameserver 192.168.1.10  # CoreDNS server IP
    

Step 7: Configure SELinux (if applicable)

If you're using SELinux, follow these steps:

  1. Generate a custom SELinux policy for CoreDNS:

    sudo ausearch -c 'coredns' --raw | audit2allow -M my-coredns
  2. Apply the custom policy:

    sudo semodule -i my-coredns.pp
  3. Set correct file contexts:

    sudo semanage fcontext -a -t bin_t "/usr/local/bin/coredns"
    sudo restorecon -v /usr/local/bin/coredns
    sudo semanage fcontext -a -t etc_t "/etc/coredns(/.*)?"
    sudo restorecon -R -v /etc/coredns

Troubleshooting

  • Check OpenXPKI logs: sudo journalctl -u openxpki
  • Check CoreDNS logs: sudo journalctl -u coredns
  • Verify DNS resolution: dig @192.168.1.10 hostname.local
  • Test SSL: openssl s_client -connect hostname.local:443 -CAfile /path/to/root-ca.crt

Advanced Usage

  • Set up a web interface for OpenXPKI for easier certificate management
  • Implement automatic certificate renewal using OpenXPKI's REST API
  • Configure CoreDNS to use DNS-over-TLS (DoT) or DNS-over-HTTPS (DoH) for enhanced security

This guide provides a comprehensive setup for CoreDNS with OpenXPKI, allowing you to manage your own Certificate Authority and issue valid SSL certificates for your local network.

@mranv
Copy link

mranv commented Sep 21, 2024

coredns-openxpki-diagram

@mranv
Copy link

mranv commented Sep 21, 2024

image

@anubhavg-icpl
Copy link
Author

image

@mranv
Copy link

mranv commented Sep 21, 2024

SSL Setup with CoreDNS and OpenXPKI

Table of Contents

  1. Introduction
  2. System Overview
  3. Setup Process
  4. Component Interactions
  5. Project Timeline
  6. Implementation Guide
  7. Best Practices
  8. Troubleshooting
  9. Additional Resources

Introduction

This README provides a comprehensive guide for setting up a secure SSL infrastructure using CoreDNS for DNS management and OpenXPKI for certificate authority operations. This setup is designed for organizations requiring a robust, scalable, and secure internal PKI solution.

System Overview

The following diagram presents a high-level overview of the SSL setup:

High-Level SSL Setup Overview

Key components:

  • CoreDNS: Manages DNS resolution for the network
  • OpenXPKI: Acts as the Certificate Authority (CA) for issuing and managing SSL certificates
  • Client VMs: Endpoints that will use the SSL certificates and CoreDNS for secure communication

Setup Process

The setup process involves several key steps, as illustrated in this flowchart:

Detailed SSL Setup Flowchart

This flowchart outlines the entire process from initial setup to final testing. Color coding helps distinguish different types of steps:

  • Green: Start/End points
  • Blue: Processes
  • Yellow: Decision points

Component Interactions

To understand how different parts of the system interact, refer to this diagram:

SSL Component Interaction Diagram

This diagram shows:

  • How client VMs interact with CoreDNS for DNS queries
  • The role of OpenXPKI in issuing SSL certificates
  • The connection to external DNS (1.1.1.1) for resolving internet domains

Implementation Guide

  1. Set up Server Infrastructure

    • Prepare server(s) for CoreDNS and OpenXPKI
    • Ensure network connectivity
  2. Install and Configure OpenXPKI

    • Set up Root CA
    • Configure Issuing CA
  3. Install and Configure CoreDNS

    • Set up DNS zones
    • Configure forwarding rules
  4. Generate and Deploy SSL Certificates

    • Use OpenXPKI to generate certificates
    • Deploy certificates to required services
  5. Configure Client VMs

    • Install Root CA certificate
    • Update DNS settings to use CoreDNS
  6. Implement Security Measures

    • Configure firewalls
    • Set up SELinux/AppArmor if applicable
  7. Testing and Verification

    • Test DNS resolution
    • Verify SSL certificate validity
    • Check secure connections between services

Best Practices

  1. Regular Updates: Keep all components up-to-date with the latest security patches.
  2. Backup: Regularly backup CA keys and certificates.
  3. Monitoring: Implement monitoring for both CoreDNS and OpenXPKI.
  4. Access Control: Use strong authentication for administrative access.
  5. Documentation: Maintain clear, up-to-date documentation of the setup and processes.

Troubleshooting

Common issues and solutions:

  1. Certificate Issuance Failures

    • Check OpenXPKI logs
    • Verify CA certificate validity
  2. DNS Resolution Problems

    • Ensure CoreDNS is running
    • Check CoreDNS configuration
  3. Client Connection Issues

    • Verify Root CA certificate installation on clients
    • Check client DNS settings

Additional Resources

@mranv
Copy link

mranv commented Sep 21, 2024

Project Timeline

For project planning, use this Gantt chart as a reference:

Untitled-2024-09-21-1324

This timeline provides:

  • A breakdown of major tasks
  • Estimated durations for each phase
  • Dependencies between different stages of the setup

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment