Cygwin/x

Описание

Cygwin представляет собой инструмент для портирования ПО UNIX в Windows и представляет собой библиотеку, которая реализует интерфейс прикладного программирования POSIX на основе системных вызовов Win32. Кроме того, Cygwin включает в себя инструменты разработки GNU для выполнения основных задач программирования, а также и некоторые прикладные программы, эквивалентные базовым программам UNIX. В 2001 году в Cygwin был включён пакет X Window System.

Кроме того, Cygwin содержит библиотеку MinGW, позволяющую работать с библиотекой Microsoft MSVCRT (Windows API); библиотека MinGW менее требовательна к объёму оперативной и дисковой памяти, распространяется под более свободной лицензией и может работать с любым программным обеспечением, но функциональные возможности спецификации POSIX реализованы в ней не так полно, как в Cygwin.

Red Hat реализует библиотеку Cygwin под лицензией GNU GPL, таким образом, её можно использовать только в программах, распространяемых под GPL. Для распространения программ, использующих библиотеку Cygwin под лицензией, отличной от GPL, необходимо приобретение лицензии у RedHat.

Starting in windowed mode (startx)

Use the standard X Window System
startx command and its associated
~/.xinitrc configuration file.

Run startx in a Cygwin shell:

$ startx

Full documentation for startx can be read with

man startx
.

You may
create a ~/.xinitrc from the template in /etc/X11/xinit/xinitrc and then customize
~/.xinitrc to start client programs and configure
your X server.

$ cp /etc/X11/xinit/xinitrc ~/.xinitrc
[edit ~/.xinitrc as desired]

Alternatively, if you just want to start a single client program (perhaps a window
manager), you don’t need to use a ~/.xinitrc, and
can start the client directly from startx, e.g.

$ startx /usr/bin/fvwm2

Проверка John the Ripper

В этом разделе мы проверим, какие устройства видит John the Ripper для использования во время брут-форса.

Опции на любой системе одинаковые, но помните, что в Windows для запуска John the Ripper нужно открыть Cygwin и в качестве исполнимого файла указывать ~/JtR/run/john.

Если вы запускаете в Linux установленный из стандартных репозиториев файл, то достаточно писать просто

john

Если вы запускаете скомпилированный из исходного кода файл, то перейдите в каталог с исполнимым файлом (в папке программы это директория run) и в качестве исполнимого файла указывайте

./john

Для просмотра устройств OpenCL используйте опцию —list=opencl-devices:

./john --list=opencl-devices

Как вы можете увидеть, у меня три устройства:

1 — видео ядро центрального процессора:

Platform #0 name: Intel(R) OpenCL HD Graphics, version: OpenCL 2.1 
    Device #0 (1) name:     Intel(R) Gen9 HD Graphics NEO
    Device vendor:          Intel(R) Corporation
    Device type:            GPU (LE)
    Device version:         OpenCL 2.1 NEO 

2 — дискретная видео карта

Platform #1 name: NVIDIA CUDA, version: OpenCL 1.2 CUDA 11.0.228
    Device #0 (2) name:     GeForce GTX 1050 Ti
    Device vendor:          NVIDIA Corporation
    Device type:            GPU (LE)
    Device version:         OpenCL 1.2 CUDA
    Driver version:         450.66 

3 — центральный процессор

Platform #2 name: Portable Computing Language, version: OpenCL 1.2 pocl 1.5, Release, LLVM 10.0.0, RELOC, SPIR, SLEEF, POCL_DEBUG
    Device #0 (3) name:     pthread-Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
    Device vendor:          GenuineIntel
    Device type:            CPU (LE)
    Device version:         OpenCL 1.2 pocl HSTR: pthread-x86_64-pc-linux-gnu-znver1
    Driver version:         1.5 

Аналогично в Windows:

~/JtR/run/john --list=opencl-devices

Как уже было сказано, John the Ripper не может просто работать с любыми поддерживаемыми алгоритмами на OpenCL — необходимо, чтобы для них был создан модуль. Поэтому некоторые алгоритмы можно взламывать только на центральном процессоре, а некоторые алгоритмы можно взламывать на видео карте или на центральном процессоре.

