aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.HLE/HOS/Services/Ssl/BuiltInCertificateManager.cs
blob: 5d2e06a4fc82e6450cb5cfd0c6cb4983cd9b1009 (plain) (blame)
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
using LibHac;
using LibHac.Common;
using LibHac.Fs;
using LibHac.Fs.Fsa;
using LibHac.FsSystem;
using LibHac.Ncm;
using LibHac.Tools.FsSystem;
using LibHac.Tools.FsSystem.NcaUtils;
using Ryujinx.Common.Configuration;
using Ryujinx.Common.Logging;
using Ryujinx.HLE.Exceptions;
using Ryujinx.HLE.FileSystem;
using Ryujinx.HLE.HOS.Services.Ssl.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Ryujinx.HLE.HOS.Services.Ssl
{
    class BuiltInCertificateManager
    {
        private const long CertStoreTitleId = 0x0100000000000800;

        private const string CertStoreTitleMissingErrorMessage = "CertStore system title not found! SSL CA retrieving will not work, provide the system archive to fix this error. (See https://github.com/Ryujinx/Ryujinx/wiki/Ryujinx-Setup-&-Configuration-Guide#initial-setup-continued---installation-of-firmware for more information)";

        private static BuiltInCertificateManager _instance;

        public static BuiltInCertificateManager Instance
        {
            get
            {
                _instance ??= new BuiltInCertificateManager();

                return _instance;
            }
        }

        private VirtualFileSystem _virtualFileSystem;
        private IntegrityCheckLevel _fsIntegrityCheckLevel;
        private ContentManager _contentManager;
        private bool _initialized;
        private Dictionary<CaCertificateId, CertStoreEntry> _certificates;

        private readonly object _lock = new();

        private struct CertStoreFileHeader
        {
            private const uint ValidMagic = 0x546C7373;

#pragma warning disable CS0649 // Field is never assigned to
            public uint Magic;
            public uint EntriesCount;
#pragma warning restore CS0649

            public readonly bool IsValid()
            {
                return Magic == ValidMagic;
            }
        }

        private struct CertStoreFileEntry
        {
#pragma warning disable CS0649 // Field is never assigned to
            public CaCertificateId Id;
            public TrustedCertStatus Status;
            public uint DataSize;
            public uint DataOffset;
#pragma warning restore CS0649
        }

        public class CertStoreEntry
        {
            public CaCertificateId Id;
            public TrustedCertStatus Status;
            public byte[] Data;
        }

        public string GetCertStoreTitleContentPath()
        {
            return _contentManager.GetInstalledContentPath(CertStoreTitleId, StorageId.BuiltInSystem, NcaContentType.Data);
        }

        public bool HasCertStoreTitle()
        {
            return !string.IsNullOrEmpty(GetCertStoreTitleContentPath());
        }

        private CertStoreEntry ReadCertStoreEntry(ReadOnlySpan<byte> buffer, CertStoreFileEntry entry)
        {
            string customCertificatePath = System.IO.Path.Join(AppDataManager.BaseDirPath, "system", "ssl", $"{entry.Id}.der");

            byte[] data;

            if (File.Exists(customCertificatePath))
            {
                data = File.ReadAllBytes(customCertificatePath);
            }
            else
            {
                data = buffer.Slice((int)entry.DataOffset, (int)entry.DataSize).ToArray();
            }

            return new CertStoreEntry
            {
                Id = entry.Id,
                Status = entry.Status,
                Data = data,
            };
        }

        public void Initialize(Switch device)
        {
            lock (_lock)
            {
                _certificates = new Dictionary<CaCertificateId, CertStoreEntry>();
                _initialized = false;
                _contentManager = device.System.ContentManager;
                _virtualFileSystem = device.FileSystem;
                _fsIntegrityCheckLevel = device.System.FsIntegrityCheckLevel;

                if (HasCertStoreTitle())
                {
                    using LocalStorage ncaFile = new(VirtualFileSystem.SwitchPathToSystemPath(GetCertStoreTitleContentPath()), FileAccess.Read, FileMode.Open);

                    Nca nca = new(_virtualFileSystem.KeySet, ncaFile);

                    IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel);

                    using var trustedCertsFileRef = new UniqueRef<IFile>();

                    Result result = romfs.OpenFile(ref trustedCertsFileRef.Ref, "/ssl_TrustedCerts.bdf".ToU8Span(), OpenMode.Read);

                    if (!result.IsSuccess())
                    {
                        // [1.0.0 - 2.3.0]
                        if (ResultFs.PathNotFound.Includes(result))
                        {
                            result = romfs.OpenFile(ref trustedCertsFileRef.Ref, "/ssl_TrustedCerts.tcf".ToU8Span(), OpenMode.Read);
                        }

                        if (result.IsFailure())
                        {
                            Logger.Error?.Print(LogClass.ServiceSsl, CertStoreTitleMissingErrorMessage);

                            return;
                        }
                    }

                    using IFile trustedCertsFile = trustedCertsFileRef.Release();

                    trustedCertsFile.GetSize(out long fileSize).ThrowIfFailure();

                    Span<byte> trustedCertsRaw = new byte[fileSize];

                    trustedCertsFile.Read(out _, 0, trustedCertsRaw).ThrowIfFailure();

                    CertStoreFileHeader header = MemoryMarshal.Read<CertStoreFileHeader>(trustedCertsRaw);

                    if (!header.IsValid())
                    {
                        Logger.Error?.Print(LogClass.ServiceSsl, "Invalid CertStore data found, skipping!");

                        return;
                    }

                    ReadOnlySpan<byte> trustedCertsData = trustedCertsRaw[Unsafe.SizeOf<CertStoreFileHeader>()..];
                    ReadOnlySpan<CertStoreFileEntry> trustedCertsEntries = MemoryMarshal.Cast<byte, CertStoreFileEntry>(trustedCertsData)[..(int)header.EntriesCount];

                    foreach (CertStoreFileEntry entry in trustedCertsEntries)
                    {
                        _certificates.Add(entry.Id, ReadCertStoreEntry(trustedCertsData, entry));
                    }

                    _initialized = true;
                }
            }
        }

        public bool TryGetCertificates(
            ReadOnlySpan<CaCertificateId> ids,
            out CertStoreEntry[] entries,
            out bool hasAllCertificates,
            out int requiredSize)
        {
            lock (_lock)
            {
                if (!_initialized)
                {
                    throw new InvalidSystemResourceException(CertStoreTitleMissingErrorMessage);
                }

                requiredSize = 0;
                hasAllCertificates = false;

                foreach (CaCertificateId id in ids)
                {
                    if (id == CaCertificateId.All)
                    {
                        hasAllCertificates = true;

                        break;
                    }
                }

                if (hasAllCertificates)
                {
                    entries = new CertStoreEntry[_certificates.Count];
                    requiredSize = (_certificates.Count + 1) * Unsafe.SizeOf<BuiltInCertificateInfo>();

                    int i = 0;

                    foreach (CertStoreEntry entry in _certificates.Values)
                    {
                        entries[i++] = entry;
                        requiredSize += (entry.Data.Length + 3) & ~3;
                    }

                    return true;
                }
                else
                {
                    entries = new CertStoreEntry[ids.Length];
                    requiredSize = ids.Length * Unsafe.SizeOf<BuiltInCertificateInfo>();

                    for (int i = 0; i < ids.Length; i++)
                    {
                        if (!_certificates.TryGetValue(ids[i], out CertStoreEntry entry))
                        {
                            return false;
                        }

                        entries[i] = entry;
                        requiredSize += (entry.Data.Length + 3) & ~3;
                    }

                    return true;
                }
            }
        }
    }
}