aboutsummaryrefslogtreecommitdiff
path: root/lib/VNLib.Plugins.Extensions.Loading/src/ManagedPasswordHashing.cs
blob: 28b3a0879f377bcc45e67664e4b502fb3c34b8c3 (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
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Extensions.Loading
* File: ManagedPasswordHashing.cs 
*
* ManagedPasswordHashing.cs is part of VNLib.Plugins.Extensions.Loading which 
* is part of the larger VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Extensions.Loading is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* VNLib.Plugins.Extensions.Loading 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/

using System;
using System.Linq;
using System.Text.Json;
using System.Collections.Generic;

using VNLib.Hashing;
using VNLib.Utils;
using VNLib.Utils.Memory;
using VNLib.Utils.Extensions;
using VNLib.Plugins.Essentials.Accounts;

namespace VNLib.Plugins.Extensions.Loading
{

    /// <summary>
    /// A plugin configurable <see cref="IPasswordHashingProvider"/> managed implementation. Users may load custom 
    /// assemblies backing instances of this class or configure the <see cref="PasswordHashing"/> implementation
    /// </summary>
    [ConfigurationName(LoadingExtensions.PASSWORD_HASHING_KEY, Required = false)]
    public sealed class ManagedPasswordHashing : IPasswordHashingProvider
    {
        public ManagedPasswordHashing(PluginBase plugin, IConfigScope config)
        {
            //Check for custom hashing assembly
            if (config.TryGetValue(LoadingExtensions.CUSTOM_PASSWORD_ASM_KEY, out JsonElement el))
            {
                string customAsm = el.GetString() ?? throw new KeyNotFoundException("You must specify a string file path for your custom password hashing assembly");

                //Load the custom assembly
                IPasswordHashingProvider userProvider = plugin.CreateServiceExternal<IPasswordHashingProvider>(customAsm);

                //Store
                Passwords = new CustomPasswordHashingAsm(userProvider);
            }
            else
            {
                Passwords = plugin.GetOrCreateSingleton<SecretProvider>().Passwords;
            }
        }

        public ManagedPasswordHashing(PluginBase plugin)
        {
            //Only configure a default password impl
            Passwords = plugin.GetOrCreateSingleton<SecretProvider>().Passwords;
        }

        /// <summary>
        /// The underlying <see cref="IPasswordHashingProvider"/>
        /// </summary>
        public IPasswordHashingProvider Passwords { get; }

        ///<inheritdoc/>
        public bool Verify(ReadOnlySpan<char> passHash, ReadOnlySpan<char> password) => Passwords.Verify(passHash, password);

        ///<inheritdoc/>
        public bool Verify(ReadOnlySpan<byte> passHash, ReadOnlySpan<byte> password) => Passwords.Verify(passHash, password);

        ///<inheritdoc/>
        public PrivateString Hash(ReadOnlySpan<char> password) => Passwords.Hash(password);

        ///<inheritdoc/>
        public PrivateString Hash(ReadOnlySpan<byte> password) => Passwords.Hash(password);

        ///<inheritdoc/>
        public ERRNO Hash(ReadOnlySpan<byte> password, Span<byte> hashOutput) => Passwords.Hash(password, hashOutput);

        sealed class CustomPasswordHashingAsm : IPasswordHashingProvider
        {
            private readonly IPasswordHashingProvider _provider;

            public CustomPasswordHashingAsm(IPasswordHashingProvider loader) => _provider = loader;

            /*
             * Password hashing isnt a super high performance system
             * so adding method overhead shouldnt be a large issue for the 
             * asm wrapper providing unload protection
             */

            public PrivateString Hash(ReadOnlySpan<char> password) => _provider.Hash(password);

            public PrivateString Hash(ReadOnlySpan<byte> password) => _provider.Hash(password);

            public ERRNO Hash(ReadOnlySpan<byte> password, Span<byte> hashOutput) => _provider.Hash(password, hashOutput);

            public bool Verify(ReadOnlySpan<char> passHash, ReadOnlySpan<char> password) => _provider.Verify(passHash, password);

            public bool Verify(ReadOnlySpan<byte> passHash, ReadOnlySpan<byte> password) => _provider.Verify(passHash, password);
        }

        private sealed class SecretProvider : VnDisposeable, ISecretProvider
        {
            private readonly IAsyncLazy<byte[]> _pepper;

            public PasswordHashing Passwords { get; }

            public SecretProvider(PluginBase plugin, IConfigScope config)
            {
                IArgon2Library? safeLib = null;

                if(config.TryGetValue("lib_path", out JsonElement manualLibPath))
                {
                    SafeArgon2Library lib = VnArgon2.LoadCustomLibrary(manualLibPath.GetString()!, System.Runtime.InteropServices.DllImportSearchPath.SafeDirectories);
                    _ = plugin.RegisterForUnload(lib.Dispose);
                    safeLib = lib;
                }

                //Load default library if the user did not explictly specify one
                safeLib ??= VnArgon2.GetOrLoadSharedLib();

                Argon2ConfigParams costParams = new();

                if (config.TryGetValue("args", out JsonElement el))
                {
                    //Convert to dict
                    IReadOnlyDictionary<string, JsonElement> hashingArgs = el.EnumerateObject().ToDictionary(static k => k.Name, static v => v.Value);

                    costParams = new()
                    {
                        HashLen = hashingArgs["hash_len"].GetUInt32(),
                        MemoryCost = hashingArgs["memory_cost"].GetUInt32(),
                        Parallelism = hashingArgs["parallelism"].GetUInt32(),
                        SaltLen = (int)hashingArgs["salt_len"].GetUInt32(),
                        TimeCost = hashingArgs["time_cost"].GetUInt32()
                    };
                }

                //Create passwords with the configuration and library
                Passwords = PasswordHashing.Create(safeLib, this, in costParams);

                //Get the pepper from secret storage
                _pepper = plugin.GetSecretAsync(LoadingExtensions.PASSWORD_HASHING_KEY)
                    .ToLazy(static sr => sr.GetFromBase64());
            }

            public SecretProvider(PluginBase plugin)
            {
                //Load passwords with default config
                Passwords = PasswordHashing.Create(this, new Argon2ConfigParams());

                //Get the pepper from secret storage
                _pepper = plugin.GetSecretAsync(LoadingExtensions.PASSWORD_HASHING_KEY)
                    .ToLazy(static sr => sr.GetFromBase64());
            }

            ///<inheritdoc/>
            public int BufferSize
            {
                get
                {
                    Check();
                    return _pepper.Value.Length;
                }
            }

            public ERRNO GetSecret(Span<byte> buffer)
            {
                Check();
                //Coppy pepper to buffer
                _pepper.Value.CopyTo(buffer);
                //Return pepper length
                return _pepper.Value.Length;
            }

            protected override void Check()
            {
                base.Check();
                _ = _pepper.Value;
            }

            protected override void Free()
            {
                if (_pepper.Completed)
                {
                    //Clear the pepper if set
                    MemoryUtil.InitializeBlock(_pepper.Value.AsSpan());
                }
            }
        }
    }
}