Список алгоритмов может различаться от ОС и от установленных зависимостей.

Чтобы посмотреть список поддерживаемых алгоритмов:

./john --list=formats

Список уместился не весь:

Чтобы посмотреть смотреть список алгоритмов для взлома на OpenCL:

./john --list=formats --format=opencl

Намного меньше, но Wi-Fi там есть.

Historia

Cygwin surge en 1995 como un proyecto de Steve Chamberlain (un ingeniero de Cygnus). Este ingeniero descubrió que Windows 95 y NT utilizan como formato para sus archivos objeto COFF y GNU incluía soporte para x86 y COFF. Esto supone, al menos en teoría, que no sería difícil adaptar el compilador GCC y crear un compilador cruzado que creara ejecutables para Windows. Tras demostrarlo en la práctica, los primeros prototipos comenzaron a aparecer rápidamente.

El siguiente paso era intentar configurar el compilador en un sistema Windows pero esto precisa una emulación de un entorno Unix para permitir que el script autoconf ejecutara correctamente. Por ello era necesario disponer de un shell como bash que facilitara los fork y la entrada/salida. Windows proporciona esa funcionalidad por lo que la biblioteca Cygwin únicamente necesitaba traducir las llamadas y gestionar de forma interna la información privada (descriptores de fichero…)

En 1996 se unieron más ingenieros al proyecto puesto que quedaba demostrado que Cygwin sería una herramienta muy útil para permitir que las herramientas de Cygnus ejecutaran en sistemas Windows (el mecanismo empleado hasta el momento era el uso del compilador DJGPP). En 1998, Cygnus empezó a distribuir el paquete Cygwin como un producto de suficiente interés por sí mismo.

What…

…is it?

Cygwin is:

  • a large collection of GNU and Open Source tools which provide functionality
    similar to a
    Linux distribution
    on Windows.
  • a DLL (cygwin1.dll) which provides substantial POSIX API functionality.

…isn’t it?

Cygwin is not:

  • a way to run native Linux apps on Windows. You must
    rebuild your application from source if you want it to run on Windows.
  • a way to magically make native Windows apps aware of UNIX
    functionality like signals, ptys, etc. Again, you need to build your apps from source
    if you want to take advantage of Cygwin functionality.

The Cygwin DLL currently works with all recent, commercially released
x86_64 versions of Windows, starting with Windows Vista. For more
information see the .

Installing Cygwin

Install Cygwin by running
setup-x86_64.exe

Use the setup program to perform a fresh install
or to update an existing installation.

Keep in mind that individual packages in the distribution are updated separately
from the DLL so the Cygwin DLL version is not useful as a general Cygwin
distribution release number.

32 bit Cygwin

Address space is a very limiting factor for Cygwin. These days, a
full 32 bit Cygwin distro is not feasible anymore, and will in all
likelihood fail in random places due to an issue with the fork(2)
system call.

Therefore we recommend using 32 bit Cygwin only in limited scenarios,
with only a minimum of necessary packages installed, and only if
there’s no way to run 64 bit Cygwin instead.

You have been warned. If you’re still sure you really need
a 32 bit Cygwin, and there’s absolutely no way around it, you may run
the setup-x86.exe installer.

The Cygwin DLL and utilities are Copyright Cygwin authors.
Other packages have other copyrights.
UNIX is a registered trademark of the Open Group in the United States
and other countries.

Install Cygwin (without admin rights)¶

