How to make a self-signed certificate persist in nixos

nixos

I have a nix expression that builds a virtualbox vm. As part of that process, I install a self-signed ssl certificate via

certfile = builtins.readFile ./certificate.crt
security.pki.certificates = [ certfile ];

That works fine. The problem is if I want to run a nixos-rebuild to reconfigure the vm. Since I no longer have access to the original certfile from the vm build process (because I'm running in the vm, not on the machine where I built the vm), I can't just include the file again through the same mechanism.

I've come up with three ideas on how to do this:

  1. During the vm build process, place an extra copy of the cert under /root in the vm. Then I can just use this in my configuration.nix to pull in the certificate again:

    security.pki.certificates = [ /root/cert ];
    
  2. Since the certificate is always available for http download from an internal server, I could somehow use fetchUrl in the configuration.nix to download it every time I do a nixos-rebuild. I suppose the only downside to this would be introducing an external dependency.

  3. Since the certificate is in /etc/ssl/ca-certificates.crt, I could somehow extract it from that file as part ofthe rebuild process and then feed it to security.pki.certificates again.

Ideas?

Best Answer

You didn't specify what certfile looks like in the first line. If it's a variable thats populated with a builtins.readFile, you can skip that step and just populate the variable yourself.

$> nixos-option security.pki.certificates
Value:
[ "-----BEGIN CERTIFICATE-----
... edited for brevity .... " ]

Default:
[ ]

Example:
[ "NixOS.org\n=========\n-----BEGIN CERTIFICATE-----\nMIIGUDCCBTigAwIBAgIDD8KWMA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJJ\nTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0\n...\n-----END CERTIFICATE-----\n" ]

Description:

A list of trusted root certificates in PEM format.

Declared by:
  "/etc/nixos/nixpkgs/nixos/modules/security/ca.nix"

Defined by:
  "/etc/nixos/user.nix

So, setting security.pki.certificates [ "insert certificate here" ]; would eliminate the file dependency and then the configuration is self contained.

Otherwise, if you wanted to keep the content out of the configuration, you'd need to create packaging/a derivation for it and add it to the store.

Related Question