summaryrefslogtreecommitdiffstats
path: root/src/main.lib/Plugins/ValidationPlugins/Dns/DnsValidation.cs
blob: 0c39ec7b48beecdf04854548c00a072f70de26d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
using ACMESharp.Authorizations;
using PKISharp.WACS.Clients.DNS;
using PKISharp.WACS.Context;
using PKISharp.WACS.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static PKISharp.WACS.Clients.DNS.LookupClientProvider;

namespace PKISharp.WACS.Plugins.ValidationPlugins
{
    /// <summary>
    /// Base implementation for DNS-01 validation plugins
    /// </summary>reee
    public abstract class DnsValidation<TPlugin> : Validation<Dns01ChallengeValidationDetails>
    {
        protected readonly LookupClientProvider _dnsClient;
        protected readonly ILogService _log;
        protected readonly ISettingsService _settings;
        private readonly List<DnsValidationRecord> _recordsCreated = new List<DnsValidationRecord>();

        protected DnsValidation(
            LookupClientProvider dnsClient,
            ILogService log,
            ISettingsService settings)
        {
            _dnsClient = dnsClient;
            _log = log;
            _settings = settings;
        }

        /// <summary>
        /// Prepare to add a new DNS record
        /// </summary>
        /// <param name="context"></param>
        /// <param name="challenge"></param>
        /// <returns></returns>
        public override async Task PrepareChallenge(ValidationContext context, Dns01ChallengeValidationDetails challenge)
        {
            // Check for substitute domains
            var authority = await _dnsClient.GetAuthority(
                challenge.DnsRecordName,
                followCnames: _settings.Validation.AllowDnsSubstitution);

            var success = false;
            while (!success)
            {
                var record = new DnsValidationRecord(context, authority, challenge.DnsRecordValue);
                success = await CreateRecord(record);
                if (!success)
                {
                    if (authority.From == null)
                    {
                        throw new Exception("Unable to prepare for challenge answer");
                    }
                    else
                    {
                        authority = authority.From;
                    }
                } 
                else
                {
                    _recordsCreated.Add(record);
                }
            }
        }

        /// <summary>
        /// Default commit function, doesn't do anything because 
        /// default doesn't do parallel operation
        /// </summary>
        /// <returns></returns>
        public override sealed async Task Commit()
        {
            // Wait for changes to be saved
            await SaveChanges();

            // Verify that the record was created succesfully and wait for possible
            // propagation/caching/TTL issues to resolve themselves naturally
            if (_settings.Validation.PreValidateDns)
            {
                var validationTasks = _recordsCreated.Select(r => ValidateRecord(r));
                await Task.WhenAll(validationTasks);
            }
        }

        /// <summary>
        /// Typically the changes will already be saved by 
        /// PrepareChallenge, but for those plugins that support
        /// parallel operation, this may be overridden to handle
        /// persistance
        /// </summary>
        /// <returns></returns>
        public virtual Task SaveChanges() => Task.CompletedTask;

        /// <summary>
        /// Check the TXT value from all known authoritative DNS servers
        /// </summary>
        /// <param name="record"></param>
        /// <returns></returns>
        protected async Task<bool> PreValidate(DnsValidationRecord record)
        {
            try
            {
                _log.Debug("[{identifier}] Looking for TXT value {DnsRecordValue}...", record.Context.Identifier, record.Authority.Domain);
                foreach (var client in record.Authority.Nameservers)
                {
                    _log.Debug("[{identifier}] Preliminary validation asking {ip}...", record.Context.Identifier, client.IpAddress);
                    var answers = await client.GetTxtRecords(record.Authority.Domain);
                    if (!answers.Any())
                    {
                        _log.Warning("[{identifier}] Preliminary validation failed: no TXT records found", record.Context.Identifier);
                        return false;
                    }
                    if (!answers.Contains(record.Value))
                    {
                        _log.Debug("[{identifier}] Preliminary validation found values: {answers}", record.Context.Identifier, answers);
                        _log.Warning("[{identifier}] Preliminary validation failed: incorrect TXT record(s) found", record.Context.Identifier);
                        return false;
                    }
                    _log.Debug("[{identifier}] Preliminary validation from {ip} looks good", record.Context.Identifier, client.IpAddress);
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex, "[{identifier}] Preliminary validation failed", record.Context.Identifier);
                return false;
            }
            _log.Information("[{identifier}] Preliminary validation succeeded", record.Context.Identifier);
            return true;
        }