This documentation is based on Oliver Doepner’s IT blog. Thank you for your work Oliver.

  1. Download setup-x86_64.exe.
  2. Open command line window (WIN+R and type ).
  3. Go to the download directory, e. g.:
    cd %USERPROFILE%\Downloads
    
  4. Run setup-x86_64.exe with the option:
    setup-x86_64.exe --no-admin
    
  5. During installation select the package.
  6. After installation open a Cygwin Terminal via Windows desktop shortcut.
  7. If you are behind an internet proxy (for example on a company environment) create for internet access:
    #!/usr/bin/env bash
    
    export http_proxy=http://your.proxy.server:proxy_port
    export https_proxy=http://your.proxy.server:proxy_port
    export ftp_proxy=http://your.proxy.server:proxy_port
    export no_proxy=localhost,.example.com
    
  8. Now you need a file called . Downlaod it via
    wget -O /usr/local/bin/cyg-get https://gitlab.com/cogline.v3/cygwin/raw/master/cyg-get?inline=false
    

    Alternatively, you can also create the file yourself.

    #!/usr/bin/env bash
    
    # import proxy definition
    [[ -r /etc/profile.d/proxy.sh ]] && . /etc/profile.d/proxy.sh
    
    readonly SUCCESS=
    readonly ERROR=1
    readonly E_WRONG_ARGS=2
    
    get_current_version()
    {
      cd /usr/local/bin
    
      ] && rm setup-x86_64.exe
      wget -q http://cygwin.com/setup-x86_64.exe
      chmod u+x setup-x86_64.exe
    }
    
    main()
    {
      local all_parameters="$@"
      local params="--no-admin"
      local packages=
    
      while :; do
        case "$1" in
          install)
            params="${params} -q -P"
            shift
            # list of comma separated packages
            packages=$(echo $@|sed -e 's/\s\+/,/g')
            params="${params}${packages}"
            ;;
          remove)
            params="${params} -q -x"
            shift
            packages=$(echo $@|sed -e 's/\s\+/,/g')
            params="${params}${packages}"
            ;;
          update)
            params="${params} -q -g"
            get_current_version
            ;;
          # Unknonw option
          -?*)
            echo "unknown option: $1"
            exit $E_WRONG_ARGS
            ;;
          # Default case: If no more options then break out of the loop.
          *)
            get_current_version
            break
        esac
        shift
      done
    
      run /usr/local/bin/setup-x86_64.exe ${params}
      exit $SUCCESS
    }
    
    main "$@"
    
  9. Make the script executable:
    chmod ugo+x /usr/local/bin/cyg-get
    
  10. On the Windows desktop create a copy of the Cygwin terminal shortcut, rename it Cygwin Setup.
  11. Edit the shortcut target, replace:
    mintty.exe -i /Cygwin-Terminal.ico -
    

    with

    mintty.exe -i /Cygwin-Terminal.ico /bin/bash -l -c 'cyg-get'
    
  12. Now test it and execute the desktop shortcut or run cyg-get from the Cygwin command
    prompt.

DRAWING ENGINE OPTIONS

-clipupdates num_boxes

Specify an optional threshold, above which the regions in a shadow
update operation will be collected into a GDI clipping region. The
clipping region is then used to do a single bit block transfer that is
constrained to the updated area by the clipping region. There is some
overhead involved in creating, installing, destroying, and removing
the clipping region, thus there may not be much benefit for a small
number of boxes (less than 10). It is even possible that this
functionality does not provide a benefit at any number of boxes; we
can only determine the usefulness of this feature through testing.
This option probably has limited effect on current Windows versions
as they already perform GDI batching.
-engine engine_type_id

This option, which is intended for Cygwin/X developers,
overrides the server’s automatically selected drawing engine type. This
parameter will be ignored if the specified drawing engine type is not
supported on the current system.

Default behavior is to select the drawing engine with optimum performance that
supports the specified depth and window configuration.

The engine type ids are:

1
Shadow GDI
4
Shadow DirectDraw Non-Locking

Cygwin

Cygwin — это набор инструментов, обеспечивающий Unix подобную среду в Windows. Здесь нельзя запускать уже существующие утилиты для Linux. Для того чтобы выполнить linux команду из Windows Cygwin, ее нужно сначала перекомпилировать.

Тем не менее пересобрано уже достаточно много программного обеспечения. Cygwin даст вам Linux подобную среду со многими утилитами, к которым вы уже привыкли в Linux. Его можно использовать как для стандартных утилит таких как команда cp windows, так и для подключения к удаленному серверу по ssh.

