#!/usr/bin/env python
""" pentest.py

Copyright (C) 2016  Dale V. Patterson (wraith.wireless@yandex.com)

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 3 of the License, or (at your option) any later
version.

Redistribution and use in source and binary forms, with or without
modifications, are permitted provided that the following conditions are met:
 o Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
 o Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 o Neither the name of the orginal author Dale V. Patterson nor the names of
    any contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

Example for setting up a wireless environment - must be done as root

"""

from __future__ import print_function  # python 2to3 compability
import argparse as ap                  # cli arg. parsing
import time                            # sleeping
import sys                             # cli exiting
import pyric                           # pyric error (and ecode EUNDEF)
import pyric.pyw as pyw                # for iw functionality
import pyric.utils.hardware as hw      # for chipset/driver
from pyric.utils.channels import rf2ch # rf to channel conversion

def execute(dev):
    print('Setting up...')
    # ensure dev is a wireless interfaces
    ifaces = pyw.interfaces()
    wifaces = pyw.winterfaces()
    if dev not in ifaces:
        print("Device {0} is not valid, use one of {1}".format(dev,ifaces))
        return
    elif dev not in wifaces:
        print("Device {0} is not wireless, use one of {1}".format(dev,wifaces))

    # get a Card & info for dev
    print("Regulatory Domain currently: ", pyw.regget())
    dinfo = pyw.devinfo(dev)
    card = dinfo['card']
    pinfo = pyw.phyinfo(card)
    driver = hw.ifdriver(card.dev)
    chipset = hw.ifchipset(driver)

    # bring the card down and change the mac
    pyw.down(card)
    pyw.macset(card,'00:03:93:57:54:46')

    # print details
    msg = "Using {0} currently in mode: {1}\n".format(card,dinfo['mode'])
    msg += "\tDriver: {0} Chipset: {1}\n".format(driver,chipset)
    if dinfo['mode'] == 'managed':
        msg += "\tcurrently on channel {0} width {1}\n".format(rf2ch(dinfo['RF']),
                                                               dinfo['CHW'])
    msg += "\tSupports modes {0}\n".format(pinfo['modes'])
    msg += "\tSupports commands {0}".format(pinfo['commands'])
    msg += "\thw addr {0}".format(pyw.macget(card))
    print(msg)

    # prepare a virtual interface named pent0 in monitor mode
    # delete all ifaces on the phy to avoid interference
    # bring the card up when down
    print('Preparing pent0 for monitor mode')
    pdev = 'pent0'
    pcard = pyw.devadd(card, pdev, 'monitor')
    for iface in pyw.ifaces(card):
        if iface[0].dev != pcard.dev:
            print("deleting {0} in mode {1}".format(iface[0],iface[1]))
            pyw.devdel(iface[0])
    pyw.up(pcard)
    print("Using", pcard)

    print("Setting channel to 6 NOHT")
    pyw.chset(pcard,6,None)
    msg = "Virtual interface {0} in monitor mode on ch 6".format(pcard)
    print(msg + ", using hwaddr: {0}".format(pyw.macget(pcard)))

    # DO stuff here
    try:
        print('Now ready to do stuff')
        print('For example, run wireshark to verify card is seeing all packets')
        print('Hit Ctrl-C to quit and restore')
        while True: time.sleep(1)
    except KeyboardInterrupt:
        pass

    # restore original
    print('Restoring', card, 'mode =', dinfo['mode'], 'mac =', dinfo['mac'])
    card = pyw.devadd(pcard,card.dev,dinfo['mode'])
    print('Deleting', pcard)
    pyw.devdel(pcard)
    pyw.macset(card,dinfo['mac'])
    pyw.up(card)
    print("card ", card, " restored")

if __name__ == '__main__':
    # create arg parser and parse command line args
    print("Wireless Pentest Environment using PyRIC v{0}".format(pyric.version))
    argp = ap.ArgumentParser(description="Wireless Pentest")
    argp.add_argument('-d','--dev',help="Pentesting Wireless Device")
    args = argp.parse_args()
    try:
        dname = args.dev
        if dname is None:
            print("usage: python pentest.py -d <dev>")
            sys.exit(0)
        else:
            execute(dname)
    except pyric.error as e:
        print(e)