        /// <summary>
        /// Delete record when we're done
        /// </summary>
        public override sealed async Task CleanUp()
        {
            foreach (var record in _recordsCreated)
            {
                try
                {
                    await DeleteRecord(record);
                }
                catch (Exception ex)
                {
                    _log.Warning($"Error deleting record: {ex.Message}");
                }
            }
            await Finalize();
        }

        /// <summary>
        /// Typically the changes will already be undone by 
        /// Finalize, but for those plugins that support
        /// parallel operation, this may be overridden 
        /// </summary>
        /// <returns></returns>
        public virtual Task Finalize() => Task.CompletedTask;

        /// <summary>
        /// Validate a record as being correctly created an sychronised, runs during/after the commit state
        /// </summary>
        /// <param name="record"></param>
        /// <returns></returns>
        private async Task ValidateRecord(DnsValidationRecord record)
        {
            var retry = 0;
            var maxRetries = _settings.Validation.PreValidateDnsRetryCount;
            var retrySeconds = _settings.Validation.PreValidateDnsRetryInterval;
            while (true)
            {
                if (await PreValidate(record))
                {
                    break;
                }
                else
                {
                    retry += 1;
                    if (retry > maxRetries)
                    {
                        _log.Information("It looks like validation is going to fail, but we will try now anyway...");
                        break;
                    }
                    else
                    {
                        _log.Information("Will retry in {s} seconds (retry {i}/{j})...", retrySeconds, retry, maxRetries);
                        await Task.Delay(retrySeconds * 1000);
                    }
                }
            }
        }

        /// <summary>
        /// Delete validation record
        /// </summary>
        /// <param name="recordName">Name of the record</param>
        public abstract Task DeleteRecord(DnsValidationRecord record);

        /// <summary>
        /// Create validation record
        /// </summary>
        /// <param name="recordName">Name of the record</param>
        /// <param name="token">Contents of the record</param>
        public abstract Task<bool> CreateRecord(DnsValidationRecord record);

        /// <summary>
        /// Match DNS zone to use from a list of all zones
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="candidates"></param>
        /// <param name="recordName"></param>
        /// <returns></returns>
        public T? FindBestMatch<T>(Dictionary<string, T> candidates, string recordName) where T: class
        {
            var result = candidates.Keys.Select(key =>
            {
                var fit = 0;
                var name = key.TrimEnd('.');
                if (string.Equals(recordName, name, StringComparison.InvariantCultureIgnoreCase) || 
                    recordName.EndsWith("." + name, StringComparison.InvariantCultureIgnoreCase))
                {
                    // If there is a zone for a.b.c.com (4) and one for c.com (2)
                    // then the former is a better (more specific) match than the
                    // latter, so we should use that
                    fit = name.Split('.').Count();
                    _log.Verbose("Zone {name} scored {fit} points", key, fit);
                }
                else
                {
                    _log.Verbose("Zone {name} not matched", key);
                }
                return new { 
                    key, 
                    value = candidates[key],
                    fit
                };
            }).
            Where(x => x.fit > 0).
            OrderByDescending(x => x.fit).
            FirstOrDefault();

            if (result != null)
            {
                _log.Debug("Picked {name} as best match", result.key);
                return result.value;
            } 
            else
            {
                _log.Error("No match found");
                return null;
            }
        }

        /// <summary>
        /// Keep track of which records are created, so that they can be deleted later
        /// </summary>
        public class DnsValidationRecord
        {
            public ValidationContext Context { get; }
            public DnsLookupResult Authority { get; }
            public string Value { get; }

            public DnsValidationRecord(ValidationContext context, DnsLookupResult authority, string value)
            {
                Context = context;
                Authority = authority;
                Value = value;
            }
        }
    }
}