Установка Cygwin

Как и другие программы Windows, Cygwin устанавливается с помощью установщика в формате .exe. Скачать его можно на официальном сайте.

Для установки вам придется пройти несколько шагов мастера, по умолчанию программа будет установлена в C:\Cygwin:

С установочным пакетом не поставляется полный набор окружения. Оно будет загружено в процессе установки. В этом окне нужно выбрать сервер для загрузки компонентов:

Затем необходимо выбрать пакеты, которые нужно загрузить и установить. Доступно довольно-таки много программ и они рассортированы по категориям. Если вы не знаете нужен ли вам тот или иной пакет, оставьте значение по умолчанию. Вы сможете установить их потом:

Осталось только нажать Next для начала загрузки и завершения установки.

Добавление Cygwin в Path

После завершения установки, чтобы выполнить команды linux в windows с максимальным удобством, желательно добавить папку с исполняемыми файлами Cygwin в переменную среды Path.

Вы можете запустить терминал Cygwin, кликнув по ярлыку на рабочем столе. Откроется терминал с папкой C:\Cygwin\bin

Здесь можно выполнять все нужные linux команды в windows, но вы не сможете их выполнить в другой директории или другом терминале.

Чтобы решить эту проблему, необходимо добавить папку Cygwin в переменную Path. Откройте окно свойства системы с помощью сочетания клавиш Win+Pause/Break, затем выберите пункт Дополнительные параметры системы на левой панели:

На вкладке дополнительно выберите Переменные среды:

Найдите в списке переменную Path и нажмите Изменить:

Добавьте в конец строки вот такую запись:

Обратите внимание, что все пути должны быть разделены точкой с запятой. Осталось нажать Ок и тестировать выполнение Linux команд в Windows

Чем различаются John the Ripper и Hashcat

1.

Hashcat для брут-форса может использовать видеокарту, центральный процессор (ЦП) или всё вместе.

John the Ripper может использовать что-то одно: или видеокарту, или видео ядро ЦП, или только ЦП.

2.

Hashcat может использовать видеокарту для взлома любых поддерживаемых алгоритмов.

John the Ripper для взлома на видеокарте поддерживает только некоторые виды алгоритмов.

3.

Если у вас несколько видеокарт, Hashcat «из коробки» поддерживает работу сразу с несколькими устройствами и по умолчанию разбивает задачу на нужное количество потоков и размер каждой этой задачи привязан к мощности видеокарты.

John the Ripper может работать с несколькими видеокартами, но по умолчанию разбивка задачи на несколько видеокарт поддерживается только для одного алгоритма.

4.

Для Hashcat не имеет значение, как вы её установили: собрали из исходного кода или скачали бинарный файл.

Для John the Ripper очень важно самому собрать бинарный файл, поскольку в этом случае учитывается специфика вашей системы. В результате при компиляции будут указаны поддерживаемые процессором наборы команд, например, AVX2 вместо дефолтного AVX, что в конечном счёте очень значительно скажется на производительности — для некоторых алгоритмов благодаря этому достигается ускорение взлома в 2 раза! Либо напротив, скомпилированные на более новом железе исполнимые файлы John могут не работать на некоторых компьютерах. 5.

5.

Для Hashcat обязательно нужно указать тип хеша.

John the Ripper определяет хеш самостоятельно, либо можно явно указать формат хеша.

6.

Синтаксис команд и опций сильно различается.

7.

О взломе пароля в John the Ripper на видеокарте нужно знать, что брут-форс на графической карте требует много времени для запуска — это заметно даже для бенчмарка. Поэтому если вам нужно выполнить множество коротких сессий, то иногда рациональнее использовать центральный процессор, взлом на котором запускается немедленно.

DESCRIPTION

XWinXWinrc
/etc/X11/system.XWinrc
$HOME/.XWinrcsystem.XWinrc$HOME/.XWinrc

