salt icon indicating copy to clipboard operation
salt copied to clipboard

Populate entire files via Pillar

Open quinnypig opened this issue 14 years ago • 49 comments

If I want to populate a file (say, /etc/ssl/cert.pem) that not every minion should be able to see, Pillar is ideal for this; however right now I don't have that option.

quinnypig avatar Jun 30 '12 23:06 quinnypig

Good call, remind me to place this on 0.10.3 when the time comes

thatch45 avatar Jun 30 '12 23:06 thatch45

This attempted workaround via jinja just results in a blank /tmp/date; should it work, or am I being too optimistic?

[cquinn@salt www]$ cd /srv/pillar/
[cquinn@salt pillar]$ cat top.sls 
base:
  '*':
    - base
  'www*':
    - www
[cquinn@salt pillar]$ cat www/init.sls 
date: {% include "blah" %}

[cquinn@salt pillar]$ cat /srv/salt/www/init.sls 
/tmp/date:
  file:
    - managed
    - source: salt://www/files/date
    - template: jinja

quinnypig avatar Jul 01 '12 00:07 quinnypig

I addressed a similar problem doing something along the lines of the following example:

top.sls: (the same for both /srv/pillar and /srv/salt directories)

base:
    '*':
        - ssh

/srv/pillar/ssh.sls:

