We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 7
2eiaiz021
Learning by practicing: Weting a Palo Ato Firewall REST API Client in Pyinon
Cres blog Accu
Learning by practicing
Learning is an ongoing activity ... practicing makes it fun
Thre J 162018
Writing a Palo Alto Firewall REST API Client in
Python
No lo dudes, tii puec
« Abre tu Cuenta de At
por Internet en pocos clit
Banclomb
hile worieng on code to configure my Palit instances automatically in Amazon
[AWS, I needed to rte functions that woula interac with the Palo Ako gatenay
(eda/remeve rules, create objecte, commit changes, et.) Palo Ake makes avalable
{| numoer of documents avaliable to help with tis, but din’ find any one source
that would explain ene process completely af now to send commanes, Interpret
yn codes and then parse outputs returned, anc so 1 wanted to dacument ts
Palo Alto gateways have @ REST API avalable which allows you to send commands
‘over HTTPS (or HTTP), and then retuins the output in XML format making i ey to
parse tough and extract the Information
REST Request and Response Structure
“The structure for the API requests i
etp(s)://hostnane/api/2request-paraneters-values
+ hostname: hostname of IP adcress ofthe Palo Alto gatenay.
+ request: Can be one of 9 different request types, we wil mainly use
keygen, config, op, and commit. There are others that allow you to
‘expor/import configuration or logs an ether information. The request has
te be specifies wth the type paramater, for example: type=keygen!
+ parameters: Each request type has ciferent parameters available tt
For example the ‘config’ request has the ‘acon’ parameter which can be
set to values such as edit set,deletaet. Inthe format
(action=setaction=eciaction=celete,etc.). The op (operation) request
has commands associated with wt such as save, show, request, ae
+ values: Some parameter would require values that need to be provided,
and these go here, For example, adding a new rule woulé require
specifying parameters such as source, cestination,servcete.
rea nt, the gateway will send back a response which consists of to
on
‘code’ whieh is 2 numerical value. For example error codes 19 and 20 mean
success, and other caces would spect ifferent error reasons (For example,
2, Results, Certain commanes would require a response fom the gateway such
238 listing specif rules or objects, and these would be shown under the results
Both these parts are provides In an XML tree format:
sy
response state
fnsgrcomand succe
“lresponse>
For more detals on the REST API structure, ast of all diferent requests and
responses, refer tothe PAN-OS XML APT Usage Guide.
hips: ww securtyrik.con20 16/07Iwing-pal-alofirewal-rest-apihiml
+ Abdul
Nik Alleyne, MSc 1 CISSP |
Sealine
subscribe
Delivered by Fesdurer
‘razon Read the sample cote
Iastoring TShark Networs Foren.
(Gea a copy: Get the Sample Craters
View PDP veo of yee
wr2evain021
Learning by practicing: Weting a Palo Ato Firewall REST API Client in Pyinon
Determining Command Syntax
“The XML API guide from Palo At is very helpful in finding out the raquest types,
parameters availabe, as well 2s error codes and notes on the cesponse structures
However, thare are some things that might not be Included In the guide, such as the
Structure of the values feld that needs to be passed for cern corsmands. The
easiest way to fin that out isto enable debugging inthe CLI, and then execute the
command that would achiave the result you are looking for. Pale Als wil then show
yeu the syntax it passed, and you can use that as a medal
For example, to get the syntax for adding a security rule:
1. Turn on debugging "éebua ci ont
2, Go into configure mode By running “configure
4, From the output,
cary:
arts highlighted in red are what you would need to
request cade"set” obo" /contig/devices/entry/|@nane="Localhost.Localdonain’}/
5. The XML API guide wil alse provide guidance on the values its expecting. For
the "set" action under the "config" type, It els you that it expects two parts for
Values: xpath and element
netps:/1/aps/ypeccontighacton=setakey-xpa
*Jeontig/sevices/entey|Soane=
Authentication
To be able to send requests tothe gateway, you need an access key to be Include in
leach request. Once you have the key, the key should be included in every request
fang ls lsted ght after the request, for example:
hnttp(s):/hostnane/apt/typeconFighact on-set Akey-KEWALUEREnd=
eats)
$1.000.0
Oye ue
Dee cna
To generate a key, send the folowing request
gateway:
hps:ww- securtyrik.con20 6/07Iwing-pal-aloirewal-rest-api hil
nmiete
Sul orensicly Capable Netware
inasructre
“het ams evetgatne Tus
Dubdinga Pros Capabe Nero
(rad Teat neo ie Cheap
ythanSeapy DNS Spuoiog Tatar
"ROM PAPERLES TO PLASTICLISS, EX
Soot there
eet
gr
> 2021 (14)
» 2020 (35)
anpavaiz021 Learning by practicing: Weting a Palo Ato Firewall REST API Client in Pyinon
Ineto(s):/ostnane/api/Meypeskeygenduseruserranctpassnordepassword
(ere username and password are the credentials ofan already configured
‘administrator secount on the gateny).
The response wil contain the access key. Sample response:
“key UHES6967Hbx1gs6 FD sAf234ASC2E—ZERIVONIZAHL/Key>
results
Teesponses
Sending a request in Python
With this information In ming, we ean now turn to Python to write the code that will
send requests to Pale Alto gateways and than Interpret the responses. Le's walk
{through the example of writing 2 function which wil let us add securty rules on a
Palo Ato gateway.
Constructing a request
The request we wil be sending wil be as follows (which covers all parts Inthe
request syntax mentioned above)
url = Retpss//"sps_Aprende keys", keyt"B° rr 18 urleneode (paransters)
Each ofthe items highlighted in red are variables that need tobe fled In te complete
the request
+ aLIp: holds the IP acdess (or hostname) af the gateway.
+ ema type of request and parameter assoclatec with the function we are
ying t0 perform. In ths case, we are wring 2 function to add securty
rules tothe gateway, and so the type 's config and action is set, so:
nd = */aps ey
confighactdon=seta”
+ pa_koy: access kay we obtained forthe gateway.
+ urlb.utencode(parameters): there are two parts here to consider:
+ parameters: holds the last part of the request which are the
Values requires for the command or request we are sending to
the gateway, In case of adding a role, tere are two values that
need to be sent
1. xpath: path tothe item we are modifying on the Palo Ao
gateway.
2. element: contains the values of the atferent options inthe rule
(Gource/destination 1, action, service, ete)
ulib-urencode: since we are sending these requests over HTTP,
some characters need to be encoded so thatthe receiving end
an interpret them properly. Characters sue as space cannot be
sent os but have {o be changed to @ supported format
encode unetion trom the uri library alow us todo this, ons
requires thet values passed to it are passes In a python
ievonary format
hps:ww- securtyrik.con20 6/07Iwing-pal-aloirewal-rest-api hil
» 2019 (27)
> 2016 (24)
> 2017 (64)
2016 (42)
‘ecember (2)
November (8)
ocaber (3)
September (2)
‘gust (1)
uly (6)
‘AWS Securty: Automating Palo Ato
‘Sscuny rues
Weng 2 Pao Ako Firewall REST
Ia Chen Py.
Suling a Splunk Oashboare by
parang Pal Ato
Suing a mentonngeoltion
Parsing Plo Aka
Suing a monitoring solution ~
orwarting Pab
Bulding menitorng solution ~
Narseing che 0S
une (1)
prt (3)
Feseusry (1)
>aruary (6)
> 2015 (86)
> 2014 (70)
p/w securtytube.net
hepfumencyoror8/
ENISA.
‘Open Secu Tralning
Fozzy Security
Honeynet Project
Coraan Beetha Wing Tutrat
ee
Additional Readings
‘Ss Reading Room
spf scr gov!
hep/fsosecunty.obgspot.c
hp ferensonseartycomy)
Igpf/secutyweesy eam
spe caoonie.comyblegs
hepa//securosscomyblog!
hip /tvestpost com
Isp fratecsecurty.sophes.cony
hep fbog.etser com
hepsi senneer omy
Morning star Secuty
InfoneeIncustry
(waurcrous 1Ps)
lcs Valor IP Bok
oergngthreats net emerging Boe
merginatheatsnet compromised bs
howsflesnt EMD
Imalvarecomsinistcom nots.
‘malwarscomaintst com
fryipis genera atest Backlist ot
Irvpsist es ates_Backst.ot
Shean com chinaceritLearning by practicing: Wrting a Palo Ato Firewall REST API Client in Pyinon
parameters = {‘xpath': “/config/devices/entry|@nane="Tocathost.tocaldonsin'}/\
Sending the request
(Once we nave constructed the request, we can send it using the urlopen function
from urlib2 ibrar
response ~ urllibz.vrlopen(sr)
In case you are connecting toa gateway with an untrusted SSL certificate, you wil
ned to tell the urlopen command to ignore the SSL certifcate check, otherwise the
command will throw an error. Te do this you can use the ssl brary In python to
croate a context that ignores the certifcate check and then pass itt the urlepen
function:
cox = sslscreate,seaule_conent()
Fesponse ~"urllibz-uriopen{urd, context=etx)
Parsing the Response in Python
In the previous section, we sent a request using the urlopen function, and specified
the reszonee variable to hold the return values from urlonen. ‘response’ inthis case
‘would Rold the values returned ‘rom the Palo Alte gateway 2s well as detals on the
response on the HTTP level. So we can use response.code for example to print ofthe
ITP status of aur request (200 for Okay, and almost everything else would indicate
Ifthe HTTP status retumed Is 200, then we can proceed to analyze the response
from the Pale Alt gateway, To do ths, we need to ead ths a: XML. Response read()
allows us to reac the contents ofthe respanse from Palo Alto, andthe fromstnng
function allows us to parse this n XML format (Need to import xml.etree.ElementTree
for this function, and I have used the syntax import xml etree ElementTree as Eto
snake It easier to reference):
contents EI fronsteing(respanse.read())
contents now wil hal the alo Alto response nan XML tree format which we can
parse easy, “contents on its own access the fst level, ‘contents(0) access the fst
member on the second level, contents(0{0] access the frst member In the second
(On each level, there are three values we can access: tag, attrib, and text. Consiger
the example of querying the Palo Ao gateway to list al configured service objects:
Request:
netps///aps/ypescontighactLonapetey-sxpathe/contig/devices/entry| rane
output:
“result total-counte"t> countet">
“service aoninesorin” eireyiee'26° tine
‘emery nares" tep >
“protocol
cport>6ic/port>
eea>
Tprotocol>
cfeneeys
2615/07/12 19:12:50"
hps:ww- securtyrik.conv20 6/07Iwring-pal-aloirewal-rest-api hil
rst.bom dos.
‘Byevetaherabine hte
‘Syevevecer abuse cn eabeolckat
Syererackerauce ch bot
Seale: abuse cn bade
amour drop oe
Sponnoutrgeorop Bt
[WaLIci0us Domains)
ybereime-trackenet aloha
‘malvarecemains.evgheu domains.
‘elwarscomaintstcom hosts
Imalvarecomsintst. com
[turtrockesobuse.c domalnblcdst
evetrackerabuse.o baddomains
5c High
SC Medium
TSC tow
Tor Gxt Nodes
Torro
MALICIOUS URLS}
‘rogue URLSE
POSING URLS)
openphisn
\wensites that you can use. cymonte is
Sn excelent one oft seorenes around
tes, check out
ps//sthub comyshine/owesame:
mmainare-analsis
1° and Oomain Reputation / Maicous
ety Repores
hepffeynan io
eps fw racordeature.cony/lva!
hspeifuiquerynet (URL Sean)
haps /nsttaneomy
tps fot aenvaut com
eps f/excrange afore elus. cory
eo)
heps/wwerconsys.0
psn shad oy
Iapsf/centralps.neticof
plows!
paar eaterowe. org
95 (fmalwccory
spawn hybnd-anayss.comy
rsp ans eduserlcas hon Port
Informaton).
Matnare /Matcous Ste Semis:
hspsif/matweesm)
hspofonsnanet/ Veitch
hp feyoererestrackenel!
tps /rersommarevackerabusechtrac
wor?
psa comfdetabace/
SINT Framewore
anpavaiz021 Learning by practicing: Weting a Palo Ato Firewall REST API Client in Pyinon
sentry nane="tep_A8ee>
“protocel>
“rouree-ports1-8559S4/seurce-port>
Sportonanecyport>
cep»
Iprotocol>
cfemeys
“entry nanee"top 465° adnine"adnin” oletytée"12°
“protocol adn
“port adnine
creep»
iprotocols
fservices
cfresuits
Tresponses
2016/07/12 19:01:60
sn” Strtylan" 12" tinen"2036/00/17 19:01:49"
code:
‘ef patoalte_service_#ind(ps_tp,p_key, protocol port)
1 Find if there are service objects that watch a certatn port and protocol t)
4 input? Polo alto gateway Ie, oto Alta Access Key, IP protocol type, and Pe
1 Output: Returns service abject nave if found on" Af there are mo etches
ctx = sel.crente_aefauls_contexc()
nd = */api/typoscontighactionegeta”
aranevers = {'upath’:~/contig/evices/entey [@nane=\"Jocalhost.1sealdonain\”
Sed = "etps://"spa_apsendsRey="spa_keys"B Fri urlencode(paraneters)
response = urlltbz.urlopen(urt, contextaetx)
Contents ET. #ronstring(respense.rea())
for £ in consents[o(8]
AF ie] ]-t3g = protocol
for j in i(8)(0)
Bf j.tag se "pore! and 3:text == port
Feit Lattribt ane]
return cesule
the response is frst formatted in XML so that it can be parsed, ané saved in variable
contents. Afterwards, we trate through all he entries two levels Gown using the
varable T, and subsequently two more levels down from | with the variable J.
Throughout this process, we are comparing the protocl and por values we are
reading wth the port ané protocol variables provide tothe function, The first of
these entries would be:
“Grotecel
tep>
crentey
In this case, the tag is etry attnb is @ dictionary ('name's'tzp_81'), se to access
the value of name’ we can do | If we wanted to go one level below, we would have
hps:ww- securtyrik.con20 6/07Iwing-pal-aloirewal-rest-api hil2evain021
Learning by practicing: Weting a Palo Ato Firewall REST API Client in Pyinon
reference if}, and then for example i0)tag would return “protocol & level below
sat would be i[0](0}, and that would give Us access to , and son,
Download
You can download the code from my athub page,
To use I, you only need to impor the palcato.oy In your code and then cal the
functions, The funetions will continue to be updated as I work to add more
functionality
Posty soa 20:84
Labels Pt to Pre, REST ML
10 comments:
[aM Atovme mse 1 ess | GcHAIHIREM uy 15, 2016 981035 88
{Good srt Abd Very god sti
ol
[Anonymous January 2, 2018 at 4:20 AM
Cen you help me to write code to import bulk of object groups using excel or ee
Realy
eps
Decco
oe cieennsm
Palo at devices as much oreasly tavesccess,
Homer th some notepcferct work you shoud be able to creat the
commands you nes to impot these soja sig the Lt (Chek tthe
foloning ink Nepsi//Wveploatonetworks.coms/ Conta
asia
Reply
6a
Bey
nase wile 2 program for 9
Realy
hps:ww- securtyrik.con20 6/07Iwing-pal-aloirewal-rest-api hil2evain021 Learning by practicing: Weting a Palo Ato Firewall REST API Client in Pyinon
Beh
|g Me Aeyme tse | EISSP | GCIAIMIREM Jarsey 7,202 t 10:39 04
with Pao Alto and scripting Look
fora future poston his op
OQ ems
|g Me Mevme se 1 eISSP | GCIAIMIREM arsay 2,202 at 48 A
Enter your coment.
Q comer
am) tyme
um (Gogh) sign
Ssubserbe to: ost Comment (tom)
‘Simple theme, Powered by Blogger.
htps:ww securtyrik.con20 6/07Iwring-pal-aloirewal-rest-api hil