With the .XWinrc configuration file it is possible to do the
following:

1- To include items into the menu associated with the XWin icon
which is in the Windows system tray. This feature functions in
all XWin modes that have such tray icon.

2- To include items into the menu which is associated with the
Windows window that XWin -multiwindow produces for each
top-level X-window. That can be done both for the generic case and
for particular programs.

3- To change the icon that is associated to the Windows window
that XWin -multiwindow produces for each top-level X-window.
Again, that can be done both for the generic case and for particular
programs. The new icons associated should be Windows format
icons .ico.

4- To change the style that is associated to the Windows window
that -multiwindow produces for each top-level X window. Again,
that can be done both for the generic case and for particular programs.

Style Instructions

STYLES {

class-or-name-of-window style-keyword-1 style-keyword-2 style-keyword-3
  
}

Associates specific styles to a specified window class or name
in -multiwindow mode. If multiple class or name matches occur,
for a window, only the first one will be used.

The style keywords indicate the following:

style-keyword-1

TOPMOST

Open the class or name above all NOTOPMOST Microsoft Windows
MAXIMIZE

Start the class or name fullscreen.
MINIMIZE

Start the class or name iconic.
BOTTOM

Open the class or name below all Windows windows.

style-keyword-2

NOTITLE

No Windows title bar, for the class or name.
OUTLINE

No Windows title bar and just a thin-line border, for the class or name.
NOFRAME

No Windows title bar or border, for the class or name.

style-keyword-3

SKIPTASKBAR

Omit the class or name from being listed in the Windows taskbar.

Up to one keyword from each of these three groups can be used. Not all
groups need be used, and the keywords can be given in any order.

Cygwin Overview

Cygwin acts as an emulation layer providing substantial POSIX (Portable Operating System Interface) system call functionality, and a collection of tools, which provide a Linux look and feel. With Cygwin installed, users have access to many standard UNIX utilities. Cygwin can help you execute all the UNIX commands on Windows PC which is always a concern for developers, specially the developers working on Linux servers.

Cygwin’s POSIX compatibility does not mesh well with the native Windows API. If you mix POSIX calls with Windows calls in your program it is possible that you will see uneven results. In particular, Cygwin signals will not work with Windows functions which accept filenames may be confused by Cygwin’s support for long filenames.

In this article I will be talking of its installation and listing some of the common features of Cygwin also the native UNIX tasks that can be done on Windows PC using this application.

История

Работа над проектом Cygwin была начата в 1995 году Стивом Чемберленом (англ. Steve Chamberlain), программистом Cygnus, заметившим, что Windows NT и Windows 95 используют в качестве формата объектных файлов формат COFF. К тому времени в GNU уже была реализована поддержка архитектуры x86, COFF, а также библиотека языка C newlib; таким образом, по крайней мере теоретически, не представляло затруднений получить из GCC кросс-компилятор, который бы создавал исполняемые файлы Windows. Это оказалось несложным и на практике. Вскоре появился прототип.

Следующим шагом было заставить компилятор работать в Windows, но для этого была необходима эмуляция многих функций Unix: к примеру, должен был работать скрипт GNU configure. Этот скрипт нуждается в оболочке типа bash, которая, в свою очередь, требует наличия стандартных потоков ввода-вывода и системного вызова fork. Windows располагает подобными функциональными возможностями, и библиотека Cygwin лишь транслирует вызовы, исходящие от программ, управляя определёнными видами данных, такими как файловые дескрипторы.

В 1996 году к проекту Cygwin присоединились и другие программисты, так как стало очевидным, что Cygwin сделает возможным использование инструментов Cygnus на системах с Windows (до этого намечалось использовать DJGPP). Этот вариант был особенно привлекательным, ведь кросскомпиляция могла бы производиться в трёх направлениях: можно было использовать мощную станцию Sun для сборки Windows-кросскомпилятора MIPS, что позволяло значительно экономить время. С 1998 года Cygnus предлагает пакет Cygwin в качестве самостоятельного продукта.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *