aboutsummaryrefslogtreecommitdiff
path: root/src/Statics.cs
blob: 0978abf2f67037ee36dd83cca4f10df541f92513 (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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Package: PkiAuthenticator
* File: Statics.cs 
*
* PkiAuthenticator is free software: you can redistribute it and/or modify 
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 2 of the License,
* or (at your option) any later version.
*
* PkiAuthenticator is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License 
* along with PkiAuthenticator. If not, see http://www.gnu.org/licenses/.
*/

using System;
using System.Linq;
using System.Text;
using System.Buffers;
using System.Text.Json;
using System.Buffers.Text;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

using Serilog;
using Serilog.Core;
using Serilog.Events;

using Yubico.YubiKey.Piv;

using VNLib.Utils;
using VNLib.Utils.Logging;
using VNLib.Utils.Memory;
using VNLib.Utils.Extensions;
using VNLib.Hashing;
using VNLib.Hashing.IdentityUtility;

namespace PkiAuthenticator
{

    internal static class Statics
    {
        public static ArgumentList CliArgs { get; } = new ArgumentList(Environment.GetCommandLineArgs());

        public static ILogProvider Log { get; } = GetLog();

        private static ILogProvider GetLog()
        {
            LoggerConfiguration config = new();

            //Set min level from cli flags
            if(CliArgs.HasArgument("--verbose") || CliArgs.HasArgument("-v"))
            {
                config.MinimumLevel.Verbose();
            }
            else if (CliArgs.HasArgument("--verbose") || CliArgs.HasArgument("-v"))
            {
                config.MinimumLevel.Debug();
            }
            else
            {
                config.MinimumLevel.Information();
            }

            //Make sure the silent flag is not set
            if(!CliArgs.HasArgument("--silent") || CliArgs.HasArgument("-s"))
            {
                //Write to console for now
                config.WriteTo.Console();
            }

            //Init new log
            return new VLogProvider(config);
        }

        /// <summary>
        /// Generats a signed VNLib authentication toke, used to authenticate against 
        /// web applications using the YubiKey
        /// </summary>
        /// <returns>The process exit code returning the status of the operation.</returns>
        public static int GenerateOtp(this IAuthenticator authenticator)
        {
            string? uid = CliArgs.GetArgument("-u");
            uid ??= CliArgs.GetArgument("--user");

            HashAlg digest;

            //Init the jwt header
            Dictionary<string, string> jwtHeader = new()
            {
                ["typ"] = "jwt"
            };

            Log.Verbose("Recovering the device metadata...");

            switch (authenticator.KeyAlgorithm)
            {
                case PivAlgorithm.Rsa1024:
                case PivAlgorithm.Rsa2048:
                    //Use rsa256 for all rsa operations
                    digest = HashAlg.SHA256;
                    jwtHeader["alg"] = "RS256";
                    break;
                case PivAlgorithm.EccP256:
                    digest = HashAlg.SHA256;
                    jwtHeader["alg"] = "ES256";
                    break;
                case PivAlgorithm.EccP384:
                    digest = HashAlg.SHA384;
                    jwtHeader["alg"] = "ES384";
                    break;
                default:
                    Log.Error("The key's authentication slot contains an unsupported algorithm");
                    return -5;
            }

            //Build the login jwt
            using JsonWebToken jwt = new();

            jwt.WriteHeader(jwtHeader);

            Log.Verbose("Recovering the x509 certificate from the key");

            //Get the auth certificate
            using (X509Certificate2 cert = authenticator.GetCertificate())
            {
                //Default uid is the subjet name
                uid ??= cert.SubjectName.Name.AsSpan().SliceAfterParam("=").ToString();

                //Get random nonce for entropy
                string nonce = RandomHash.GetRandomBase32(16);

                jwt.InitPayloadClaim()
                  .AddClaim("sub", uid)
                  .AddClaim("n", nonce)
                  .AddClaim("iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds())
                  //Keyid is the hex sha1 of the certificate
                  .AddClaim("keyid", Convert.ToHexString(cert.GetCertHash(HashAlgorithmName.SHA1)))
                  .AddClaim("serial", cert.SerialNumber)
                  .CommitClaims();
            }

            Log.Verbose("Signing authentication token...");

            try
            {
                //Sign the token
                jwt.Sign(authenticator, digest);

                Log.Information(Program.TOKEN_PRINT_TEMPLATE, jwt.Compile());

                //If silent mode is enabled, write credential directly to stdout
                if (CliArgs.HasArgument("--silent") || CliArgs.HasArgument("-s"))
                {
                    Console.Write(jwt.Compile());
                }

                return 0;
            }
            catch (OperationCanceledException)
            {
                Log.Error("The operation has been cancelled");
                return -1;
            }
        }

        /// <summary>
        /// Base64url encodes the data buffer and returns a utf8 string from 
        /// the encoded results.
        /// </summary>
        /// <param name="data">The binary buffer to encode</param>
        /// <returns>The encoded string</returns>
        public static string ToBase64Url(ReadOnlySpan<byte> data)
        {
            int base64 = Base64.GetMaxEncodedToUtf8Length(data.Length);

            //Alloc buffer
            using UnsafeMemoryHandle<byte> buffer = MemoryUtil.UnsafeAllocNearestPage<byte>(base64);

            int written = ToBase64Url(data, buffer.Span);

            return Encoding.UTF8.GetString(buffer.Span[..written]);
        }

        /// <summary>
        /// Base64url encodes the data buffer and writes the output to the <paramref name="writer"/>
        /// argument.
        /// </summary>
        /// <param name="data">The binary data to base64url encode</param>
        /// <param name="writer">A referrence to the <see cref="ForwardOnlyWriter{T}"/></param>
        /// <exception cref="Exception"></exception>
        public static void ToUrlSafe(ReadOnlySpan<byte> data, ref ForwardOnlyWriter<byte> writer)
        {
            int base64Size = Base64.GetMaxEncodedToUtf8Length(data.Length);

            //Alloc buffer
            using UnsafeMemoryHandle<byte> buffer = MemoryUtil.UnsafeAllocNearestPage<byte>(base64Size);

            //Convert the data to base64url safe
            int written = ToBase64Url(data, buffer.Span);

            if(written == ERRNO.E_FAIL)
            {
                throw new Exception($"Failed to encode the binary data due to a base64 encoding failure");
            }

            //Write encoded data to writer
            writer.Append(buffer.Span[..written]);
        }

        /// <summary>
        /// Base64url encodes the data buffer and writes the output to the output buffer.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="buffer">The output buffer to write the base64url encoded utf8 bytes</param>
        /// <returns>The number of bytes written to the output buffer, or 0/false if the operation failed</returns>
        /// <exception cref="Exception"></exception>
        public static ERRNO ToBase64Url(ReadOnlySpan<byte> data, Span<byte> buffer)
        {
            //Encode the data to base64
            OperationStatus status = Base64.EncodeToUtf8(data, buffer, out _, out int written, true);
            
            if (status != OperationStatus.Done)
            {
                return ERRNO.E_FAIL;
            }

            //Url encode
            VnEncoding.Base64ToUrlSafeInPlace(buffer[..written]);

            //Remove trailing padding bytes
            while (buffer[written - 1] == (byte)'=')
            {
                written--;
            }

            return written;
        }

        /// <summary>
        /// Writes the public key information for the current session, using the 
        /// configured slot, to a JWK, setting the key-id (kid) as the as the 
        /// hex encoded hash of the certificate.
        /// </summary>
        /// <param name="authenticator"></param>
        /// <returns>The process exit code, 0 if successful, non-zero if a failure occured</returns>
        public static string? ExportJwk(this IAuthenticator authenticator)
        {
            static void WriteEcParams(X509Certificate2 cert, IDictionary<string, string> jwk)
            {
                using ECDsa alg = cert.GetECDsaPublicKey()!;

                //recover params
                ECParameters p = alg.ExportParameters(false);

                //Write public key elements
                jwk["x"] = ToBase64Url(p.Q.X);
                jwk["y"] = ToBase64Url(p.Q.Y);
            }

            static void WriteRsaParams(X509Certificate2 cert, IDictionary<string, string> jwk)
            {
                using RSA rSA = cert.GetRSAPublicKey()!;

                RSAParameters p = rSA.ExportParameters(false);

                jwk["e"] = ToBase64Url(p.Exponent);
                jwk["n"] = ToBase64Url(p.Modulus);
            }

            Dictionary<string, string> jwkObj = new()
            {
                { "use", "sig" }
            };

            //Get key certificate
            using X509Certificate2 cert = authenticator.GetCertificate();

            //Write cert hash to the kid
            jwkObj["kid"] = Convert.ToHexString(cert.GetCertHash(HashAlgorithmName.SHA1));

            //Write cert serial number
            jwkObj["serial"] = cert.SerialNumber;

            switch (authenticator.KeyAlgorithm)
            {
                case PivAlgorithm.EccP256:
                    jwkObj["kty"] = "EC";
                    jwkObj["crv"] = "P-256";
                    jwkObj["alg"] = "ES256";

                    //write the ec params to jwk
                    WriteEcParams(cert, jwkObj);
                    break;
                case PivAlgorithm.EccP384:
                    jwkObj["kty"] = "EC";
                    jwkObj["crv"] = "P-384";
                    jwkObj["alg"] = "ES384";

                    //write the ec params to jwk
                    WriteEcParams(cert, jwkObj);
                    break;

                case PivAlgorithm.Rsa1024:
                case PivAlgorithm.Rsa2048:
                    jwkObj["kty"] = "RSA";
                    jwkObj["alg"] = "RS256";

                    //Rsa print
                    WriteRsaParams(cert, jwkObj);
                    break;

                default:
                    return null;
            }

            //Write jwk to std out
            return JsonSerializer.Serialize(jwkObj);
        }

        /// <summary>
        /// Writes the public key information for the current session, using the 
        /// configured slot, using PEM encoding.
        /// </summary>
        /// <param name="authenticator"></param>
        /// <returns>The process exit code, 0 if successful, non-zero if a failure occured</returns>
        public static string ExportPem(this IAuthenticator authenticator)
        {
            //Get key certificate
            using X509Certificate2 cert = authenticator.GetCertificate();

            byte[] pubkey = cert.PublicKey.ExportSubjectPublicKeyInfo();

            //Sb for printing cert data
            StringBuilder builder = new ();
            builder.AppendLine("-----BEGIN PUBLIC KEY-----");
            builder.AppendLine(Convert.ToBase64String(pubkey, Base64FormattingOptions.InsertLineBreaks));
            builder.AppendLine("-----END PUBLIC KEY-----");

            return builder.ToString();
        }

        private sealed class VLogProvider : VnDisposeable, ILogProvider
        {
            private readonly Logger LogCore;

            public VLogProvider(LoggerConfiguration config)
            {
                LogCore = config.CreateLogger();
            }
            public void Flush() { }

            public object GetLogProvider() => LogCore;

            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public bool IsEnabled(LogLevel level) => LogCore.IsEnabled((LogEventLevel)level);

            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void Write(LogLevel level, string value)
            {
                LogCore.Write((LogEventLevel)level, value);
            }

            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void Write(LogLevel level, Exception exception, string value = "")
            {
                LogCore.Write((LogEventLevel)level, exception, value);
            }

            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void Write(LogLevel level, string value, params object[] args)
            {
                LogCore.Write((LogEventLevel)level, value, args);
            }

            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void Write(LogLevel level, string value, params ValueType[] args)
            {
                //Serilog logger supports passing valuetypes to avoid boxing objects
                if (LogCore.IsEnabled((LogEventLevel)level))
                {
                    object[] ar = args.Select(a => (object)a).ToArray();
                    LogCore.Write((LogEventLevel)level, value, ar);
                }
            }

            protected override void Free() => LogCore.Dispose();
        }
    }
}