ssh_certs:
{% if grains['fqdn'] == 'server1.example.com' %}
    dsa: |
        -----BEGIN DSA PRIVATE KEY-----
        {# key text goes here with consistant indentation... #}
        -----END DSA PRIVATE KEY-----
    ecdsa: |
        -----BEGIN ECDSA PRIVATE KEY-----
        {# key text goes here with consistant indentation... #}
        -----END ECDSA PRIVATE KEY-----
    rsa: |
        -----BEGIN RSA PRIVATE KEY-----
        {# key text goes here with consistant indentation... #}
        -----END RSA PRIVATE KEY-----
{% elif grains['fqdn'] == 'server2.example.com' %}
    # same as above but with different key texts of course....
{% endif %}

/srv/salt/ssh.sls:

{# using .get() and providing a default on the next line is important to avoid a KeyError for
   hosts that don't include the Pillar ssh.sls file: #}

{% for key_type in pillar.get('ssh_certs', {}) %}
/etc/ssh/ssh_host_{{ key_type }}_key:
    file.managed:
        - context:
            key_type: {{ key_type }}
        - mode: 600
        - source: salt://ssh/files/private_key
        - template: jinja
{% endfor %}

/srv/salt/ssh/files/private_key:

{{ pillar['ssh_certs'][key_type] }}

It's a little bit convoluted, but works just fine for me... Of course this approach wouldn't work very well for binary data or any kind of data that might cause PyYaml or Jinja2 problems....

rnd42 avatar Oct 15 '12 07:10 rnd42

I've been looking into this as well as I need to be able to manage systems for multiple unconnected companies and came up with the following:

tf198/salt@SHA: 8a30f60379aab99faaaa48fe58114a6c6a138759

Basically it adds a path_hide_regex and path_hide_glob option to the master config which prevents listing of files to minions. Then you can use a suitably long and securely generated secret distributed via a pillar to restrict access to individual or groups of minions.

/etc/salt/master - hide the private directory

path_hide_glob:
  - private/*

/srv/pillar/private.sls - distribute the secret through pillar mechanism

{% if grains['id'] == 'server1.example.com' %}
secret: gK9yOuETT9pKdnsvWAhbbHoYqJlchxDD
{% endif %}

/srv/salt/private/gK9yOuETT9pKdnsvWAhbbHoYqJlchxDD/cert.pem

-----BEGIN RSA PRIVATE KEY-----
...
 -----END RSA PRIVATE KEY-----

/srv/salt/ssl.sls - install the file

/etc/ssl/cert.pem:
  file.managed:
    - source: salt://private/{{ pillar.secret }}/cert.pem
    - mode: 600

minions cant see the files

$ salt 'server1.*' cp.list_master
{'server1.example.com': ['top.sls', 'ssl.sls']}
$ salt 'server1.*' cp.list_master_dirs
{'server1.example.com': ['.', 'private']}

The only issue I can see (until some security guru pops up and shoots this down in flames) is that you cannot use the file.recurse state for a hidden path, though I guess there could be other side effects.

From my reading of the ZMQ docs then any other access control would require a relatively major change to the transport layer involving tokens so I cant imagine it coming any time soon unless Thatch has something in the wings.

Comments welcomed...

tf198 avatar Jan 03 '13 05:01 tf198

there's issue #636 that was closed wrt pillar ;-)

pille avatar Jan 03 '13 13:01 pille

This is not a bad idea @tf198, although it does seem too hacky. I have been thinking about this a little, I am wondering if we could allow files to be stored in pillar and then realized via a pillar file request, then the files can be enabled within the pillar data itself for the specific minion, otherwise direct file downloads from the pillar_roots is restricted. It is also noteworthy, that this patch would not apply to master any more because of some serious changes I have made to the file server for 0.12.0 allowing multiple fileserver backends. take a look at the salt/fileserver/roots.py module as that is where the fileserver code is now.

thatch45 avatar Jan 03 '13 17:01 thatch45

Man this project moves fast - I was only away for a week :-)

The problem as I see it is that you'll end up duplicating a lot of code to allow file requests from the pillar - new handler for pillar:// etc... Am glad to hear that you are still looking into this though as it is a blocker for several usage scenarios at the moment.

Have reworked my patch for the new fileserver backends tf198/salt@4f9c713b572d0f3be78e5726afeda317e76cb5ef so that you can declare environments as private which seems like a more natural separation and gives cleaner code. Usage is pretty much the same as above except you need to specify the env in the state file.

/etc/master/salt

file_roots:
  base:
    - /srv/salt
  private:
    - /srv/private

private_envs:
  - private

/srv/pillar/private.sls - distribute the secret through pillar mechanism

{% if grains['id'] == 'server1.example.com' %}
secret: gK9yOuETT9pKdnsvWAhbbHoYqJlchxDD
{% endif %}

/srv/private/gK9yOuETT9pKdnsvWAhbbHoYqJlchxDD/cert.pem

-----BEGIN RSA PRIVATE KEY-----
...
 -----END RSA PRIVATE KEY-----

/srv/salt/ssl.sls

/etc/ssl/cert.pem:
  file.managed:
    - source: salt://{{ pillar.secret }}/cert.pem
    - env: private
    - mode: 600

minions cant see the files

$ salt 'server1.*' cp.list_master
{'server1.example.com': ['top.sls', 'ssl.sls']}
$ salt 'server1.*' cp.list_master private
{'server1.example.com': []}

tf198 avatar Jan 04 '13 00:01 tf198

Hmm, this is a good direction, but we would need to evaluate some of the security implications more. Lets do this, we will put this on hold until after 0.12.0 is released since we need to get it out the door. then we can more this guy to the forefront and more aggressively evaluate it. Sound alright?

thatch45 avatar Jan 04 '13 05:01 thatch45

Agreed - I'm still at the evaluation stage so am just kicking a few ideas about to see whether we can make SaltStack bend to our particular needs. Obviously full granular access control is preferable but this gives me enough to be going on with.

Assuming of course that there is no way the secret leaks through any of the logging/caching internals...

BTW. I can't find anywhere in the current test suite to add master/config behaviour tests - is this currently not covered?

tf198 avatar Jan 04 '13 06:01 tf198

Yes, you can set config values on the master, in here: https://github.com/saltstack/salt/blob/develop/tests/integration/files/conf/master this is for the primary master that we start for all of the integration tests

thatch45 avatar Jan 04 '13 06:01 thatch45

I've worked around this via mako (er, python). Basically:

#!mako|yaml

<%!
import re
import os
import yaml
%>
<%

path = '/home/salt/pillar'
data = yaml.safe_load(open(path + '/ssl.conf').read())
out  = []

if grains['id'] in data:

  sslkeys = {}

  for ssldir in data[grains['id']]:
    sslpath = path + '/ssl/' + ssldir + '/'

    keydata  = open(sslpath + 'key').read().split('\n')
    certdata = open(sslpath + 'certificate').read().split('\n')
    intermediatedata = None
    if os.path.exists(sslpath + 'intermediate'):
      intermediatedata = open(sslpath + 'intermediate').read().split('\n')

    sslkeys[ssldir] = { 'key' : keydata, 'cert' : certdata, 'int' : intermediatedata }

  # nu hebben we alles gelezen, maak yaml

  for sslname, ssl in sslkeys.iteritems():
    out.append(  '  ' + sslname + ': ')
    out.append(  '    key: |\n'+         '      ' + '\n      '.join(ssl['key']))
    out.append(  '    certificate: |\n'+ '      ' + '\n      '.join(ssl['cert']))
    if ssl['int'] != None:
      out.append('    intermediate: |\n'+'      ' + '\n      '.join(ssl['int']))

%>
ssl:
${'\n'.join(out)}

Then, have a state that references this:

{% if 'ssl' in pillar %}
{% for ssldir in pillar['ssl'] %}

/etc/apache2/ssl/{{ ssldir }}:
  file.directory:
    - mode: 700
    - user: root
    - require:
      - file: /etc/apache2/ssl

/etc/apache2/ssl/{{ ssldir }}/key:
  file.managed:
    - mode: 400
    - user: root
    - source: salt://apache/ssl-file
    - template: jinja
    - context:
      content: |-
        {{ pillar['ssl'][ssldir]['key'] | indent(8) }}
    - require:
      - file: /etc/apache2/ssl/{{ ssldir }}

/etc/apache2/ssl/{{ ssldir }}/certificate:
  file.managed:
    - mode: 444
    - user: root
    - source: salt://apache/ssl-file
    - template: jinja
    - context:
      content: |-
        {{ pillar['ssl'][ssldir]['certificate'] | indent(8) }}
    - require:
      - file: /etc/apache2/ssl/{{ ssldir }}

and ssl-file prints the data:

{{ content }}

Won't work for binary data, obviously, but if you encode it base64 at the start and decode it in ssl-file (use mako instead if jinja) you'd get there eventually.

Mrten avatar Apr 18 '13 20:04 Mrten

I've solved this by writing custom ext_pillar: https://gist.github.com/jollyroger/6037683. This module has some assumptions but is pretty straightforward:

import os.path
def ext_pillar( pillar, **kwargs ):
    ca_pillar = {}
    host_id = __opts__['id']
    for pillar_key, ca_dir in kwargs.iteritems():
        cacert_path = os.path.join(ca_dir, 'cacert.pem')
        cert_path = os.path.join(ca_dir, 'certs', "".join([host_id, '.crt']))
        key_path = os.path.join(ca_dir, 'private', "".join([host_id, '.key']))
        try:
            cacert = open(cacert_path,'r').read()
            key = open(key_path,'r').read()
            cert = open(cert_path, 'r').read()
            ca_pillar[pillar_key] = {
                "cacert": cacert,
                "key": key,
                "cert": cert 
                }
        except IOError:
            continue
    return ca_pillar

You need to configure ext_pillar in master's config as well as to point out the path to the ext_pillar (for example, the code above is written to /srv/salt/modules/pillar/ca.py ) with extension_modules setting, for example:

extension_modules: /srv/salt/modules
ext_pillar:
  - ca: 
      example_ca: /srv/ca.example.com/demoCA

In this example ext_pillar will populate pillar key example_ca with a dictionary containing keys cacert, key, and cert that hold CA root certificate and host's private key and certificate respectively based on the host's id. Assuming target host is server1.example.com, the following pillar values will be available for it:

  • example_ca:cacert will be read from /srv/ca.example.com/demoCA/cacert.pem
  • example_ca:key will be read from /srv/ca.example.com/demoCA/private/server1.example.com.key
  • example_ca:cert will be read from /srv/ca.example.com/demoCA/certs/server1.example.com.crt

The actual states using this pillar can look like this:

{{ "/etc/ssl/certs/%s.crt"|format(grains[id]) }}:
  file.managed:
    - mode: 0600
    - user: root
    - group: root
    - contents: |-
      {{ salt['pillar.get']('example_ca:cert')|indent(6) }}
{{ "/etc/ssl/private/%s.key"|format(grains[id]) }}:
  file.managed:
    - mode: 0600
    - user: root
    - group: root
    - contents: |-
      {{ salt['pillar.get']('example_ca:key')|indent(6) }}

Thanks to @Mrten for inspiration since most of the ideas are his, I just better like the ext_pillar idea.

jollyroger avatar Jul 19 '13 09:07 jollyroger

One extra thing to add to this discussion - any solution that uses pillars results in the file being transferred every time regardless. Hardening salt envs in some way retains all the benefits of file.managed so is preferable from a network overheads point of view...

tf198 avatar Jul 31 '13 11:07 tf198

+1 It would be very nice and helpful to deploy ssl certs/key via Salt.

jarus avatar Aug 18 '13 10:08 jarus

This was implemented about 7 weeks ago in 3077e63 and will be in 0.17.0. Closing.

terminalmage avatar Sep 25 '13 15:09 terminalmage

I don't think that the fix of 3077e63 fixes this. 3077e63 is for using pillar variables as the contents of a file. My understanding is that this ticket was about getting an entire file from the pillar.

aptiko avatar Nov 12 '13 15:11 aptiko

I don't quite understand the difference. Pillar data aren't files, they're strings, integers, etc. This issue asked for the ability to populate an entire file from pillar data, and the above commit does that.

terminalmage avatar Nov 12 '13 17:11 terminalmage

@terminalmage Yes, it isn't very clear how to interpret what the original poster wanted; however, he gives an example in his second post, where the pillar contains`

  date: {% include "blah" %}

Apparently he wants the pillar to store "blah" as a separate file, not as as a string inside the pillar. I think that this is not possible; the "include" trick above won't work if "blah" contains newlines, and I don't see any way in jinja to make it work; you'd need something like

  date: |
    {% include "blah" | replace("\n", "\n        ") %}

which doesn't work of course (is there anything like this? I'm far from a jinja guru).

The only workaround seems to be to have the required contents inside the pillar file:

  date: |
    This is an important date
    just because it is important:
    2013-11-13

However, I think that in complicated pillars it might be beneficial to be able to store the stuff in a separate file.

aptiko avatar Nov 13 '13 08:11 aptiko

@aptiko What I wanted was the ability to store SSL certificates in Pillar. This has been working for me for ages now, but I see where you're going with it.

quinnypig avatar Nov 15 '13 18:11 quinnypig

@aptiko I thought this ticket referenced this need too - I share your opinion. Storing SSL certificates on separate files inside pillar would be much easier to manage rather than inlining the content. Should this be ticketed as a new issue?

ruimarinho avatar Nov 15 '13 18:11 ruimarinho