BuiltInCertificateManager.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. using LibHac;
  2. using LibHac.Common;
  3. using LibHac.Fs;
  4. using LibHac.Fs.Fsa;
  5. using LibHac.FsSystem;
  6. using LibHac.Ncm;
  7. using LibHac.Tools.FsSystem;
  8. using LibHac.Tools.FsSystem.NcaUtils;
  9. using Ryujinx.Common.Configuration;
  10. using Ryujinx.Common.Logging;
  11. using Ryujinx.HLE.Exceptions;
  12. using Ryujinx.HLE.FileSystem;
  13. using Ryujinx.HLE.HOS.Services.Ssl.Types;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Runtime.CompilerServices;
  18. using System.Runtime.InteropServices;
  19. namespace Ryujinx.HLE.HOS.Services.Ssl
  20. {
  21. class BuiltInCertificateManager
  22. {
  23. private const long CertStoreTitleId = 0x0100000000000800;
  24. private readonly 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)";
  25. private static BuiltInCertificateManager _instance;
  26. public static BuiltInCertificateManager Instance
  27. {
  28. get
  29. {
  30. if (_instance == null)
  31. {
  32. _instance = new BuiltInCertificateManager();
  33. }
  34. return _instance;
  35. }
  36. }
  37. private VirtualFileSystem _virtualFileSystem;
  38. private IntegrityCheckLevel _fsIntegrityCheckLevel;
  39. private ContentManager _contentManager;
  40. private bool _initialized;
  41. private Dictionary<CaCertificateId, CertStoreEntry> _certificates;
  42. private object _lock = new object();
  43. private struct CertStoreFileHeader
  44. {
  45. private const uint ValidMagic = 0x546C7373;
  46. #pragma warning disable CS0649
  47. public uint Magic;
  48. public uint EntriesCount;
  49. #pragma warning restore CS0649
  50. public bool IsValid()
  51. {
  52. return Magic == ValidMagic;
  53. }
  54. }
  55. private struct CertStoreFileEntry
  56. {
  57. #pragma warning disable CS0649
  58. public CaCertificateId Id;
  59. public TrustedCertStatus Status;
  60. public uint DataSize;
  61. public uint DataOffset;
  62. #pragma warning restore CS0649
  63. }
  64. public class CertStoreEntry
  65. {
  66. public CaCertificateId Id;
  67. public TrustedCertStatus Status;
  68. public byte[] Data;
  69. }
  70. public string GetCertStoreTitleContentPath()
  71. {
  72. return _contentManager.GetInstalledContentPath(CertStoreTitleId, StorageId.BuiltInSystem, NcaContentType.Data);
  73. }
  74. public bool HasCertStoreTitle()
  75. {
  76. return !string.IsNullOrEmpty(GetCertStoreTitleContentPath());
  77. }
  78. private CertStoreEntry ReadCertStoreEntry(ReadOnlySpan<byte> buffer, CertStoreFileEntry entry)
  79. {
  80. string customCertificatePath = System.IO.Path.Join(AppDataManager.BaseDirPath, "system", "ssl", $"{entry.Id}.der");
  81. byte[] data;
  82. if (File.Exists(customCertificatePath))
  83. {
  84. data = File.ReadAllBytes(customCertificatePath);
  85. }
  86. else
  87. {
  88. data = buffer.Slice((int)entry.DataOffset, (int)entry.DataSize).ToArray();
  89. }
  90. return new CertStoreEntry
  91. {
  92. Id = entry.Id,
  93. Status = entry.Status,
  94. Data = data
  95. };
  96. }
  97. public void Initialize(Switch device)
  98. {
  99. lock (_lock)
  100. {
  101. _certificates = new Dictionary<CaCertificateId, CertStoreEntry>();
  102. _initialized = false;
  103. _contentManager = device.System.ContentManager;
  104. _virtualFileSystem = device.FileSystem;
  105. _fsIntegrityCheckLevel = device.System.FsIntegrityCheckLevel;
  106. if (HasCertStoreTitle())
  107. {
  108. using LocalStorage ncaFile = new LocalStorage(_virtualFileSystem.SwitchPathToSystemPath(GetCertStoreTitleContentPath()), FileAccess.Read, FileMode.Open);
  109. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile);
  110. IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel);
  111. using var trustedCertsFileRef = new UniqueRef<IFile>();
  112. Result result = romfs.OpenFile(ref trustedCertsFileRef.Ref(), "/ssl_TrustedCerts.bdf".ToU8Span(), OpenMode.Read);
  113. if (!result.IsSuccess())
  114. {
  115. // [1.0.0 - 2.3.0]
  116. if (ResultFs.PathNotFound.Includes(result))
  117. {
  118. result = romfs.OpenFile(ref trustedCertsFileRef.Ref(), "/ssl_TrustedCerts.tcf".ToU8Span(), OpenMode.Read);
  119. }
  120. if (result.IsFailure())
  121. {
  122. Logger.Error?.Print(LogClass.ServiceSsl, CertStoreTitleMissingErrorMessage);
  123. return;
  124. }
  125. }
  126. using IFile trustedCertsFile = trustedCertsFileRef.Release();
  127. trustedCertsFile.GetSize(out long fileSize).ThrowIfFailure();
  128. Span<byte> trustedCertsRaw = new byte[fileSize];
  129. trustedCertsFile.Read(out _, 0, trustedCertsRaw).ThrowIfFailure();
  130. CertStoreFileHeader header = MemoryMarshal.Read<CertStoreFileHeader>(trustedCertsRaw);
  131. if (!header.IsValid())
  132. {
  133. Logger.Error?.Print(LogClass.ServiceSsl, "Invalid CertStore data found, skipping!");
  134. return;
  135. }
  136. ReadOnlySpan<byte> trustedCertsData = trustedCertsRaw[Unsafe.SizeOf<CertStoreFileHeader>()..];
  137. ReadOnlySpan<CertStoreFileEntry> trustedCertsEntries = MemoryMarshal.Cast<byte, CertStoreFileEntry>(trustedCertsData)[..(int)header.EntriesCount];
  138. foreach (CertStoreFileEntry entry in trustedCertsEntries)
  139. {
  140. _certificates.Add(entry.Id, ReadCertStoreEntry(trustedCertsData, entry));
  141. }
  142. _initialized = true;
  143. }
  144. }
  145. }
  146. public bool TryGetCertificates(ReadOnlySpan<CaCertificateId> ids, out CertStoreEntry[] entries)
  147. {
  148. lock (_lock)
  149. {
  150. if (!_initialized)
  151. {
  152. throw new InvalidSystemResourceException(CertStoreTitleMissingErrorMessage);
  153. }
  154. bool hasAllCertificates = false;
  155. foreach (CaCertificateId id in ids)
  156. {
  157. if (id == CaCertificateId.All)
  158. {
  159. hasAllCertificates = true;
  160. break;
  161. }
  162. }
  163. if (hasAllCertificates)
  164. {
  165. entries = new CertStoreEntry[_certificates.Count];
  166. int i = 0;
  167. foreach (CertStoreEntry entry in _certificates.Values)
  168. {
  169. entries[i++] = entry;
  170. }
  171. return true;
  172. }
  173. else
  174. {
  175. entries = new CertStoreEntry[ids.Length];
  176. for (int i = 0; i < ids.Length; i++)
  177. {
  178. if (!_certificates.TryGetValue(ids[i], out CertStoreEntry entry))
  179. {
  180. return false;
  181. }
  182. entries[i] = entry;
  183. }
  184. return true;
  185. }
  186. }
  187. }
  188. }
  189. }